pub struct Graph { /* private fields */ }Expand description
An undirected simple graph with compact adjacency and exact BFS queries.
External IDs map to stable, append-only indices. Neighbor listing
(neighbors_after) is opt-in: after
enable_neighbor_listing the graph also keeps
the ID of every index (8 bytes per vertex); otherwise it keeps nothing extra.
Each sorted adjacency vector contains unique indices, and every edge appears at
both endpoints. Cuts retain vertices. Logical storage is O(V + E). Allocated storage is O(V + H), where H is
the sum of per-vertex adjacency capacities: each is at least the vertex’s
historical maximum degree (capacity is retained) and, for a graph built in
bulk by the lifecycle facade, starts at the vertex’s enabled registered
degree. No query answers are cached.
Implementations§
Source§impl Graph
impl Graph
Sourcepub fn connected_with_workspace(
&self,
source: NodeId,
target: NodeId,
workspace: &mut BfsWorkspace,
) -> Result<bool, GraphError>
pub fn connected_with_workspace( &self, source: NodeId, target: NodeId, workspace: &mut BfsWorkspace, ) -> Result<bool, GraphError>
Tests connectivity using reusable caller-owned traversal storage.
Unlike Graph::connected, repeated calls reuse allocations. A generation
counter makes old marks inactive without clearing them after each query.
Traversal takes O(V_reached + E_examined), plus O(log V) endpoint lookup
and amortized storage growth (initial growth is O(V)). Generation rollover
clears the retained mark array once per u32::MAX non-reflexive queries,
costing O(N) for the largest graph previously queried with this workspace.
No answers are cached; queries always observe current edges.
use knotrel_core::{BfsWorkspace, Graph};
let mut graph = Graph::new();
graph.link(10, 20)?;
let mut workspace = BfsWorkspace::default();
assert!(graph.connected_with_workspace(10, 20, &mut workspace)?);
graph.cut(10, 20)?;
assert!(!graph.connected_with_workspace(10, 20, &mut workspace)?);§Errors
Returns GraphError::UnknownNode for absent endpoints, source first.
Source§impl Graph
impl Graph
Sourcepub fn add_node(&mut self, node: NodeId) -> bool
pub fn add_node(&mut self, node: NodeId) -> bool
Adds an isolated vertex, returning true only if it was absent.
Existing edges are unchanged. O(1) amortized time; growing the outer vector can take O(V) in a single insertion. Indices never change.
Sourcepub fn link(
&mut self,
source: NodeId,
target: NodeId,
) -> Result<bool, GraphError>
pub fn link( &mut self, source: NodeId, target: NodeId, ) -> Result<bool, GraphError>
Inserts an undirected edge, creating absent endpoints.
Reversed endpoints identify the same edge; duplicates return false. O(1 + deg(source) + deg(target)) amortized time, including sorted vector shifts. A new vertex can trigger an O(V) capacity growth.
§Errors
Returns GraphError::SelfLoop without creating vertices for equal IDs.
Sourcepub fn cut(
&mut self,
source: NodeId,
target: NodeId,
) -> Result<bool, GraphError>
pub fn cut( &mut self, source: NodeId, target: NodeId, ) -> Result<bool, GraphError>
Removes an edge, preserving vertices; absent edges return false.
Worst-case time: O(1 + deg(source) + deg(target)), due to vector shifts.
§Errors
Returns GraphError::SelfLoop for equal IDs without changing the graph.
Sourcepub fn connected(
&self,
source: NodeId,
target: NodeId,
) -> Result<bool, GraphError>
pub fn connected( &self, source: NodeId, target: NodeId, ) -> Result<bool, GraphError>
Reports whether a path exists between two existing vertices.
Existing vertices connect to themselves. Worst-case time O(V + E), with O(1) endpoint lookup. Scratch is per thread and reused: a query costs no allocation or O(V) initialization once the thread’s scratch has grown, and shared queries need no internal lock. Each thread keeps at most 256 KiB of scratch between queries.
The search grows from both endpoints and stops when they meet or when
either side exhausts its component, so queries between nearby vertices,
through hubs, or against a small component finish early. On path-like
graphs it examines the same entries as a one-sided search from source.
let mut graph = knotrel_core::Graph::new();
graph.link(1, 2)?;
graph.link(2, 3)?;
graph.add_node(9);
assert_eq!(graph.connected(1, 3), Ok(true));
assert_eq!(graph.connected(1, 9), Ok(false));§Errors
Returns GraphError::UnknownNode for absent endpoints, source first.
Sourcepub fn node_count(&self) -> usize
pub fn node_count(&self) -> usize
Returns the number of vertices, including isolated ones, in O(1) time.
Sourcepub fn edge_count(&self) -> usize
pub fn edge_count(&self) -> usize
Returns the number of undirected edges in O(1) time.
Sourcepub fn degree(&self, node: NodeId) -> Option<usize>
pub fn degree(&self, node: NodeId) -> Option<usize>
Returns the number of edges incident to node, or None if it is not
registered. Expected O(1).
let mut graph = knotrel_core::Graph::new();
graph.link(1, 2)?;
assert_eq!(graph.degree(1), Some(1));
assert_eq!(graph.degree(9), None);Sourcepub fn enable_neighbor_listing(&mut self)
pub fn enable_neighbor_listing(&mut self)
Starts keeping the ID of every internal index, which
neighbors_after needs. Costs 8 bytes per vertex
and one vector push per new vertex from now on; building the vector for
the existing vertices is O(V). Calling it again does nothing.
let mut graph = knotrel_core::Graph::new();
graph.link(1, 2)?;
assert!(graph.neighbors_after(1, None).is_err());
graph.enable_neighbor_listing();
assert_eq!(graph.neighbors_after(1, None)?.collect::<Vec<_>>(), [2]);Sourcepub fn neighbors_after(
&self,
node: NodeId,
after: Option<NodeId>,
) -> Result<impl Iterator<Item = NodeId> + '_, IncidenceError>
pub fn neighbors_after( &self, node: NodeId, after: Option<NodeId>, ) -> Result<impl Iterator<Item = NodeId> + '_, IncidenceError>
Iterates the neighbors of node in the graph’s stable incidence order,
starting strictly after the neighbor after (or from the start).
The order is the neighbors’ registration order. It is stable across
mutations: indices are never reused, so a neighbor present before and
after a sequence of calls keeps its relative position. That makes
after usable as a pagination cursor: every neighbor that stays linked
while a caller pages through the list is visited exactly once, and
neighbors linked or cut meanwhile may or may not be visited. after
need not still be linked to node.
Positioning costs O(log deg(node)) expected; each step is O(1).
§Errors
IncidenceError::NotEnabled before
enable_neighbor_listing,
IncidenceError::UnknownNode if node is not registered, and
IncidenceError::UnknownCursor if after is not a registered node.
Vertices are never removed from a Graph, so a cursor obtained from
this graph never becomes unknown.
let mut graph = knotrel_core::Graph::new();
graph.enable_neighbor_listing();
graph.link(5, 9)?;
graph.link(5, 1)?;
graph.link(5, 7)?;
let all: Vec<_> = graph.neighbors_after(5, None)?.collect();
assert_eq!(all, [9, 1, 7]); // registration order, not ID order
let rest: Vec<_> = graph.neighbors_after(5, Some(9))?.collect();
assert_eq!(rest, [1, 7]);