Struct Graph

Source
pub struct Graph<N, E, Ty = Directed> { /* private fields */ }
Expand description

Graph<N, E, Ty> is a graph datastructure using an associative array of its node weights N.

It uses an combined adjacency list and sparse adjacency matrix representation, using O(|V| + |E|) space, and allows testing for edge existance in constant time.

§Graph is parameterized over:

  • Associated data N for nodes and E for edges, called weights.
  • The node weight N must implement Copy and will be used as node identifier, duplicated into several places in the data structure. It must be suitable as a hash table key (implementing Eq + Hash). The node type must also implement Ord so that the implementation can order the pair (a, b) for an edge connecting any two nodes a and b.
  • E can be of arbitrary type.
  • Edge type Ty that determines whether the graph edges are directed or undirected.

You can use the type alias UndirectedGraph for convenience.

Graph does not allow parallel edges, but self loops are allowed.

Implementations§

Source§

impl<N, E, Ty> Graph<N, E, Ty>
where N: NodeTrait, Ty: EdgeType,

Source

pub fn new() -> Self

Create a new Graph instance.

§Examples
use safe_graph::Graph;

let graph: Graph<i32, f32> = Graph::new();
Source

pub fn with_capacity(nodes: usize, edges: usize) -> Self

Create a new Graph with estimated capacity.

Source

pub fn capacity(&self) -> (usize, usize)

Return the current node and edge capacity of the graph.

Source

pub fn edge_key(a: N, b: N) -> (N, N)

Use their natural order to map the node pair (a, b) to a canonical edge id.

Source

pub fn is_directed(&self) -> bool

Whether the graph has directed edges.

Source

pub fn from_edges<I>(iterable: I) -> Self
where I: IntoIterator, I::Item: IntoWeightedEdge<E, NodeId = N>,

Create a new Graph from an iterable of edges.

Node values are taken directly from the list. Edge weights E may either be specified in the list, or they are filled with default values.

Nodes are inserted automatically to match the edges.

§Examples
use safe_graph::Graph;

// Create a new directed Graph.
// Use a type hint to have `()` be the edge weight type.
let gr = Graph::<_, ()>::from_edges(&[
    (0, 1), (0, 2), (0, 3),
    (1, 2), (1, 3),
    (2, 3),
]);
Source

pub fn node_count(&self) -> usize

Return the number of nodes in the graph.

Source

pub fn edge_count(&self) -> usize

Return the number of edges in the graph.

Source

pub fn clear(&mut self)

Remove all nodes and edges

Source

pub fn add_node(&mut self, n: N) -> N

Add node n to the graph.

Source

pub fn contains_node(&self, n: N) -> bool

Return true if the node is contained in the graph.

Source

pub fn add_edge(&mut self, a: N, b: N, weight: E) -> Option<E>

Add an edge connecting a and b to the graph, with associated data weight. For a directed graph, the edge is directed from a to b.

Inserts nodes a and/or b if they aren’t already part of the graph.

Return None if the edge did not previously exist, otherwise, the associated data is updated and the old value is returned as Some(old_weight).

§Examples
// Create a Graph with directed edges, and add one edge to it
use safe_graph::Graph;

let mut g: Graph<_, _> = Graph::new();
g.add_edge("x", "y", -1);
assert_eq!(g.node_count(), 2);
assert_eq!(g.edge_count(), 1);
assert!(g.contains_edge("x", "y"));
assert!(!g.contains_edge("y", "x"));
Source

pub fn contains_edge(&self, a: N, b: N) -> bool

Return true if the edge connecting a with b is contained in the graph.

Source

pub fn nodes(&self) -> Nodes<'_, N>

Return an iterator over the nodes of the graph.

Iterator element type is N.

Source

pub fn neighbors(&self, a: N) -> Neighbors<'_, N, Ty>

Return an iterator of all nodes with an edge starting from a.

  • Directed: Outgoing edges from a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is N.

Source

pub fn neighbors_directed( &self, a: N, dir: Direction, ) -> NeighborsDirected<'_, N, Ty>

Return an iterator of all neighbors that have an edge between them and a, in the specified direction. If the graph’s edges are undirected, this is equivalent to .neighbors(a).

  • Directed, Outgoing: All edges from a.
  • Directed, Incoming: All edges to a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is N.

Source

pub fn edges(&self, from: N) -> Edges<'_, N, E, Ty>

Return an iterator of target nodes with an edge starting from a, paired with their respective edge weights.

  • Directed: Outgoing edges from a.
  • Undirected: All edges from or to a.

Produces an empty iterator if the node doesn’t exist.
Iterator element type is (N, &E).

Source

pub fn edge_weight(&self, a: N, b: N) -> Option<&E>

Return a reference to the edge weight connecting a with b, or None if the edge does not exist in the graph.

Source

pub fn edge_weight_mut(&mut self, a: N, b: N) -> Option<&mut E>

Return a mutable reference to the edge weight connecting a with b, or None if the edge does not exist in the graph.

Source

pub fn all_edges(&self) -> AllEdges<'_, N, E, Ty>

Return an iterator over all edges of the graph with their weight in arbitrary order.

Iterator element type is (N, N, &E)

Trait Implementations§

Source§

impl<N: Clone, E: Clone, Ty: Clone> Clone for Graph<N, E, Ty>

Source§

fn clone(&self) -> Graph<N, E, Ty>

Returns a copy of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<N: Eq + Hash + Debug, E: Debug, Ty: EdgeType> Debug for Graph<N, E, Ty>

Source§

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

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

impl<N, E, Ty> Default for Graph<N, E, Ty>
where N: NodeTrait, Ty: EdgeType,

Create a new empty Graph.

Source§

fn default() -> Self

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

impl<N, E, Ty, Item> Extend<Item> for Graph<N, E, Ty>
where Item: IntoWeightedEdge<E, NodeId = N>, N: NodeTrait, Ty: EdgeType,

Extend the graph from an iterable of edges.

Nodes are inserted automatically to match the edges.

Source§

fn extend<I>(&mut self, iterable: I)
where I: IntoIterator<Item = Item>,

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl<N, E, Ty, Item> FromIterator<Item> for Graph<N, E, Ty>
where Item: IntoWeightedEdge<E, NodeId = N>, N: NodeTrait, Ty: EdgeType,

Create a new Graph from an iterable of edges.

Source§

fn from_iter<I>(iterable: I) -> Self
where I: IntoIterator<Item = Item>,

Creates a value from an iterator. Read more

Auto Trait Implementations§

§

impl<N, E, Ty> Freeze for Graph<N, E, Ty>

§

impl<N, E, Ty> RefUnwindSafe for Graph<N, E, Ty>

§

impl<N, E, Ty> Send for Graph<N, E, Ty>
where Ty: Send, N: Send, E: Send,

§

impl<N, E, Ty> Sync for Graph<N, E, Ty>
where Ty: Sync, N: Sync, E: Sync,

§

impl<N, E, Ty> Unpin for Graph<N, E, Ty>
where Ty: Unpin, N: Unpin, E: Unpin,

§

impl<N, E, Ty> UnwindSafe for Graph<N, E, Ty>
where Ty: UnwindSafe, N: UnwindSafe, E: 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.