Skip to main content

substrate_data/schema/refs/
uid.rs

1//! [`Uid`]: a 128-bit id, spelled in hex.
2
3use std::borrow::Cow;
4use std::fmt;
5
6use super::RefId;
7use crate::schema::Expected;
8
9/// A 128-bit id (a UUID's bits, a hash), spelled as 32 lower-case hex
10/// digits: `@doc:0123456789abcdef0123456789abcdef`.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
12pub struct Uid(pub u128);
13
14/// Hex digits of a [`Uid`].
15const UID_DIGITS: usize = 32;
16
17impl fmt::Display for Uid {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        write!(f, "{:0width$x}", self.0, width = UID_DIGITS)
20    }
21}
22
23impl RefId for Uid {
24    const EXPECTED: Expected = Expected::Uid;
25    fn parse(spelled: &str) -> Option<Self> {
26        if spelled.len() != UID_DIGITS
27            || !spelled
28                .bytes()
29                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
30        {
31            return None;
32        }
33        u128::from_str_radix(spelled, 16).ok().map(Uid)
34    }
35    fn spell(&self) -> Cow<'_, str> {
36        Cow::Owned(self.to_string())
37    }
38}
39
40/// Stored as its hex text everywhere (a tool shows a `uid`).
41impl crate::schema::NamedType for Uid {
42    const NAME: &'static str = "uid";
43    type Stored = String;
44    fn to_stored(&self) -> String {
45        self.to_string()
46    }
47    fn from_stored(s: String) -> Option<Self> {
48        <Uid as RefId>::parse(&s)
49    }
50}
51
52crate::named_schema!(Uid);