Add VertexMap to attach data to vertices

This commit is contained in:
2026-05-06 20:28:00 +02:00
parent 6e9867a65e
commit f40c03b113
6 changed files with 168 additions and 54 deletions
+122
View File
@@ -0,0 +1,122 @@
use std::ops::{Index, IndexMut};
use crate::traits::GraphTopology;
pub struct VertexMap<V: Copy, T: Clone> {
data: Vec<T>,
default: T,
to_index: fn(V) -> usize,
}
impl<V: Copy, T: Clone> VertexMap<V, T> {
pub fn new(default: T, to_index: fn(V) -> usize, capacity: usize) -> Self {
Self {
data: vec![default.clone(); capacity],
default,
to_index,
}
}
pub fn sync<G: GraphTopology<Vertex = V>>(&mut self, graph: &G) {
let capacity = graph.vertex_capacity();
if capacity > self.data.len() {
self.data.resize(capacity, self.default.clone());
}
}
}
impl<V: Copy, T: Clone> Index<V> for VertexMap<V, T> {
type Output = T;
fn index(&self, v: V) -> &T {
let i = (self.to_index)(v);
if i < self.data.len() {
&self.data[i]
} else {
&self.default
}
}
}
impl<V: Copy, T: Clone> IndexMut<V> for VertexMap<V, T> {
fn index_mut(&mut self, v: V) -> &mut T {
let i = (self.to_index)(v);
if i >= self.data.len() {
self.data.resize(i + 1, self.default.clone());
}
&mut self.data[i]
}
}
#[cfg(test)]
mod tests {
use crate::models::append_graph::AppendGraph;
use crate::traits::GraphTopology;
#[test]
fn initial_values_are_default() {
let mut graph = AppendGraph::new();
let v1 = graph.add_vertex();
let v2 = graph.add_vertex();
let map = graph.vertex_map(42);
assert_eq!(map[v1], 42);
assert_eq!(map[v2], 42);
}
#[test]
fn write_and_read() {
let mut graph = AppendGraph::new();
let v1 = graph.add_vertex();
let v2 = graph.add_vertex();
let mut map = graph.vertex_map(0);
map[v1] = 7;
assert_eq!(map[v1], 7);
assert_eq!(map[v2], 0);
}
#[test]
fn lazy_growth_on_read() {
let mut graph = AppendGraph::new();
graph.add_vertex();
let map = graph.vertex_map(99);
let v = graph.add_vertex();
assert_eq!(map[v], 99);
}
#[test]
fn lazy_growth_on_write() {
let mut graph = AppendGraph::new();
let v1 = graph.add_vertex();
let mut map = graph.vertex_map(0);
let v2 = graph.add_vertex();
map[v2] = 7;
assert_eq!(map[v1], 0);
assert_eq!(map[v2], 7);
}
#[test]
fn sync_expands_to_new_vertices() {
let mut graph = AppendGraph::new();
graph.add_vertex();
let mut map = graph.vertex_map(42);
graph.add_vertex();
graph.add_vertex();
assert!(
map.data.len() < graph.vertex_capacity(),
"precondition: map is stale before sync"
);
map.sync(&graph);
assert_eq!(map.data.len(), graph.vertex_capacity());
}
#[test]
fn sync_does_not_overwrite_existing_values() {
let mut graph = AppendGraph::new();
let v = graph.add_vertex();
let mut map = graph.vertex_map(0);
map[v] = 5;
graph.add_vertex();
map.sync(&graph);
assert_eq!(map[v], 5);
}
}