1use std::fmt;
13use std::io;
14use std::ops;
15
16pub use minibytes::Bytes;
17use serde::Deserialize;
18use serde::Serialize;
19
20#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
23#[derive(Serialize, Deserialize)]
24pub struct Id(pub u64);
25
26#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)]
28#[serde(transparent)]
29pub struct Vertex(pub Bytes);
30
31impl AsRef<[u8]> for Vertex {
32 fn as_ref(&self) -> &[u8] {
33 &self.0
34 }
35}
36
37impl Vertex {
38 pub fn to_hex(&self) -> String {
39 const HEX_CHARS: &[u8] = b"0123456789abcdef";
40 let mut v = Vec::with_capacity(self.0.len() * 2);
41 for &byte in self.as_ref() {
42 v.push(HEX_CHARS[(byte >> 4) as usize]);
43 v.push(HEX_CHARS[(byte & 0xf) as usize]);
44 }
45 unsafe { String::from_utf8_unchecked(v) }
46 }
47
48 pub fn from_hex(hex: &[u8]) -> io::Result<Self> {
52 let mut bytes = vec![0u8; hex.len().div_ceil(2)];
53 for (i, byte) in hex.iter().enumerate() {
54 let value = match byte {
55 b'0'..=b'9' => byte - b'0',
56 b'a'..=b'f' => byte - b'a' + 10,
57 b'A'..=b'F' => byte - b'A' + 10,
58 _ => {
59 return Err(io::Error::new(
60 io::ErrorKind::InvalidInput,
61 format!("{:?} is not a hex character", *byte as char),
62 ));
63 }
64 };
65 if i & 1 == 0 {
66 bytes[i / 2] |= value << 4;
67 } else {
68 bytes[i / 2] |= value;
69 }
70 }
71 Ok(Vertex(Bytes::from(bytes)))
72 }
73
74 pub fn copy_from(value: &[u8]) -> Self {
75 Self(value.to_vec().into())
76 }
77}
78
79impl<T> From<T> for Vertex
80where
81 Bytes: From<T>,
82{
83 fn from(value: T) -> Self {
84 Self(Bytes::from(value))
85 }
86}
87
88impl fmt::Debug for Vertex {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 if self.0.len() >= 4 || !looks_like_ascii_identifier(self.as_ref()) {
91 let hex = self.to_hex();
93 if let Some(width) = f.precision() {
95 let truncated = hex.get(..width).unwrap_or(&hex);
96 f.write_str(truncated)
97 } else {
98 f.write_str(&hex)
99 }
100 } else {
101 match std::str::from_utf8(self.as_ref()) {
103 Ok(s) => write!(f, "{s}"),
104 Err(_) => write!(f, "{}", self.to_hex()),
105 }
106 }
107 }
108}
109
110fn looks_like_ascii_identifier(bytes: &[u8]) -> bool {
111 let mut iter = bytes.iter().copied();
112 if !(iter.next().unwrap_or(b'\0') as char).is_ascii_alphabetic() {
113 return false;
114 }
115 iter.all(|b| b.is_ascii_alphanumeric())
116}
117
118#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
125#[derive(Serialize, Deserialize)]
126pub struct Group(pub usize);
127
128impl Group {
129 pub const MASTER: Self = Self(0);
136
137 pub const NON_MASTER: Self = Self(1);
146
147 pub const VIRTUAL: Self = Self(2);
152
153 pub const PERSIST: [Self; 2] = [Self::MASTER, Self::NON_MASTER];
155
156 pub const ALL: [Self; 3] = [Self::MASTER, Self::NON_MASTER, Self::VIRTUAL];
157 pub const MAX: Self = Self::ALL[Self::COUNT - 1];
158
159 pub const COUNT: usize = Self::ALL.len();
160
161 pub const BITS: u32 = 8;
163 pub const BYTES: usize = 1;
164
165 pub const fn min_id(self) -> Id {
167 Id((self.0 as u64) << (64 - Self::BITS))
168 }
169
170 pub const fn max_id(self) -> Id {
172 Id(self.min_id().0 + ((1u64 << (64 - Self::BITS)) - 1))
173 }
174
175 pub const fn bytes(self) -> [u8; 1] {
177 [self.0 as u8]
178 }
179
180 pub fn hex_bytes(self) -> [u8; 2] {
182 if self.0 < 10 {
183 [b'0', b'0' + (self.0 as u8)]
184 } else {
185 unreachable!()
186 }
187 }
188
189 pub fn is_valid(self) -> bool {
191 self.0 <= Self::MAX.0
192 }
193}
194
195impl Id {
196 pub fn group(self) -> Group {
198 let group = (self.0 >> (64 - Group::BITS)) as usize;
199 Group(group)
200 }
201
202 pub fn is_valid(self) -> bool {
204 self.group().is_valid()
205 }
206
207 pub fn to(self, other: Id) -> IdIter {
209 IdIter {
210 current: self,
211 end: other,
212 }
213 }
214
215 pub fn to_bytearray(self) -> [u8; 8] {
217 self.0.to_be().to_ne_bytes()
219 }
220
221 pub fn to_prefixed_bytearray(self, prefix: u8) -> [u8; 9] {
224 let a = self.to_bytearray();
225 [prefix, a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]]
226 }
227
228 pub fn is_virtual(self) -> bool {
230 self.group() == Group::VIRTUAL
231 }
232
233 pub const MAX: Self = Group::ALL[Group::COUNT - 1].max_id();
234 pub const MIN: Self = Group::ALL[0].min_id();
235}
236
237impl fmt::Display for Id {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 let group = self.group();
240 match group {
241 Group::NON_MASTER => write!(f, "N")?,
242 Group::VIRTUAL => write!(f, "V")?,
243 _ => {}
244 }
245 write!(f, "{}", self.0 - group.min_id().0)
246 }
247}
248
249impl fmt::Debug for Id {
250 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
251 write!(f, "{self}")
252 }
253}
254
255impl fmt::Display for Group {
256 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
257 match *self {
258 Group::MASTER => write!(f, "Group Master"),
259 Group::NON_MASTER => write!(f, "Group Non-Master"),
260 Group::VIRTUAL => write!(f, "Group Virtual"),
261 _ => write!(f, "Group {}", self.0),
262 }
263 }
264}
265
266impl ops::Add<u64> for Id {
267 type Output = Id;
268
269 fn add(self, other: u64) -> Self {
270 Self(self.0 + other)
271 }
272}
273
274impl ops::Sub<u64> for Id {
275 type Output = Id;
276
277 fn sub(self, other: u64) -> Self {
278 Self(self.0 - other)
279 }
280}
281
282impl ops::Add<u8> for Group {
283 type Output = Group;
284
285 fn add(self, other: u8) -> Self {
286 Self(self.0 + other as usize)
287 }
288}
289
290impl ops::Sub<u8> for Group {
291 type Output = Group;
292
293 fn sub(self, other: u8) -> Self {
294 Self(self.0 - other as usize)
295 }
296}
297
298pub struct IdIter {
300 current: Id,
301 end: Id,
302}
303
304impl Iterator for IdIter {
305 type Item = Id;
306
307 fn next(&mut self) -> Option<Id> {
308 if self.current > self.end {
309 None
310 } else {
311 let result = self.current;
312 self.current = self.current + 1;
313 Some(result)
314 }
315 }
316}
317
318#[cfg(any(test, feature = "for-tests"))]
319use quickcheck::Arbitrary;
320#[cfg(any(test, feature = "for-tests"))]
321use quickcheck::Gen;
322
323#[cfg(any(test, feature = "for-tests"))]
324impl Arbitrary for Id {
325 fn arbitrary(g: &mut Gen) -> Self {
326 let group = Group((u32::arbitrary(g) & 1) as usize);
327 group.min_id() + u64::arbitrary(g) % (group.max_id().0 - group.min_id().0)
328 }
329}
330
331impl std::cmp::PartialEq<u64> for Id {
333 fn eq(&self, other: &u64) -> bool {
334 self.0 == *other
335 }
336}
337
338#[cfg(test)]
339mod tests {
340 use quickcheck::quickcheck;
341
342 use super::*;
343
344 #[test]
345 fn test_vertex_from_hex_odd() {
346 let vertex = Vertex::from_hex(b"a").unwrap();
347 let vertex2 = Vertex::from_hex(b"a0").unwrap();
348 assert_eq!(vertex, vertex2);
349 assert_eq!(vertex.to_hex(), "a0");
350 }
351
352 quickcheck! {
353 fn test_vertex_hex_roundtrip(slice: Vec<u8>) -> bool {
354 let vertex = Vertex::from(slice);
355 let hex = vertex.to_hex();
356 let vertex2 = Vertex::from_hex(hex.as_bytes()).unwrap();
357 vertex2 == vertex
358 }
359 }
360}