Add ElementMap::reserve to replace ElementMap::expand, update tests

ElementMap tests are now self contained unit tests, without any graph context. The only exception is the repurposed test "reused_slot_returns_old_value", which is not suited for GraphTopologyDeletion, but actually specific for Graph.
This commit is contained in:
2026-08-06 23:06:52 +02:00
parent a7346bd782
commit 59d9c2b8a7
5 changed files with 85 additions and 136 deletions
+62 -8
View File
@@ -41,15 +41,13 @@ impl<E: Copy, T: Clone> ElementMap<E, T> {
self.data.capacity()
}
/// Expands the internal data storage capacity of the map to `capacity`, Does nothing if
/// capacity is already sufficient.
/// Reserves capacity for at least `additional` more data entries. Does nothing if capacity is
/// already sufficient.
///
/// Use this before writing data for new graph entities to avoid incremental growth on the first
/// write to each new entity.
pub fn expand(&mut self, capacity: usize) {
if capacity > self.data.len() {
self.data.resize(capacity, self.default.clone());
}
/// Use this before writing data for new graph elements to avoid incremental growth on the first
/// write to each new element.
pub fn reserve(&mut self, additional: usize) {
self.data.reserve(additional);
}
}
@@ -75,3 +73,59 @@ impl<E: Copy, T: Clone> IndexMut<E> for ElementMap<E, T> {
&mut self.data[i]
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn initial_values_are_default() {
let map = ElementMap::new(42, |e| e, 0);
assert_eq!(map[0], 42, "initial read at 0 should be default");
assert_eq!(map[5], 42, "initial read at 5 should be default");
}
#[test]
fn reserve_increases_capacity_without_initializing() {
let mut map = ElementMap::new(0, |e| e, 0);
let capacity_before = map.capacity();
map.reserve(capacity_before + 10);
assert!(
map.capacity() > capacity_before,
"expected sufficient capacity increase after reserve"
);
assert_eq!(map[5], 0, "expected read beyond length to return default");
}
#[test]
fn reserve_prevents_reallocation_on_write() {
let mut map = ElementMap::new(0, |e| e, 0);
map.reserve(10);
let capacity_before = map.capacity();
for i in 0..10 {
map[i] = i as i32;
}
assert_eq!(
map.capacity(),
capacity_before,
"writes within reserved capacity should not reallocate"
);
}
#[test]
fn reserve_does_not_overwrite_existing_values() {
let mut map = ElementMap::new(0, |e| e, 0);
map[0] = 5;
let capacity_before = map.capacity();
map.reserve(capacity_before + 10);
assert_eq!(map[0], 5, "reserve should not change existing data");
}
#[test]
fn write_and_read() {
let mut map = ElementMap::new(0, |e| e, 0);
map[1] = 7;
assert_eq!(map[1], 7, "unexpected read value after write");
assert_eq!(map[0], 0, "initial read should be default");
}
}