Refactor ElementMap, removing its copy-on-write feature

This commit is contained in:
2026-10-11 22:24:00 +02:00
parent 4e20c49486
commit 3d7dda6f7b
9 changed files with 281 additions and 113 deletions
+113 -76
View File
@@ -1,7 +1,7 @@
//! Provides maps to associate custom data to graph vertices and edges.
//!
//! [`ElementMap`] provides a copy-on-write, [`Vec`]-backed map to associate data to either all
//! vertices or all edges in a graph.
//! [`ElementMap`] is a dense, [`Vec`]-backed map to associate data to either all vertices or all
//! edges in a graph.
use std::ops::{Index, IndexMut};
@@ -12,15 +12,19 @@ use std::ops::{Index, IndexMut};
/// which means that the provided index conversion function should map elements to contiguous
/// indices, or indices with relatively few gaps.
///
/// Data allocation happens as copy-on-write, i.e. the backing [`Vec`] is only resized if a value is
/// written beyond current capacity, but the `default` value can transparently be read. No bound or
/// validity checks are performed by the map on the provided element handles.
///
/// Use [`GraphTopology::vertex_map`] or [`GraphTopology::edge_map`] to obtain an `ElementMap` for
/// vertices or edges, respectively.
///
/// The map does not grow on its own when the associated graph grows. Use the graph's
/// [`GraphTopologyAddition::sync_vertex_map`] or [`GraphTopologyAddition::sync_edge_map`] to extend
/// the map explicitly after adding vertices or edges to it.
///
/// No bound or validity checks are performed by the map on the provided element handles.
///
/// [`GraphTopology::edge_map`]: crate::traits::GraphTopology::edge_map
/// [`GraphTopology::vertex_map`]: crate::traits::GraphTopology::vertex_map
/// [`GraphTopologyAddition::sync_vertex_map`]: crate::traits::GraphTopologyAddition::sync_vertex_map
/// [`GraphTopologyAddition::sync_edge_map`]: crate::traits::GraphTopologyAddition::sync_edge_map
pub struct ElementMap<E: Copy, T: Clone> {
data: Vec<T>,
default: T,
@@ -29,47 +33,59 @@ pub struct ElementMap<E: Copy, T: Clone> {
impl<E: Copy, T: Clone> ElementMap<E, T> {
/// Creates a new map with the given `default` value, an index conversion function `to_index`,
/// and an initial `capacity`.
pub fn new(default: T, to_index: fn(E) -> usize, capacity: usize) -> Self {
/// and an initial `len`, i.e. the number of slots that can be read from and written to.
///
/// Since `to_index` is usually an implementation detail of the graph model, this is not meant
/// to be called directly. Use [`GraphTopology::vertex_map`] or [`GraphTopology::edge_map`]
/// instead.
///
/// [`GraphTopology::edge_map`]: crate::traits::GraphTopology::edge_map
/// [`GraphTopology::vertex_map`]: crate::traits::GraphTopology::vertex_map
pub fn new(default: T, to_index: fn(E) -> usize, len: usize) -> Self {
Self {
data: vec![default.clone(); capacity],
data: vec![default.clone(); len],
default,
to_index,
}
}
/// Returns the total number of data entries the map can write without reallocating. Reads
/// beyond `capacity` are valid and return the default value.
pub fn capacity(&self) -> usize {
self.data.capacity()
}
/// Reserves capacity for at least `additional` more data entries. Does nothing if capacity is
/// already sufficient.
/// Grows the map so that it contains at least `new_len` slots for elements, initialising any
/// newly added slots to the `default` value provided to [`new`], without modifying existing
/// data. Does nothing if the map already has at least `new_len` slots.
///
/// 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);
/// Since the number of elements the map can actually store depend on the index conversion
/// function, which is usually an implementation detail of the graph model, this is not meant to
/// be called directly. Use [`GraphTopologyAddition::sync_vertex_map`] or
/// [`GraphTopologyAddition::sync_edge_map`] instead.
///
/// [`new`]: ElementMap::new
/// [`GraphTopologyAddition::sync_vertex_map`]: crate::traits::GraphTopologyAddition::sync_vertex_map
/// [`GraphTopologyAddition::sync_edge_map`]: crate::traits::GraphTopologyAddition::sync_edge_map
pub fn grow(&mut self, new_len: usize) {
if new_len > self.data.len() {
self.data.resize(new_len, self.default.clone());
}
}
/// Returns a new map over the same elements with values transformed by `f`.
///
/// The default value of the new map is `f` applied to the original default, so reads beyond the
/// current capacity of the new map behave consistently with the transformation.
/// The default value of the new map is `f` applied to the original default, so slots later added
/// to the new map by [`GraphTopologyAddition::sync_vertex_map`] or
/// [`GraphTopologyAddition::sync_edge_map`] are filled consistently with the transformation.
///
/// [`GraphTopologyAddition::sync_vertex_map`]: crate::traits::GraphTopologyAddition::sync_vertex_map
/// [`GraphTopologyAddition::sync_edge_map`]: crate::traits::GraphTopologyAddition::sync_edge_map
///
/// # Examples
///
/// ```
/// # use grapherity::maps::ElementMap;
/// let mut map: ElementMap<usize, Option<i32>> = ElementMap::new(None, |e| e, 0);
/// let mut map: ElementMap<usize, Option<i32>> = ElementMap::new(None, |e| e, 2);
/// map[1] = Some(42);
///
/// let bools = map.map(|v| v.is_some());
/// assert_eq!(bools[0], false);
/// assert_eq!(bools[1], true);
/// // Returns mapped default for reads beyond capacity.
/// assert_eq!(bools[9], false);
/// ```
pub fn map<U: Clone>(&self, f: impl Fn(&T) -> U) -> ElementMap<E, U> {
ElementMap {
@@ -84,22 +100,13 @@ impl<E: Copy, T: Clone> Index<E> for ElementMap<E, T> {
type Output = T;
fn index(&self, e: E) -> &T {
let i = (self.to_index)(e);
if i < self.data.len() {
&self.data[i]
} else {
&self.default
}
&self.data[(self.to_index)(e)]
}
}
impl<E: Copy, T: Clone> IndexMut<E> for ElementMap<E, T> {
fn index_mut(&mut self, e: E) -> &mut T {
let i = (self.to_index)(e);
if i >= self.data.len() {
self.data.resize(i + 1, self.default.clone());
}
&mut self.data[i]
&mut self.data[(self.to_index)(e)]
}
}
@@ -109,67 +116,97 @@ mod tests {
#[test]
fn initial_values_are_default() {
let map = ElementMap::new(42, |e| e, 0);
let map = ElementMap::new(42, |e| e, 6);
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");
#[should_panic]
fn read_out_of_bounds() {
let map = ElementMap::new(42, |e| e, 3);
let _ = map[3];
}
#[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");
#[should_panic]
fn write_out_of_bounds() {
let mut map = ElementMap::new(0, |e| e, 3);
map[3] = 1;
}
#[test]
fn write_and_read() {
let mut map = ElementMap::new(0, |e| e, 0);
let mut map = ElementMap::new(0, |e| e, 2);
map[1] = 7;
assert_eq!(map[1], 7, "unexpected read value after write");
assert_eq!(map[0], 0, "initial read should be default");
}
#[test]
fn grow() {
let mut map = ElementMap::new(0, |e| e, 2);
assert_eq!(
map.data.len(),
2,
"precondition: unexpected data length before grow"
);
map.grow(10);
assert_eq!(map.data.len(), 10, "unexpected data length after grow");
}
#[test]
fn grow_extends_with_default() {
let mut map = ElementMap::new(17, |e| e, 3);
map.grow(6);
assert_eq!(map[5], 17, "read of newly grown slot should be default");
map[5] = 9;
assert_eq!(
map[5], 9,
"unexpected value after write in newly grown slot"
);
}
#[test]
fn grow_preserves_existing_values() {
let mut map = ElementMap::new(22, |e| e, 3);
map[0] = 5;
map.grow(10);
assert_eq!(map[0], 5, "unexpected data after grow");
}
#[test]
fn grow_to_smaller_len() {
let mut map = ElementMap::new(23, |e| e, 6);
map[5] = 9;
map.grow(3);
assert_eq!(
map[5], 9,
"grow to a smaller length should not discard data"
);
assert_eq!(map.data.len(), 6, "unexpected data length");
}
#[test]
fn map() {
let mut source: ElementMap<usize, Option<i32>> = ElementMap::new(None, |e| e, 0);
let mut source: ElementMap<usize, Option<i32>> = ElementMap::new(None, |e| e, 3);
source[1] = Some(42);
source[2] = None;
let mapped = source.map(|v| v.is_some());
assert_eq!(mapped[0], false, "unset entry should map to false");
assert_eq!(mapped[1], true, "Some entry should map to true");
assert_eq!(mapped[2], false, "explicit None entry should map to false");
assert_eq!(
mapped[9], false,
"read beyond capacity should return mapped default"
assert!(!mapped[0], "unset entry should map to false");
assert!(mapped[1], "Some entry should map to true");
assert!(!mapped[2], "explicit None entry should map to false");
}
#[test]
fn map_grow() {
let mut source: ElementMap<usize, Option<i32>> = ElementMap::new(None, |e| e, 2);
source[1] = Some(42);
let mut mapped = source.map(|v| v.is_some());
mapped.grow(4);
assert!(
!mapped[3],
"slot added by grow should hold the mapped default"
);
}
}