Skip to content

Fix condition in realloc() implementation of Vec #5

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 40 additions & 2 deletions src/poolable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,21 @@ impl<T: Default + Clone> Realloc for Vec<T> {
use std::cmp::Ordering::*;

assert!(new_size > 0);
match new_size.cmp(&self.capacity()) {
Greater => self.resize(new_size, T::default()),
match new_size.cmp(&self.len()) {
Greater => {
self.reserve_exact(new_size - self.len());
debug_assert_eq!(self.capacity(), new_size);
self.resize(new_size, T::default());
debug_assert_eq!(self.len(), new_size);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this assert seems a bit redundant, but doesn't do much harm either.


// Check that resize() did not reserve additional space.
debug_assert_eq!(self.capacity(), new_size);
}
Less => {
self.truncate(new_size);
debug_assert_eq!(self.len(), new_size);
self.shrink_to_fit();
debug_assert_eq!(self.capacity(), new_size);
}
Equal => {}
}
Expand Down Expand Up @@ -74,3 +84,31 @@ where
}
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Regression test for `Realloc` trait implementation of `Vec`.
///
/// Previously `Realloc::realloc()` called `self.capacity()` instead
/// of `self.len()` when checking whether the vector should be expanded.
/// As a result, it sometimes attempted to shrink the vector
/// when it should be expanded, and effectively did nothing.
#[test]
fn realloc_vec() {
let mut v: Vec<u8> = Poolable::alloc(100);

for i in 1..100 {
let new_size = Poolable::capacity(&v) + i;
v.realloc(new_size);
assert_eq!(Poolable::capacity(&v), new_size);

// Length of the vectory and underlying buffer
// for poolable vectors should
// be exactly of the requested size.
assert_eq!(v.len(), new_size);
assert_eq!(v.capacity(), new_size);
}
}
}