1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! This module implements the ``TypeIdSuffix`` struct and its associated functionality.
//! ``TypeIdSuffix`` represents the suffix part of a `TypeId`, which is a base32-encoded UUID.
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
use std::ops::Deref;
use std::str::FromStr;
use uuid::{Uuid, Variant, Version};
#[cfg(feature = "serde")]
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use crate::encoding::{decode_base32, encode_base32};
use crate::errors::{DecodeError, InvalidSuffixReason, InvalidUuidReason};
use crate::namespace::NamespaceId;
use crate::versions::{UuidVersion, V7};
/// Represents a `TypeId` suffix, which is a 26-character base32-encoded UUID.
///
/// This struct encapsulates the suffix part of a `TypeId`, providing methods for
/// creation, conversion, and validation.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TypeIdSuffix([u8; 26]);
impl TypeIdSuffix {
/// Creates a new ``TypeIdSuffix`` from a specific UUID version.
///
/// This method generates a new UUID of the specified version and encodes it
/// as a ``TypeIdSuffix``.
///
/// # Type Parameters
///
/// * `V`: A type that implements `UuidVersion` and `Default`.
///
/// # Returns
///
/// A new ``TypeIdSuffix`` instance.
///
/// # Examples
///
/// ```
/// use typeid_suffix::prelude::*;
///
/// let suffix = TypeIdSuffix::new::<V4>();
/// ```
#[cfg_attr(feature = "instrument", tracing::instrument)]
#[inline]
#[must_use]
pub fn new<V>() -> Self
where
V: UuidVersion + Default,
{
Self(encode_base32(V::default().as_bytes()))
}
/// Creates a new `TypeIdSuffix` from a V3 UUID (MD5-based name hash).
///
/// V3 UUIDs are generated by hashing a namespace identifier and a name
/// using the MD5 algorithm. This produces deterministic UUIDs from names.
///
/// # Arguments
///
/// * `namespace` - The namespace identifier for the UUID.
/// * `name` - The byte slice to hash with the namespace.
///
/// # Returns
///
/// A new `TypeIdSuffix` instance generated from a V3 UUID.
///
/// # Examples
///
/// ```
/// use typeid_suffix::prelude::*;
///
/// // Using a well-known namespace
/// let suffix = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
///
/// // Using a custom namespace
/// let custom_ns = NamespaceId::from_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap();
/// let suffix = TypeIdSuffix::new_v3(custom_ns, b"my-resource");
/// ```
#[cfg_attr(feature = "instrument", tracing::instrument)]
#[inline]
#[must_use]
pub fn new_v3(namespace: NamespaceId, name: &[u8]) -> Self {
let uuid = Uuid::new_v3(namespace.as_uuid(), name);
Self::from(uuid)
}
/// Creates a new `TypeIdSuffix` from a V5 UUID (SHA-1-based name hash).
///
/// V5 UUIDs are generated by hashing a namespace identifier and a name
/// using the SHA-1 algorithm. This produces deterministic UUIDs from names
/// and is preferred over V3 due to better security properties of SHA-1 vs MD5.
///
/// # Arguments
///
/// * `namespace` - The namespace identifier for the UUID.
/// * `name` - The byte slice to hash with the namespace.
///
/// # Returns
///
/// A new `TypeIdSuffix` instance generated from a V5 UUID.
///
/// # Examples
///
/// ```
/// use typeid_suffix::prelude::*;
///
/// // Using a well-known namespace for a domain
/// let suffix = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
///
/// // Using a well-known namespace for a URL
/// let suffix = TypeIdSuffix::new_v5(NamespaceId::URL, b"https://example.com/path");
///
/// // Using a custom namespace
/// let custom_ns = NamespaceId::from_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap();
/// let suffix = TypeIdSuffix::new_v5(custom_ns, b"my-resource");
/// ```
#[cfg_attr(feature = "instrument", tracing::instrument)]
#[inline]
#[must_use]
pub fn new_v5(namespace: NamespaceId, name: &[u8]) -> Self {
let uuid = Uuid::new_v5(namespace.as_uuid(), name);
Self::from(uuid)
}
/// Checks if a given UUID is valid according to the `TypeId` specification.
///
/// This method validates both the variant and version of the UUID.
///
/// # Arguments
///
/// * `uuid`: A reference to the `Uuid` to be validated.
///
/// # Returns
///
/// `true` if the UUID is valid, `false` otherwise.
const fn is_valid_uuid(uuid: &Uuid) -> bool {
let is_valid_variant = matches!(
uuid.get_variant(),
Variant::RFC4122 | Variant::Microsoft | Variant::Future | Variant::NCS
);
let is_valid_version = matches!(
uuid.get_version(),
Some(
Version::Max
| Version::Custom
| Version::SortMac
| Version::Mac
| Version::Dce
| Version::Md5
| Version::Random
| Version::Sha1
| Version::SortRand
| Version::Nil
)
);
is_valid_variant || is_valid_version
}
/// Converts the `TypeIdSuffix` to a UUID.
///
/// This method decodes the base32-encoded suffix back into a UUID.
///
/// # Returns
///
/// The `Uuid` represented by this `TypeIdSuffix`.
///
/// # Panics
///
/// This method uses `expect()` internally, but it should never panic under normal circumstances.
/// A panic would indicate a serious internal inconsistency in the `TypeIdSuffix` struct,
/// which should be reported as a bug in the library.
///
/// The reason it shouldn't panic is that:
/// 1. The `TypeIdSuffix` is always created from a valid UUID or a valid base32 string.
/// 2. All creation methods (`new()`, `from_str()`, `From<Uuid>`) perform thorough validation.
/// 3. The internal representation is immutable after creation.
///
/// # Examples
///
/// ```
/// use typeid_suffix::prelude::*;
///
/// let suffix = TypeIdSuffix::new::<V4>();
/// let uuid = suffix.to_uuid();
/// ```
#[inline]
#[must_use]
pub fn to_uuid(&self) -> Uuid {
let decoded_bytes = decode_base32(&self.0).expect("This should never fail because we've already validated the input");
Uuid::from_bytes(decoded_bytes)
}
/// Returns a string slice of the ``TypeIdSuffix``.
///
/// This method provides a way to access the underlying string representation
/// of the ``TypeIdSuffix``.
///
/// # Returns
///
/// A string slice containing the base32-encoded ``TypeIdSuffix``.
///
/// # Examples
///
/// ```
/// use typeid_suffix::prelude::*;
///
/// let suffix = TypeIdSuffix::new::<V4>();
/// let suffix_str = suffix.as_ref();
/// assert_eq!(suffix_str.len(), 26);
/// ```
#[must_use]
#[inline]
fn as_str(&self) -> &str {
// SAFETY: This unwrap is safe because we know that the internal bytes
// are always valid ASCII characters, which are valid UTF-8
std::str::from_utf8(&self.0).unwrap()
}
}
impl TypeIdSuffix {
/// Checks if the ``TypeIdSuffix`` contains a V6 or V7 UUID.
fn is_sortable(&self) -> bool {
matches!(self.to_uuid().get_version(), Some(Version::SortMac | Version::SortRand))
}
}
impl Ord for TypeIdSuffix {
fn cmp(&self, other: &Self) -> Ordering {
if self.is_sortable() && other.is_sortable() {
self.to_uuid().cmp(&other.to_uuid())
} else {
// Fall back to lexicographic ordering for non-V6/V7 UUIDs
self.0.cmp(&other.0)
}
}
}
impl PartialOrd for TypeIdSuffix {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Default for TypeIdSuffix {
/// Creates a default ``TypeIdSuffix`` using `UUIDv7`.
///
/// This implementation uses `V7` (`UUIDv7`) as the default UUID version
/// for generating a ``TypeIdSuffix``.
///
/// # Returns
///
/// A new ``TypeIdSuffix`` instance generated from a `UUIDv7`.
fn default() -> Self {
Self::new::<V7>()
}
}
impl Deref for TypeIdSuffix {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl AsRef<str> for TypeIdSuffix {
fn as_ref(&self) -> &str {
self
}
}
impl Borrow<str> for TypeIdSuffix {
fn borrow(&self) -> &str {
self
}
}
impl fmt::Display for TypeIdSuffix {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self)
}
}
impl From<&TypeIdSuffix> for Uuid {
/// Converts a reference to a ``TypeIdSuffix`` into a Uuid.
///
/// This implementation allows for efficient conversion from a `TypeIdSuffix`
/// reference to a Uuid without unnecessary cloning.
///
/// # Arguments
///
/// * `value`: A reference to the ``TypeIdSuffix`` to convert.
///
/// # Returns
///
/// The `Uuid` represented by the ``TypeIdSuffix``.
fn from(value: &TypeIdSuffix) -> Self {
value.to_uuid()
}
}
impl From<TypeIdSuffix> for Uuid {
/// Converts a ``TypeIdSuffix`` into a Uuid.
///
/// This implementation allows for conversion from a `TypeIdSuffix`
/// to a Uuid, consuming the original ``TypeIdSuffix``.
///
/// # Arguments
///
/// * `value`: The ``TypeIdSuffix`` to convert.
///
/// # Returns
///
/// The `Uuid` represented by the ``TypeIdSuffix``.
fn from(value: TypeIdSuffix) -> Self {
value.to_uuid()
}
}
impl FromStr for TypeIdSuffix {
type Err = DecodeError;
/// Parses a string slice into a ``TypeIdSuffix``.
///
/// This method attempts to create a ``TypeIdSuffix`` from a string representation.
/// It performs various validations to ensure the input string is a valid ``TypeIdSuffix``.
///
/// # Arguments
///
/// * `input`: The string slice to parse.
///
/// # Returns
///
/// A `Result` containing either the parsed ``TypeIdSuffix`` or a `DecodeError`.
///
/// # Errors
///
/// This function will return an error if:
/// - The input string is not exactly 26 characters long.
/// - The input string contains non-ASCII characters.
/// - The first character of the input string is greater than '7'.
/// - The input string contains invalid base32 characters.
/// - The decoded UUID is not valid according to the `TypeId` specification.
///
/// # Examples
///
/// ```
/// use std::str::FromStr;
/// use typeid_suffix::prelude::*;
///
/// let suffix = TypeIdSuffix::from_str("01h455vb4pex5vsknk084sn02q").unwrap();
/// ```
fn from_str(input: &str) -> Result<Self, Self::Err> {
if input.len() != 26 {
return Err(DecodeError::InvalidSuffix(InvalidSuffixReason::InvalidLength));
}
if !input.is_ascii() {
return Err(DecodeError::InvalidSuffix(InvalidSuffixReason::NonAsciiCharacter));
}
if input.as_bytes()[0] > b'7' {
return Err(DecodeError::InvalidSuffix(InvalidSuffixReason::InvalidFirstCharacter));
}
let encoded_bytes: [u8; 26] = input.as_bytes().try_into().map_err(|_| DecodeError::InvalidSuffix(InvalidSuffixReason::InvalidLength))?;
let decoded_bytes = decode_base32(&encoded_bytes)?;
let uuid = Uuid::from_bytes(decoded_bytes);
if !Self::is_valid_uuid(&uuid) {
return Err(DecodeError::InvalidUuid(InvalidUuidReason::InvalidVersion));
}
Ok(Self(encoded_bytes))
}
}
impl From<Uuid> for TypeIdSuffix {
/// Converts a Uuid into a ``TypeIdSuffix``.
///
/// This implementation allows for conversion from a Uuid to a ``TypeIdSuffix``.
///
/// # Arguments
///
/// * `value`: The Uuid to convert.
///
/// # Returns
///
/// A new ``TypeIdSuffix`` instance representing the given Uuid.
///
/// # Examples
///
/// ```
/// use uuid::Uuid;
/// use typeid_suffix::prelude::*;
///
/// let uuid = Uuid::new_v4();
/// let suffix: TypeIdSuffix = uuid.into();
/// ```
fn from(value: Uuid) -> Self {
// SAFETY: The Uuid crate guarantees that the bytes are always 16 bytes long
let encoded_bytes = encode_base32(value.as_bytes());
Self(encoded_bytes)
}
}
#[cfg(feature = "serde")]
impl Serialize for TypeIdSuffix {
/// Serializes the `TypeIdSuffix` as its string representation.
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "serde")] {
/// use typeid_suffix::prelude::*;
/// let suffix = TypeIdSuffix::default();
/// let json = serde_json::to_string(&suffix).unwrap();
/// // The JSON string will be the suffix string, e.g., "\"01h455vb4pex5vsknk084sn02q\""
/// assert!(json.starts_with("\"") && json.ends_with("\""));
/// assert_eq!(json.trim_matches('"'), suffix.as_ref());
/// # }
/// ```
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for TypeIdSuffix {
/// Deserializes a `TypeIdSuffix` from its string representation.
///
/// This expects a string that is a valid `TypeID` suffix.
///
/// # Errors
///
/// Returns an error if the string is not a valid `TypeIdSuffix`
/// (e.g., incorrect length, invalid characters, invalid first character,
/// or decodes to an invalid UUID variant/version).
///
/// # Examples
///
/// ```
/// # #[cfg(feature = "serde")] {
/// use typeid_suffix::prelude::*;
///
/// let suffix_str = "\"01h455vb4pex5vsknk084sn02q\""; // JSON string
/// let deserialized: TypeIdSuffix = serde_json::from_str(suffix_str).unwrap();
///
/// let invalid_suffix_str = "\"invalid\"";
/// let result: Result<TypeIdSuffix, _> = serde_json::from_str(invalid_suffix_str);
/// assert!(result.is_err());
/// # }
/// ```
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Self::from_str(&s).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod namespace_tests {
use super::*;
#[test]
fn new_v3_is_deterministic() {
let suffix1 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
assert_eq!(suffix1, suffix2);
}
#[test]
fn new_v5_is_deterministic() {
let suffix1 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
assert_eq!(suffix1, suffix2);
}
#[test]
fn new_v3_different_names_produce_different_suffixes() {
let suffix1 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"different.com");
assert_ne!(suffix1, suffix2);
}
#[test]
fn new_v5_different_names_produce_different_suffixes() {
let suffix1 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"different.com");
assert_ne!(suffix1, suffix2);
}
#[test]
fn new_v3_different_namespaces_produce_different_suffixes() {
let suffix1 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v3(NamespaceId::URL, b"example.com");
assert_ne!(suffix1, suffix2);
}
#[test]
fn new_v5_different_namespaces_produce_different_suffixes() {
let suffix1 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
let suffix2 = TypeIdSuffix::new_v5(NamespaceId::URL, b"example.com");
assert_ne!(suffix1, suffix2);
}
#[test]
fn new_v3_and_v5_produce_different_suffixes() {
let suffix_v3 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
let suffix_v5 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
assert_ne!(suffix_v3, suffix_v5);
}
#[test]
fn new_v3_produces_md5_version() {
let suffix = TypeIdSuffix::new_v3(NamespaceId::DNS, b"example.com");
let uuid = suffix.to_uuid();
assert_eq!(uuid.get_version(), Some(Version::Md5));
}
#[test]
fn new_v5_produces_sha1_version() {
let suffix = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
let uuid = suffix.to_uuid();
assert_eq!(uuid.get_version(), Some(Version::Sha1));
}
#[test]
fn new_v5_example_from_docs() {
// This matches the example from the mti lib.rs docs
let suffix = TypeIdSuffix::new_v5(NamespaceId::DNS, b"example.com");
let uuid = suffix.to_uuid();
assert_eq!(uuid.to_string(), "cfbff0d1-9375-5685-968c-48ce8b15ae17");
}
#[test]
fn new_v3_with_custom_namespace() {
let custom_ns = NamespaceId::from_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap();
let suffix = TypeIdSuffix::new_v3(custom_ns, b"test");
assert_eq!(suffix.to_uuid().get_version(), Some(Version::Md5));
}
#[test]
fn new_v5_with_custom_namespace() {
let custom_ns = NamespaceId::from_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap();
let suffix = TypeIdSuffix::new_v5(custom_ns, b"test");
assert_eq!(suffix.to_uuid().get_version(), Some(Version::Sha1));
}
#[test]
fn new_v5_with_empty_name() {
let suffix1 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"");
let suffix2 = TypeIdSuffix::new_v5(NamespaceId::DNS, b"");
assert_eq!(suffix1, suffix2);
}
#[test]
fn new_v3_with_empty_name() {
let suffix1 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"");
let suffix2 = TypeIdSuffix::new_v3(NamespaceId::DNS, b"");
assert_eq!(suffix1, suffix2);
}
}