Skip to main content

xuid/
lib.rs

1//! # XUID
2//!
3//! XUID (eXtended Unique IDentifier) enhances UUIDs with a short type prefix while
4//! keeping the standard 128-bit UUID size. XUIDs are encoded in base32 (rather than
5//! base16), so they never exceed 36 characters and are more human-readable.
6//!
7//! This is a Rust port of the Go library [`KarpelesLab/xuid`]. The string format is
8//! byte-for-byte compatible: an XUID produced by either implementation parses cleanly
9//! in the other.
10//!
11//! ```
12//! use xuid::Xuid;
13//!
14//! // Time-ordered (UUIDv7) by default — sortable and index-friendly.
15//! let id = Xuid::new("user");
16//! println!("{id}"); // e.g. user-h4nu2n-zu3f-dmnn-kguv-6f643nei
17//!
18//! // Parse back, including from a plain UUID string.
19//! let parsed: Xuid = "user-h4nu2n-zu3f-dmnn-kguv-6f643nei".parse().unwrap();
20//! assert_eq!(parsed.prefix(), "user");
21//!
22//! // Deterministic IDs from a key.
23//! let a = Xuid::from_key_prefix("specific-resource-name", "res");
24//! let b = Xuid::from_key_prefix("specific-resource-name", "res");
25//! assert_eq!(a, b);
26//! ```
27//!
28//! [`KarpelesLab/xuid`]: https://github.com/KarpelesLab/xuid
29
30use core::fmt;
31use core::str::FromStr;
32
33use data_encoding::BASE32_NOPAD;
34use uuid::Uuid;
35
36mod error;
37pub use error::Error;
38
39#[cfg(feature = "serde")]
40mod serde_impl;
41
42#[cfg(feature = "sqlx")]
43mod sqlx_impl;
44
45#[cfg(feature = "rusqlite")]
46mod rusqlite_impl;
47
48/// Reference namespace used to derive deterministic XUIDs from keys (matches the Go lib).
49const REF_NS: Uuid = Uuid::from_bytes([
50    0xd1, 0x6b, 0x61, 0x39, 0x89, 0x89, 0x46, 0x7f, 0xa2, 0x40, 0x44, 0x1d, 0xf6, 0x73, 0x4f, 0x45,
51]);
52
53/// Maximum number of prefix characters kept in the string representation.
54const MAX_PREFIX: usize = 5;
55
56/// An extended UUID: a standard [`Uuid`] paired with an optional type prefix.
57///
58/// The prefix is an arbitrary string, but only its first [`MAX_PREFIX`](self) characters
59/// appear in the string representation, where they are also lowercased. The prefix is
60/// stored verbatim, so two XUIDs whose prefixes differ only in case are **not** equal
61/// even though they render identically.
62#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
63pub struct Xuid {
64    prefix: String,
65    uuid: Uuid,
66}
67
68impl Xuid {
69    /// Creates a new time-ordered (UUIDv7) XUID with the given prefix.
70    ///
71    /// This is the recommended constructor: the embedded timestamp makes the IDs
72    /// sortable by creation time and friendly to database indexes.
73    pub fn new(prefix: impl Into<String>) -> Self {
74        Self::new_v7(prefix)
75    }
76
77    /// Creates a new time-ordered (UUIDv7) XUID with the given prefix.
78    pub fn new_v7(prefix: impl Into<String>) -> Self {
79        Self {
80            prefix: prefix.into(),
81            uuid: Uuid::now_v7(),
82        }
83    }
84
85    /// Creates a new fully random (UUIDv4) XUID with the given prefix.
86    pub fn new_random(prefix: impl Into<String>) -> Self {
87        Self {
88            prefix: prefix.into(),
89            uuid: Uuid::new_v4(),
90        }
91    }
92
93    /// Builds an XUID from an existing [`Uuid`] and a prefix.
94    pub fn from_uuid(uuid: Uuid, prefix: impl Into<String>) -> Self {
95        Self {
96            prefix: prefix.into(),
97            uuid,
98        }
99    }
100
101    /// Derives a deterministic XUID from `key`, always using the `"utref"` prefix.
102    ///
103    /// The same key always yields the same XUID (UUIDv5 / SHA-1 over a fixed namespace).
104    pub fn from_key(key: impl AsRef<[u8]>) -> Self {
105        Self::from_uuid(Uuid::new_v5(&REF_NS, key.as_ref()), "utref")
106    }
107
108    /// Derives a deterministic XUID from both `key` and `prefix`.
109    ///
110    /// The prefix seeds a per-prefix namespace, so the same `(key, prefix)` pair always
111    /// produces the same XUID and different prefixes never collide.
112    pub fn from_key_prefix(key: impl AsRef<[u8]>, prefix: impl Into<String>) -> Self {
113        let prefix = prefix.into();
114        let sub_ns = Uuid::new_v5(&REF_NS, prefix.as_bytes());
115        Self::from_uuid(Uuid::new_v5(&sub_ns, key.as_ref()), prefix)
116    }
117
118    /// Parses `s` and verifies the prefix matches `prefix`, returning [`Error::BadPrefix`]
119    /// otherwise. Useful for type-safe parsing of a known entity type.
120    pub fn parse_prefix(s: &str, prefix: &str) -> Result<Self, Error> {
121        let x = s.parse::<Self>()?;
122        if x.prefix != prefix {
123            return Err(Error::BadPrefix {
124                expected: prefix.to_owned(),
125                found: x.prefix,
126            });
127        }
128        Ok(x)
129    }
130
131    /// Parses a standard UUID string into an XUID with the given prefix.
132    pub fn parse_uuid(uuid: &str, prefix: impl Into<String>) -> Result<Self, Error> {
133        Ok(Self::from_uuid(Uuid::parse_str(uuid)?, prefix))
134    }
135
136    /// Returns the type prefix (stored verbatim, not truncated or lowercased).
137    pub fn prefix(&self) -> &str {
138        &self.prefix
139    }
140
141    /// Returns the underlying [`Uuid`].
142    pub fn uuid(&self) -> Uuid {
143        self.uuid
144    }
145
146    /// Returns the underlying UUID in canonical hyphenated form, e.g.
147    /// `3f1b4d37-34d9-46c6-b546-a57c5f736d22`.
148    pub fn to_uuid_string(&self) -> String {
149        self.uuid.to_string()
150    }
151}
152
153impl fmt::Display for Xuid {
154    /// Formats as `prefix-aaaaaa-aaaa-aaaa-aaaa-aaaaaaaa` (the prefix is omitted when empty).
155    ///
156    /// Output is always lowercase, and the prefix is clipped to the first
157    /// [`MAX_PREFIX`](self) characters.
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        // 16 bytes -> 26 base32 chars (no padding), lowercased to match the Go encoder.
160        let enc = BASE32_NOPAD
161            .encode(self.uuid.as_bytes())
162            .to_ascii_lowercase();
163        let b = enc.as_bytes();
164
165        if !self.prefix.is_empty() {
166            let pfx: String = self.prefix.chars().take(MAX_PREFIX).collect();
167            f.write_str(&pfx.to_lowercase())?;
168            f.write_str("-")?;
169        }
170
171        // Hyphenate in the same positions as a regular UUID: 6-4-4-4-8.
172        f.write_str(core::str::from_utf8(&b[0..6]).unwrap())?;
173        f.write_str("-")?;
174        f.write_str(core::str::from_utf8(&b[6..10]).unwrap())?;
175        f.write_str("-")?;
176        f.write_str(core::str::from_utf8(&b[10..14]).unwrap())?;
177        f.write_str("-")?;
178        f.write_str(core::str::from_utf8(&b[14..18]).unwrap())?;
179        f.write_str("-")?;
180        f.write_str(core::str::from_utf8(&b[18..26]).unwrap())?;
181        Ok(())
182    }
183}
184
185impl FromStr for Xuid {
186    type Err = Error;
187
188    /// Parses an XUID, or falls back to interpreting `s` as a plain UUID (empty prefix).
189    fn from_str(s: &str) -> Result<Self, Self::Err> {
190        // Work on bytes so that arbitrary (even non-ASCII) input can never panic a
191        // str-slice on a char boundary; we fall back to UUID parsing instead.
192        let sb = s.as_bytes();
193        // Body length is 30 (6-4-4-4-8 with four hyphens). Total length is therefore
194        // 30 (no prefix) or 32..=36 (1..=5 char prefix + '-' + body).
195        let (prefix_bytes, body) = match sb.len() {
196            30 => (&b""[..], sb),
197            32..=36 => {
198                let pfx_len = sb.len() - 31;
199                if sb[pfx_len] != b'-' {
200                    return Self::parse_uuid(s, "");
201                }
202                (&sb[..pfx_len], &sb[pfx_len + 1..])
203            }
204            _ => return Self::parse_uuid(s, ""),
205        };
206
207        // `body` is now exactly 30 bytes; verify the hyphen layout.
208        if body[6] != b'-' || body[11] != b'-' || body[16] != b'-' || body[21] != b'-' {
209            return Self::parse_uuid(s, "");
210        }
211
212        // Strip the hyphens into the 26 base32 chars and uppercase (the alphabet is uppercase).
213        let mut raw = [0u8; 26];
214        raw[0..6].copy_from_slice(&body[0..6]);
215        raw[6..10].copy_from_slice(&body[7..11]);
216        raw[10..14].copy_from_slice(&body[12..16]);
217        raw[14..18].copy_from_slice(&body[17..21]);
218        raw[18..26].copy_from_slice(&body[22..30]);
219        raw.make_ascii_uppercase();
220
221        let bytes = BASE32_NOPAD.decode(&raw)?;
222        let uuid = Uuid::from_slice(&bytes).map_err(|_| Error::InvalidEncoding)?;
223
224        // The prefix is a verbatim slice of the (UTF-8) input; reject a split char boundary.
225        let prefix = core::str::from_utf8(prefix_bytes).map_err(|_| Error::InvalidEncoding)?;
226        Ok(Self::from_uuid(uuid, prefix))
227    }
228}
229
230impl From<Xuid> for Uuid {
231    fn from(x: Xuid) -> Uuid {
232        x.uuid
233    }
234}