1use std::fmt;
4use std::str::FromStr;
5
6use uuid::Uuid;
7
8use crate::cbor::{self, FromCbor, ToCbor, Value};
9
10macro_rules! identifier {
11 ($(#[$doc:meta])* $name:ident) => {
12 $(#[$doc])*
13 #[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17 pub struct $name(Uuid);
18
19 impl $name {
20 #[must_use]
23 pub fn from_random_bytes(bytes: [u8; 16]) -> Self {
24 Self(uuid::Builder::from_random_bytes(bytes).into_uuid())
25 }
26
27 #[must_use]
31 pub fn derived(context: &str, material: &[u8]) -> Self {
32 let key = blake3::derive_key(context, material);
33 let mut bytes = [0; 16];
34 bytes.copy_from_slice(&key[..16]);
35 Self::from_random_bytes(bytes)
36 }
37
38 pub fn random(rng: &mut impl rand_core::CryptoRng) -> Self {
40 let mut bytes = [0; 16];
41 rng.fill_bytes(&mut bytes);
42 Self::from_random_bytes(bytes)
43 }
44
45 #[must_use]
48 pub fn from_bytes(bytes: [u8; 16]) -> Self {
49 Self(Uuid::from_bytes(bytes))
50 }
51
52 #[must_use]
54 pub fn as_bytes(&self) -> &[u8; 16] {
55 self.0.as_bytes()
56 }
57 }
58
59 impl fmt::Display for $name {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 fmt::Display::fmt(&self.0.hyphenated(), f)
62 }
63 }
64
65 impl fmt::Debug for $name {
66 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67 write!(f, concat!(stringify!($name), "({})"), self.0.hyphenated())
68 }
69 }
70
71 impl FromStr for $name {
72 type Err = ParseIdError;
73
74 fn from_str(text: &str) -> Result<Self, Self::Err> {
77 let uuid = Uuid::try_parse(text).map_err(|_| ParseIdError)?;
78 let id = Self(uuid);
79 if id.to_string() == text { Ok(id) } else { Err(ParseIdError) }
80 }
81 }
82
83 impl ToCbor for $name {
84 fn to_cbor(&self) -> Value {
85 Value::Uuid(*self.as_bytes())
86 }
87 }
88
89 impl FromCbor for $name {
90 fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
91 match value {
92 Value::Uuid(bytes) => Ok(Self::from_bytes(*bytes)),
93 _ => Err(cbor::Error::Expected("a UUID")),
94 }
95 }
96 }
97 };
98}
99
100identifier!(
101 EntityId
103);
104
105identifier!(
106 SpaceId
108);
109
110identifier!(
111 PersonId
113);
114
115identifier!(
116 StatementId
118);
119
120#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
122#[error("not an identifier in the form 00000000-0000-0000-0000-000000000000")]
123pub struct ParseIdError;