Skip to content

Commit

Permalink
Add shrink_to_fit
Browse files Browse the repository at this point in the history
Shamelessly stolen from fitzgen#37
  • Loading branch information
s1341 committed Sep 13, 2021
1 parent 72975c8 commit 51495cf
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,35 @@ impl<T> Arena<T> {
self.len = 0;
}

/// Reduces allocated space to the minimum possible to fit all the elements in the arena.
///
/// # Examples
///
/// ```
/// use generational_arena::Arena;
///
/// let mut arena = Arena::new();
/// arena.extend([1, 2, 3, 4, 5].iter().copied());
/// assert!(arena.capacity() >= 5);
/// arena.shrink_to_fit();
/// assert_eq!(arena.capacity(), 5);
/// ```
pub fn shrink_to_fit(&mut self) {
self.items.truncate(self.items.iter().rposition(|entry| matches!(entry, Entry::Occupied { .. })).map(|n| n + 1).unwrap_or(0));
self.items.shrink_to_fit();

self.free_list_head = None;
for (i, item) in self.items.iter_mut().enumerate() {
match item {
Entry::Occupied { .. } => (),
Entry::Free { next_free } => {
*next_free = self.free_list_head;
self.free_list_head = Some(i);
}
}
}
}

/// Attempts to insert `value` into the arena using existing capacity.
///
/// This method will never allocate new capacity in the arena.
Expand Down

0 comments on commit 51495cf

Please sign in to comment.