Skip to main content

nibkeep_base/
id.rs

1//! Random identifiers for entities, spaces and people.
2
3use 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		///
14		/// New identifiers are version 4 UUIDs. The text form is the lowercase hyphenated
15		/// form of the UUID; in CBOR, an identifier is a UUID tag.
16		#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17		pub struct $name(Uuid);
18
19		impl $name {
20			/// Makes a new identifier from 16 random bytes. Six of the bits are replaced
21			/// by the version and variant of a version 4 UUID.
22			#[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			/// The identifier derived from `material` with `context`: the first 16 bytes of
28			/// the BLAKE3 key derived with that context from it, as a version 4 UUID. Every
29			/// replica that derives one from the same material gets the same identifier.
30			#[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			/// Makes a new identifier from 16 bytes of the random number generator.
39			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			/// Returns the identifier with these 16 bytes, as stored. Any UUID is accepted,
46			/// because an identifier is opaque.
47			#[must_use]
48			pub fn from_bytes(bytes: [u8; 16]) -> Self {
49				Self(Uuid::from_bytes(bytes))
50			}
51
52			/// The identifier's 16 bytes.
53			#[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			/// Reads the text form. Other forms of UUIDs, such as uppercase ones or ones
75			/// without hyphens, are rejected, so that every identifier has one text form.
76			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	/// Identifies an entity: a person, a photo, a book, a list or anything else.
102	EntityId
103);
104
105identifier!(
106	/// Identifies a space, the unit of sharing, sync and encryption.
107	SpaceId
108);
109
110identifier!(
111	/// Identifies a person who uses NibKeep.
112	PersonId
113);
114
115identifier!(
116	/// Identifies a statement: one value of one field of an entity, with its qualifiers.
117	StatementId
118);
119
120/// The error returned for text that is not an identifier in its text form.
121#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
122#[error("not an identifier in the form 00000000-0000-0000-0000-000000000000")]
123pub struct ParseIdError;