changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > demo / obj/src/id.rs

changeset 11: d8f806f1d327
author: ellis <ellis@rwest.io>
date: Sun, 14 May 2023 21:27:04 -0400
permissions: -rw-r--r--
description: obj updates
1 use std::{fmt, str::FromStr};
2 use serde::{Serialize, Deserialize};
3 pub use uuid::Uuid;
4 pub use ulid::Ulid;
5 use rand::Rng;
6 use crate::hash::{KEY_LEN,OUT_LEN,B3Hasher};
7 /// a simple Id abstraction
8 #[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug, Serialize, Deserialize, Hash)]
9 pub struct Id(pub Vec<u8>);
10 
11 impl Id {
12  pub fn rand() -> Self {
13  let mut rng = rand::thread_rng();
14  let vals: Vec<u8> = (0..KEY_LEN).map(|_| rng.gen_range(0..u8::MAX)).collect();
15  Id(vals)
16  }
17 
18  pub fn state_hash(&self, state: &mut B3Hasher) -> Self {
19  let mut output = vec![0; OUT_LEN];
20  state.update(&self.0);
21  let mut res = state.finalize_xof();
22  res.fill(&mut output);
23  Id(output)
24  }
25 
26  pub fn to_hex(&self) -> String {
27  hex::encode(&self.0)
28  }
29 }
30 
31 /// PeerId
32 ///
33 /// identifies a unique Peer
34 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
35 pub struct PeerId {
36  id: [u8; 32],
37 }
38 
39 impl PeerId {
40  pub fn new() -> Self {
41  Self::default()
42  }
43 
44  pub fn rand() -> Self {
45  let pd = rand::thread_rng().gen::<[u8; 32]>();
46  Self { id: pd }
47  }
48 
49  pub fn from_bytes(data: &[u8]) -> Self {
50  let pd = blake3::hash(data);
51  let hash = pd.as_bytes();
52  Self { id: *hash }
53  }
54 }
55 
56 impl Default for PeerId {
57  fn default() -> Self {
58  PeerId { id: [0; 32] }
59  }
60 }
61 
62 /// Identity trait
63 ///
64 /// Defines Identity-related behaviors
65 pub trait Identity: Sized {
66  /// return the hashed bytes of an ObjectId
67  fn id(&self) -> Id;
68 }
69 
70 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
71 pub struct ObjectId(u128);
72 
73 pub struct NameSpace {
74  pub prefix: Option<String>,
75  pub capacity: u64,
76  pub route: Vec<Id>,
77  pub key: Option<Id>,
78 }
79 
80 pub struct Domain {
81  pub ns: NameSpace,
82  pub id: Id,
83 }
84 
85 impl From<Uuid> for ObjectId {
86  fn from(uuid: Uuid) -> Self {
87  ObjectId(uuid.as_u128())
88  }
89 }
90 
91 impl From<Ulid> for ObjectId {
92  fn from(ulid: Ulid) -> Self {
93  ObjectId(u128::from(ulid))
94  }
95 }
96 
97 impl From<u128> for ObjectId {
98  fn from(src: u128) -> Self {
99  ObjectId(src)
100  }
101 }
102 
103 impl FromStr for ObjectId {
104  type Err = ();
105  fn from_str(input: &str) -> std::result::Result<ObjectId, Self::Err> {
106  match input {
107  i => Ok(ObjectId(u128::from(Ulid::from_str(i).unwrap()))),
108  }
109  }
110 }
111 
112 impl fmt::Display for ObjectId {
113  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
114  match *self {
115  ObjectId(i) => {
116  write!(f, "{}", Ulid::from(i))
117  }
118  }
119  }
120 }