fast_graph/
edge.rs

1//! # A struct representing an edge in the graph.
2//!
3//! Contains an [EdgeID] which is a key to the edge in the slotmap, and two [NodeID]s which are the nodes the edge connects (from & to).
4//!
5//! An edge can also have “data”, which could be anything or nothing; for example the weight of the connection or a struct or enum representing something else.
6//!
7//! # Why is there no "EdgeTrait"?
8//!
9//! The [Edge] struct is very simple and doesn't need a trait. It's just a struct with an ID, two node IDs, and some data.
10//! If you want to add more functionality or data to the edge you can probably just add it to the data field, or add an edge as a field to your custom type.
11
12use slotmap::{new_key_type, KeyData};
13
14use super::*;
15
16new_key_type! {
17    /// An index to an edge in the slotmap
18    pub struct EdgeID;
19}
20impl EdgeID {
21    pub fn to_u64(&self) -> u64 {
22        self.0.as_ffi()
23    }
24    pub fn from_u64(id: u64) -> Self {
25        EdgeID::from(KeyData::from_ffi(id))
26    }
27}
28
29/// # A struct representing an edge in the graph.
30///
31/// Contains an [EdgeID] which is a key to the edge in the slotmap, and two [NodeID]s which are the nodes the edge connects (from & to).
32/// An edge can also have “data”, which could be anything or nothing; for example the weight of the connection or a struct or enum representing something else.
33///
34/// ## Why is there no "EdgeTrait"?
35///
36/// The [Edge] struct is very simple and doesn't need a trait. It's just a struct with an ID, two node IDs, and some data.
37/// If you want to add more functionality or data to the edge you can probably just add it to the data field, or add an edge as a field to your custom type.
38#[derive(Clone)]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40#[cfg_attr(feature = "specta", derive(specta::Type))]
41pub struct Edge<T> {
42    pub id: EdgeID,
43    pub from: NodeID,
44    pub to: NodeID,
45    pub data: T,
46}
47
48/// Implements Hash for Edge<T> so only the ID is used for hashing.
49impl<T: std::hash::Hash> std::hash::Hash for Edge<T> {
50    fn hash<H: std::hash::Hasher>(&self, ra_expand_state: &mut H) {
51        self.id.hash(ra_expand_state);
52    }
53}
54
55/// Implements PartialEq for Edge<T> so only the ID is used for comparison.
56impl<T> PartialEq for Edge<T> {
57    fn eq(&self, other: &Self) -> bool {
58        self.id == other.id
59    }
60}
61
62impl<T: fmt::Debug> fmt::Debug for Edge<T> {
63    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
64        write!(
65            f,
66            "Edge {{ id: {:#?}, from: {:#?}, to: {:#?}, data: {:#?} }}",
67            self.id, self.from, self.to, self.data
68        )
69    }
70}
71
72impl<T> Edge<T> {
73    pub fn new(id: EdgeID, from: NodeID, to: NodeID, data: T) -> Edge<T> {
74        Edge { id, from, to, data }
75    }
76}