Skip to content
This repository has been archived by the owner on Nov 8, 2023. It is now read-only.

Add shrink_to_fit #37

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
105 changes: 66 additions & 39 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -300,19 +300,8 @@ impl<T> Arena<T> {
/// ```
pub fn clear(&mut self) {
self.items.clear();

let end = self.items.capacity();
self.items.extend((0..end).map(|i| {
if i == end - 1 {
Entry::Free { next_free: None }
} else {
Entry::Free {
next_free: Some(i + 1),
}
}
}));
self.free_list_head = Some(0);
self.len = 0;
self.reserve(self.items.capacity());
}

/// Attempts to insert `value` into the arena using existing capacity.
Expand Down Expand Up @@ -351,7 +340,7 @@ impl<T> Arena<T> {
value,
};
Ok(index)
},
}
}
}

Expand Down Expand Up @@ -392,7 +381,7 @@ impl<T> Arena<T> {
value: create(index),
};
Ok(index)
},
}
}
}

Expand All @@ -410,7 +399,7 @@ impl<T> Arena<T> {
generation: self.generation,
})
}
}
},
}
}

Expand Down Expand Up @@ -503,14 +492,19 @@ impl<T> Arena<T> {
Entry::Occupied { generation, .. } if i.generation == generation => {
let entry = mem::replace(
&mut self.items[i.index],
Entry::Free { next_free: self.free_list_head },
Entry::Free {
next_free: self.free_list_head,
},
);
self.generation += 1;
self.free_list_head = Some(i.index);
self.len -= 1;

match entry {
Entry::Occupied { generation: _, value } => Some(value),
Entry::Occupied {
generation: _,
value,
} => Some(value),
_ => unreachable!(),
}
}
Expand Down Expand Up @@ -598,10 +592,9 @@ impl<T> Arena<T> {
/// ```
pub fn get(&self, i: Index) -> Option<&T> {
match self.items.get(i.index) {
Some(Entry::Occupied {
generation,
value,
}) if *generation == i.generation => Some(value),
Some(Entry::Occupied { generation, value }) if *generation == i.generation => {
Some(value)
}
_ => None,
}
}
Expand All @@ -625,10 +618,9 @@ impl<T> Arena<T> {
/// ```
pub fn get_mut(&mut self, i: Index) -> Option<&mut T> {
match self.items.get_mut(i.index) {
Some(Entry::Occupied {
generation,
value,
}) if *generation == i.generation => Some(value),
Some(Entry::Occupied { generation, value }) if *generation == i.generation => {
Some(value)
}
_ => None,
}
}
Expand Down Expand Up @@ -690,18 +682,12 @@ impl<T> Arena<T> {
};

let item1 = match raw_item1 {
Entry::Occupied {
generation,
value,
} if *generation == i1.generation => Some(value),
Entry::Occupied { generation, value } if *generation == i1.generation => Some(value),
_ => None,
};

let item2 = match raw_item2 {
Entry::Occupied {
generation,
value,
} if *generation == i2.generation => Some(value),
Entry::Occupied { generation, value } if *generation == i2.generation => Some(value),
_ => None,
};

Expand Down Expand Up @@ -816,6 +802,41 @@ impl<T> Arena<T> {
self.free_list_head = Some(start);
}

/// 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);
}
}
}
}

/// Iterate over shared references to the elements in this arena.
///
/// Yields pairs of `(Index, &T)` items.
Expand Down Expand Up @@ -913,10 +934,13 @@ impl<T> Arena<T> {
/// You should use the `get` method instead most of the time.
pub fn get_unknown_gen(&self, i: usize) -> Option<(&T, Index)> {
match self.items.get(i) {
Some(Entry::Occupied {
generation,
Some(Entry::Occupied { generation, value }) => Some((
value,
}) => Some((value, Index { generation: *generation, index: i})),
Index {
generation: *generation,
index: i,
},
)),
_ => None,
}
}
Expand All @@ -933,10 +957,13 @@ impl<T> Arena<T> {
/// You should use the `get_mut` method instead most of the time.
pub fn get_unknown_gen_mut(&mut self, i: usize) -> Option<(&mut T, Index)> {
match self.items.get_mut(i) {
Some(Entry::Occupied {
generation,
Some(Entry::Occupied { generation, value }) => Some((
value,
}) => Some((value, Index { generation: *generation, index: i})),
Index {
generation: *generation,
index: i,
},
)),
_ => None,
}
}
Expand Down
2 changes: 1 addition & 1 deletion tests/quickchecks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ quickcheck! {
}

arena.retain(|_, &mut b| b);

for live in live_indices.iter().cloned() {
assert!(arena.contains(live));
}
Expand Down
45 changes: 41 additions & 4 deletions tests/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,11 +134,17 @@ fn get_unknown_gen() {
assert_eq!(id, idx);
assert_eq!(*el, 5);
} else {
panic!("element at index {} (without generation) should exist at this point", i);
panic!(
"element at index {} (without generation) should exist at this point",
i
);
}
arena.remove(idx);
if let Some((_, _)) = arena.get_unknown_gen(i) {
panic!("element at index {} (without generation) should not exist at this point", i);
panic!(
"element at index {} (without generation) should not exist at this point",
i
);
}
}

Expand All @@ -154,12 +160,18 @@ fn get_unknown_gen_mut() {
assert_eq!(*el, 5);
*el += 1;
} else {
panic!("element at index {} (without generation) should exist at this point", i);
panic!(
"element at index {} (without generation) should exist at this point",
i
);
}
assert_eq!(arena.get_mut(idx).cloned(), Some(6));
arena.remove(idx);
if let Some((_, _)) = arena.get_unknown_gen_mut(i) {
panic!("element at index {} (without generation) should not exist at this point", i);
panic!(
"element at index {} (without generation) should not exist at this point",
i
);
}
}

Expand Down Expand Up @@ -293,3 +305,28 @@ fn retain() {
assert_eq!(arena.len(), 1);
assert!(!arena.contains(index));
}

#[test]
fn shrink_to_fit() {
let mut arena = Arena::with_capacity(4);

arena.extend([1, 2, 3, 4].iter().copied());
let five = arena.insert(5);
assert_eq!(arena.capacity(), 8);

arena.shrink_to_fit();
assert_eq!(arena.len(), 5);
assert_eq!(arena.capacity(), 5);

arena.insert(6);
assert_eq!(arena.capacity(), 10);

arena.shrink_to_fit();
assert_eq!(arena.len(), 6);
assert_eq!(arena.capacity(), 6);

arena.remove(five);
arena.shrink_to_fit();
assert_eq!(arena.len(), 5);
assert_eq!(arena.capacity(), 6);
}