use std::fmt;
use std::str::FromStr;
use uuid::Uuid;
use crate::cbor::{self, FromCbor, ToCbor, Value};
macro_rules! identifier {
($(#[$doc:meta])* $name:ident) => {
$(#[$doc])*
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(Uuid);
impl $name {
#[must_use]
pub fn from_random_bytes(bytes: [u8; 16]) -> Self {
Self(uuid::Builder::from_random_bytes(bytes).into_uuid())
}
#[must_use]
pub fn derived(context: &str, material: &[u8]) -> Self {
let key = blake3::derive_key(context, material);
let mut bytes = [0; 16];
bytes.copy_from_slice(&key[..16]);
Self::from_random_bytes(bytes)
}
pub fn random(rng: &mut impl rand_core::CryptoRng) -> Self {
let mut bytes = [0; 16];
rng.fill_bytes(&mut bytes);
Self::from_random_bytes(bytes)
}
#[must_use]
pub fn from_bytes(bytes: [u8; 16]) -> Self {
Self(Uuid::from_bytes(bytes))
}
#[must_use]
pub fn as_bytes(&self) -> &[u8; 16] {
self.0.as_bytes()
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0.hyphenated(), f)
}
}
impl fmt::Debug for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, concat!(stringify!($name), "({})"), self.0.hyphenated())
}
}
impl FromStr for $name {
type Err = ParseIdError;
fn from_str(text: &str) -> Result<Self, Self::Err> {
let uuid = Uuid::try_parse(text).map_err(|_| ParseIdError)?;
let id = Self(uuid);
if id.to_string() == text { Ok(id) } else { Err(ParseIdError) }
}
}
impl ToCbor for $name {
fn to_cbor(&self) -> Value {
Value::Uuid(*self.as_bytes())
}
}
impl FromCbor for $name {
fn from_cbor(value: &Value) -> Result<Self, cbor::Error> {
match value {
Value::Uuid(bytes) => Ok(Self::from_bytes(*bytes)),
_ => Err(cbor::Error::Expected("a UUID")),
}
}
}
};
}
identifier!(
EntityId
);
identifier!(
SpaceId
);
identifier!(
PersonId
);
identifier!(
StatementId
);
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("not an identifier in the form 00000000-0000-0000-0000-000000000000")]
pub struct ParseIdError;