/ crates / distrox-model / src / node.rs
node.rs
 1  #[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, derive_more::From)]
 2  pub struct NodeId(distrox_multihash::multihash::Multihash);
 3  
 4  impl NodeId {
 5      pub fn from_bytes(bytes: &[u8]) -> Result<Self, NodeIdError> {
 6          distrox_multihash::multihash::Multihash::from_bytes(bytes)
 7              .map(Self)
 8              .map_err(NodeIdError::from)
 9      }
10  
11      pub fn from_multihash(multihash: distrox_multihash::multihash::Multihash) -> Self {
12          Self(multihash)
13      }
14  
15      pub fn inner(&self) -> distrox_multihash::multihash::Multihash {
16          self.0
17      }
18  
19      pub fn display(&self) -> NodeIdDisplay<'_> {
20          NodeIdDisplay(self)
21      }
22  }
23  
24  impl std::fmt::Debug for NodeId {
25      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26          write!(
27              f,
28              "NodeId({})",
29              distrox_multihash::utils::multihash_to_display(&self.0)
30          )
31      }
32  }
33  
34  pub struct NodeIdDisplay<'n>(&'n NodeId);
35  
36  impl std::fmt::Display for NodeIdDisplay<'_> {
37      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
38          write!(
39              f,
40              "{}",
41              distrox_multihash::utils::multihash_to_display(&self.0.0)
42          )
43      }
44  }
45  
46  static_assertions::assert_impl_all!(NodeId: Send, Sync);
47  
48  #[derive(Debug, thiserror::Error)]
49  #[non_exhaustive]
50  pub enum NodeIdError {
51      #[error(transparent)]
52      MultiHash(#[from] distrox_multihash::multihash::TryFromMultihashError),
53  }
54  
55  #[derive(Debug, Clone)]
56  pub struct Node {
57      version: u64,
58      parents: Vec<NodeId>,
59      content: Option<crate::content::ContentId>,
60  }
61  
62  impl Node {
63      pub fn from_raw_parts(
64          version: u64,
65          parents: Vec<NodeId>,
66          content: Option<crate::content::ContentId>,
67      ) -> Self {
68          Self {
69              version,
70              parents,
71              content,
72          }
73      }
74  
75      pub fn parent_ids(&self) -> &[NodeId] {
76          &self.parents
77      }
78  
79      pub fn content(&self) -> Option<crate::content::ContentId> {
80          self.content
81      }
82  
83      pub fn version(&self) -> u64 {
84          self.version
85      }
86  
87      pub fn is_root(&self) -> bool {
88          self.parents.is_empty()
89      }
90  }
91  
92  #[derive(Debug, Clone, PartialEq, Eq, derive_more::Into, derive_more::From, derive_more::AsRef)]
93  pub struct Signature(#[as_ref] Vec<u8>);
94  
95  impl std::fmt::Display for Signature {
96      fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97          format!("Signature(0x{})", hex::encode_upper(&self.0)).fmt(f)
98      }
99  }