Skip to main content

Graph

Struct Graph 

Source
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

Source

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

Source

pub fn new() -> Self

Creates an empty graph in O(1) time.

Source

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.

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.

Source

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.

Source

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.

Source

pub fn node_count(&self) -> usize

Returns the number of vertices, including isolated ones, in O(1) time.

Source

pub fn edge_count(&self) -> usize

Returns the number of undirected edges in O(1) time.

Source

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);
Source

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]);
Source

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]);

Trait Implementations§

Source§

impl Debug for Graph

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Graph

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Graph> for ConnectivityGraph

Source§

fn from(graph: Graph) -> Self

Takes ownership without rebuilding or losing existing graph state.

Auto Trait Implementations§

§

impl Forget for Graph

§

impl Freeze for Graph

§

impl Move for Graph

§

impl RefUnwindSafe for Graph

§

impl Send for Graph
where RawTable<(u64, usize)>: Send, RawVecInner: Send,

§

impl Sync for Graph
where RawTable<(u64, usize)>: Sync, RawVecInner: Sync,

§

impl Unpin for Graph
where *const u8 is !null: Unpin,

§

impl UnsafeUnpin for Graph

§

impl UnwindSafe for Graph
where HashMap<u64, usize, BuildHasherDefault<IdHasher>>: UnwindSafe, RawVecInner: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.