Skip to content
Closed
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
30 changes: 29 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -824,8 +824,26 @@ impl<T> ThinVec<T> {
if old_len == self.capacity() {
self.reserve(1);
}
unsafe {
// SAFETY: reserve() ensures sufficient capacity.
self.push_reserved(val);
}
}

/// Appends an element to the back like `push`,
/// but assumes that sufficient capacity has already been reserved, i.e.
/// `len() < capacity()`.
///
/// # Safety
///
/// - Capacity must be reserved in advance such that `capacity() > len()`.
pub unsafe fn push_reserved(&mut self, val: T) {
let old_len = self.len();
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's at least debug_assert!(old_len < self.capacity()); for good measure.


unsafe {
ptr::write(self.data_raw().add(old_len), val);

// SAFETY: capacity > len >= 0, so capacity != 0, so this is not a singleton.
self.set_len_non_singleton(old_len + 1);
}
}
Expand Down Expand Up @@ -1927,11 +1945,21 @@ impl<T> Extend<T> for ThinVec<T> {
where
I: IntoIterator<Item = T>,
{
let iter = iter.into_iter();
let mut iter = iter.into_iter();
let hint = iter.size_hint().0;
if hint > 0 {
self.reserve(hint);
}
for x in iter.by_ref().take(hint) {
Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Probably put it inside the hint > 0 for consistency?

// SAFETY: `reserve(hint)` ensures the next `hint` calls of `push_reserved`
// have sufficient capacity.
unsafe {
self.push_reserved(x);
}
}

// if the hint underestimated the iterator length,
// push the remaining items with capacity check each time.
for x in iter {
self.push(x);
}
Expand Down