Skip to main content

bidirected_adjacency_array/
index.rs

1use std::{
2    fmt::{Debug, Display},
3    hash::Hash,
4};
5
6use num_traits::{Bounded, PrimInt};
7use optional_numeric_index::implement_generic_index;
8
9pub trait GraphIndexInteger:
10    PrimInt + Bounded + Hash + Debug + Display + From<u8> + TryFrom<usize> + TryInto<usize>
11{
12}
13
14impl<T: PrimInt + Bounded + Hash + Debug + Display + From<u8> + TryFrom<usize> + TryInto<usize>>
15    GraphIndexInteger for T
16{
17}
18
19implement_generic_index!(pub NodeIndex, pub OptionalNodeIndex);
20implement_generic_index!(pub EdgeIndex, pub OptionalEdgeIndex);
21
22implement_generic_index!(pub DirectedNodeIndex, pub OptionalDirectedNodeIndex);
23implement_generic_index!(pub DirectedEdgeIndex, pub OptionalDirectedEdgeIndex);
24
25impl<IndexType: GraphIndexInteger> DirectedNodeIndex<IndexType> {
26    pub fn from_bidirected(bidirected: NodeIndex<IndexType>, forward: bool) -> Self {
27        let base = bidirected.0 * 2u8.into();
28        if forward {
29            DirectedNodeIndex(base)
30        } else {
31            DirectedNodeIndex(base + 1u8.into())
32        }
33    }
34
35    pub fn into_bidirected(self) -> NodeIndex<IndexType> {
36        NodeIndex(self.0 / 2u8.into())
37    }
38
39    pub fn invert(self) -> Self {
40        DirectedNodeIndex(self.0 ^ 1u8.into())
41    }
42
43    pub fn is_forward(self) -> bool {
44        (self.0 & 1u8.into()) == 0u8.into()
45    }
46
47    pub fn is_reverse(self) -> bool {
48        !self.is_forward()
49    }
50
51    pub(crate) fn add(self, other: DirectedNodeIndex<IndexType>) -> DirectedNodeIndex<IndexType> {
52        Self::new(self.0 + other.0)
53    }
54}
55
56impl<IndexType: GraphIndexInteger> DirectedEdgeIndex<IndexType> {
57    pub(crate) fn zero() -> Self {
58        Self::new(0u8.into())
59    }
60
61    pub(crate) fn increment(&mut self) {
62        *self = Self::new(self.0 + 1u8.into());
63    }
64
65    pub(crate) fn decrement(&mut self) {
66        *self = Self::new(self.0 - 1u8.into());
67    }
68
69    pub(crate) fn add(self, other: DirectedEdgeIndex<IndexType>) -> DirectedEdgeIndex<IndexType> {
70        Self::new(self.0 + other.0)
71    }
72}