pub struct Graph<N, W> {
pub nodes: Vec<N>,
pub edges: Vec<Edge<W>>,
pub directedness: Directedness,
}Expand description
A weighted graph over node labels N and edge weights W.
Algorithm-level node identity is the usize index into nodes; labels are
payload and never affect correctness. Edge ids are stable. Multiedges and
self-loops are representable. Undirected graphs store one record per edge;
Graph::neighbors expands both directions.
§Examples
Build a small directed graph and read a node’s outgoing adjacencies:
use sim_lib_discrete_graph::{Directedness, Graph};
let mut g: Graph<&str, u64> = Graph::new(Directedness::Directed);
let a = g.add_node("a");
let b = g.add_node("b");
let c = g.add_node("c");
g.add_edge(a, b, 1).unwrap();
g.add_edge(a, c, 2).unwrap();
assert_eq!(g.node_count(), 3);
assert_eq!(g.edge_count(), 2);
let neighbors: Vec<usize> = g.neighbors(a).unwrap().iter().map(|n| n.node).collect();
assert_eq!(neighbors, vec![b, c]);Fields§
§nodes: Vec<N>Node labels, indexed by node id.
edges: Vec<Edge<W>>Edge records.
directedness: DirectednessWhether edges are directed.
Implementations§
Source§impl<N, W> Graph<N, W>
impl<N, W> Graph<N, W>
Sourcepub fn new(directedness: Directedness) -> Self
pub fn new(directedness: Directedness) -> Self
An empty graph with the given directedness.
Sourcepub fn with_nodes(nodes: Vec<N>, directedness: Directedness) -> Self
pub fn with_nodes(nodes: Vec<N>, directedness: Directedness) -> Self
A graph seeded with nodes and no edges.
Sourcepub fn node_count(&self) -> usize
pub fn node_count(&self) -> usize
Number of nodes.
Sourcepub fn edge_count(&self) -> usize
pub fn edge_count(&self) -> usize
Number of edge records (one per undirected edge).
Sourcepub fn is_directed(&self) -> bool
pub fn is_directed(&self) -> bool
Whether the graph is directed.
Sourcepub fn add_edge(
&mut self,
source: usize,
target: usize,
weight: W,
) -> Result<usize, GraphError>
pub fn add_edge( &mut self, source: usize, target: usize, weight: W, ) -> Result<usize, GraphError>
Append an edge, validating endpoints and assigning a fresh id.
Sourcepub fn validate(&self) -> Result<(), GraphError>
pub fn validate(&self) -> Result<(), GraphError>
Validate that edge ids match storage order and every endpoint is in range.
Public fields keep the value easy to encode, but id-indexed consumers
require edges[i].id == i. Sparse, duplicate, or shuffled ids are
rejected before bridge and certificate code indexes by edge id.