rshyper_core/node/
hyper_node.rs1use crate::{VertexId, Weight};
6
7#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
8#[cfg_attr(
9 feature = "serde",
10 derive(serde::Deserialize, serde::Serialize),
11 serde(rename_all = "lowercase")
12)]
13pub struct Node<T = (), Idx = usize> {
14 pub(crate) index: VertexId<Idx>,
15 pub(crate) weight: Weight<T>,
16}
17
18impl<T, Idx> Node<T, Idx> {
19 pub fn new(index: VertexId<Idx>, weight: T) -> Self {
21 Self {
22 index,
23 weight: Weight(weight),
24 }
25 }
26 pub fn from_index(index: VertexId<Idx>) -> Self
28 where
29 T: Default,
30 {
31 Self {
32 index,
33 weight: Weight::default(),
34 }
35 }
36 pub fn from_weight(weight: Weight<T>) -> Self
38 where
39 Idx: Default,
40 {
41 Self {
42 index: VertexId::default(),
43 weight,
44 }
45 }
46 pub fn with_index<I2>(self, index: VertexId<I2>) -> Node<T, I2> {
48 Node {
49 index,
50 weight: self.weight,
51 }
52 }
53 pub fn with_weight<U>(self, weight: Weight<U>) -> Node<U, Idx> {
55 Node {
56 index: self.index,
57 weight,
58 }
59 }
60 pub const fn index(&self) -> &VertexId<Idx> {
62 &self.index
63 }
64 pub const fn weight(&self) -> &Weight<T> {
66 &self.weight
67 }
68 pub const fn weight_mut(&mut self) -> &mut Weight<T> {
70 &mut self.weight
71 }
72 pub fn set_weight(&mut self, weight: T) -> &mut Self {
74 self.weight_mut().set(weight);
75 self
76 }
77 pub fn replace_weight(&mut self, weight: T) -> T {
80 self.weight_mut().replace(weight)
81 }
82 pub fn swap_weight(&mut self, other: &mut Self) {
85 self.weight_mut().swap(other.weight_mut());
86 }
87 pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Node<U, Idx> {
90 Node {
91 index: self.index,
92 weight: self.weight.map(f),
93 }
94 }
95}
96
97impl<T, Idx> AsRef<Weight<T>> for Node<T, Idx> {
98 fn as_ref(&self) -> &Weight<T> {
99 &self.weight
100 }
101}
102
103impl<T, Idx> AsMut<Weight<T>> for Node<T, Idx> {
104 fn as_mut(&mut self) -> &mut Weight<T> {
105 &mut self.weight
106 }
107}
108
109impl<T, Idx> core::borrow::Borrow<VertexId<Idx>> for Node<T, Idx> {
110 fn borrow(&self) -> &VertexId<Idx> {
111 &self.index
112 }
113}
114
115impl<T, Idx> core::fmt::Display for Node<T, Idx>
116where
117 Idx: core::fmt::Display,
118 T: core::fmt::Display,
119{
120 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
121 write!(
122 f,
123 "{{ index: {}, weight: {} }}",
124 self.index(),
125 self.weight()
126 )
127 }
128}