switchy_uuid 0.3.0

Switchy UUID package
Documentation
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
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! UUID wrapper type providing a unified interface across implementations.
//!
//! This module provides a `Uuid` wrapper type that abstracts over the underlying
//! UUID implementation, allowing code to work generically with UUIDs regardless
//! of whether the simulator or standard uuid crate is being used.

use std::fmt;
use std::str::FromStr;

/// A universally unique identifier (UUID).
///
/// This is a wrapper type around the underlying UUID implementation that provides
/// a consistent interface regardless of which backend is being used (standard `uuid`
/// crate or simulator).
///
/// # Examples
///
/// ```
/// use switchy_uuid::Uuid;
///
/// // Generate a new random UUID
/// # #[cfg(any(feature = "uuid", feature = "simulator"))]
/// # {
/// let id = Uuid::new_v4();
///
/// // Convert to string
/// let id_string = id.to_string();
///
/// // Parse from string
/// let parsed: Uuid = id_string.parse().unwrap();
/// assert_eq!(id, parsed);
/// # }
/// ```
#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Uuid(uuid::Uuid);

impl Uuid {
    /// The number of bytes in a UUID.
    pub const SIZE: usize = 16;

    /// Creates a UUID from a 128-bit value.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::from_u128(0x550e8400_e29b_41d4_a716_446655440000);
    /// ```
    #[must_use]
    pub const fn from_u128(v: u128) -> Self {
        Self(uuid::Uuid::from_u128(v))
    }

    /// Creates a UUID from a 128-bit value in little-endian byte order.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::from_u128_le(0x550e8400_e29b_41d4_a716_446655440000);
    /// ```
    #[must_use]
    pub const fn from_u128_le(v: u128) -> Self {
        Self(uuid::Uuid::from_u128_le(v))
    }

    /// Returns the UUID as a 128-bit value.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let v: u128 = 0x550e_8400_e29b_41d4_a716_4466_5544_0000;
    /// let uuid = Uuid::from_u128(v);
    /// assert_eq!(uuid.as_u128(), v);
    /// ```
    #[must_use]
    pub const fn as_u128(&self) -> u128 {
        self.0.as_u128()
    }

    /// Returns the UUID as a 128-bit value in little-endian byte order.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::from_u128(0x550e8400_e29b_41d4_a716_446655440000);
    /// let le_value = uuid.as_u128_le();
    /// ```
    #[must_use]
    pub const fn as_u128_le(&self) -> u128 {
        self.0.to_u128_le()
    }

    /// Creates a UUID from 16 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let bytes = [0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4,
    ///              0xa7, 0x16, 0x44, 0x66, 0x55, 0x44, 0x00, 0x00];
    /// let uuid = Uuid::from_bytes(bytes);
    /// ```
    #[must_use]
    pub const fn from_bytes(bytes: [u8; 16]) -> Self {
        Self(uuid::Uuid::from_bytes(bytes))
    }

    /// Creates a UUID from a byte slice.
    ///
    /// # Errors
    ///
    /// * Returns [`ParseError`] if `slice` does not contain exactly 16 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let bytes = [0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4,
    ///              0xa7, 0x16, 0x44, 0x66, 0x55, 0x44, 0x00, 0x00];
    /// let uuid = Uuid::from_slice(&bytes).unwrap();
    /// ```
    pub fn from_slice(slice: &[u8]) -> Result<Self, ParseError> {
        uuid::Uuid::from_slice(slice)
            .map(Self)
            .map_err(|e| ParseError(e.to_string()))
    }

    /// Returns the bytes of the UUID.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.as_bytes(), &[0u8; 16]);
    /// ```
    #[must_use]
    pub const fn as_bytes(&self) -> &[u8; 16] {
        self.0.as_bytes()
    }

    /// Returns the bytes of the UUID as an owned array.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// let bytes: [u8; 16] = uuid.into_bytes();
    /// assert_eq!(bytes, [0u8; 16]);
    /// ```
    #[must_use]
    pub const fn into_bytes(self) -> [u8; 16] {
        *self.0.as_bytes()
    }

    /// Creates a nil UUID (all zeros).
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let nil = Uuid::nil();
    /// assert!(nil.is_nil());
    /// ```
    #[must_use]
    pub const fn nil() -> Self {
        Self(uuid::Uuid::nil())
    }

    /// Returns `true` if this is a nil UUID (all zeros).
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// # #[cfg(any(feature = "uuid", feature = "simulator"))]
    /// # {
    /// assert!(Uuid::nil().is_nil());
    /// assert!(!Uuid::new_v4().is_nil());
    /// # }
    /// ```
    #[must_use]
    pub const fn is_nil(&self) -> bool {
        self.0.is_nil()
    }

    /// Creates a max UUID (all ones).
    ///
    /// The max UUID is `ffffffff-ffff-ffff-ffff-ffffffffffff`.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let max = Uuid::max();
    /// assert!(max.is_max());
    /// assert_eq!(max.as_bytes(), &[0xffu8; 16]);
    /// ```
    #[must_use]
    pub const fn max() -> Self {
        Self(uuid::Uuid::max())
    }

    /// Returns `true` if this is a max UUID (all ones).
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// assert!(Uuid::max().is_max());
    /// assert!(!Uuid::nil().is_max());
    /// ```
    #[must_use]
    pub const fn is_max(&self) -> bool {
        self.0.is_max()
    }

    /// Returns the version number of the UUID.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// # #[cfg(any(feature = "uuid", feature = "simulator"))]
    /// # {
    /// let uuid = Uuid::new_v4();
    /// assert_eq!(uuid.get_version_num(), 4);
    /// # }
    /// ```
    #[must_use]
    pub const fn get_version_num(&self) -> usize {
        self.0.get_version_num()
    }

    /// Parses a UUID from a string.
    ///
    /// # Errors
    ///
    /// * Returns [`ParseError`] if `input` is not a valid UUID string in any
    ///   supported format.
    ///
    /// # Accepted formats
    ///
    /// * Simple: `550e8400e29b41d4a716446655440000`
    /// * Hyphenated: `550e8400-e29b-41d4-a716-446655440000`
    /// * Braced: `{550e8400-e29b-41d4-a716-446655440000}`
    /// * URN: `urn:uuid:550e8400-e29b-41d4-a716-446655440000`
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
    /// ```
    pub fn parse_str(input: &str) -> Result<Self, ParseError> {
        uuid::Uuid::parse_str(input)
            .map(Self)
            .map_err(|e| ParseError(e.to_string()))
    }

    /// Returns a reference to the inner `uuid::Uuid`.
    ///
    /// This method provides access to the underlying UUID type for interoperability
    /// with code that requires the standard `uuid::Uuid` type.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// let inner: &uuid::Uuid = uuid.inner();
    /// ```
    #[must_use]
    pub const fn inner(&self) -> &uuid::Uuid {
        &self.0
    }

    /// Consumes the wrapper and returns the inner `uuid::Uuid`.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// let inner: uuid::Uuid = uuid.into_inner();
    /// ```
    #[must_use]
    pub const fn into_inner(self) -> uuid::Uuid {
        self.0
    }

    /// Creates a wrapper from a `uuid::Uuid`.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let inner = uuid::Uuid::nil();
    /// let wrapped = Uuid::from_inner(inner);
    /// ```
    #[must_use]
    pub const fn from_inner(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }

    /// Returns the UUID as a hyphenated string.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.hyphenated(), "00000000-0000-0000-0000-000000000000");
    /// ```
    #[must_use]
    pub fn hyphenated(&self) -> String {
        self.0.hyphenated().to_string()
    }

    /// Returns the UUID as a simple (non-hyphenated) string.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.simple(), "00000000000000000000000000000000");
    /// ```
    #[must_use]
    pub fn simple(&self) -> String {
        self.0.simple().to_string()
    }

    /// Returns the UUID as a URN string.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.urn(), "urn:uuid:00000000-0000-0000-0000-000000000000");
    /// ```
    #[must_use]
    pub fn urn(&self) -> String {
        self.0.urn().to_string()
    }

    /// Returns the UUID as a braced string.
    ///
    /// # Examples
    ///
    /// ```
    /// use switchy_uuid::Uuid;
    ///
    /// let uuid = Uuid::nil();
    /// assert_eq!(uuid.braced(), "{00000000-0000-0000-0000-000000000000}");
    /// ```
    #[must_use]
    pub fn braced(&self) -> String {
        self.0.braced().to_string()
    }
}

impl fmt::Debug for Uuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.0, f)
    }
}

impl fmt::Display for Uuid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl FromStr for Uuid {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_str(s)
    }
}

impl Default for Uuid {
    fn default() -> Self {
        Self::nil()
    }
}

impl From<uuid::Uuid> for Uuid {
    fn from(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }
}

impl From<Uuid> for uuid::Uuid {
    fn from(uuid: Uuid) -> Self {
        uuid.0
    }
}

impl From<[u8; 16]> for Uuid {
    fn from(bytes: [u8; 16]) -> Self {
        Self::from_bytes(bytes)
    }
}

impl From<Uuid> for [u8; 16] {
    fn from(uuid: Uuid) -> Self {
        uuid.into_bytes()
    }
}

impl From<u128> for Uuid {
    fn from(v: u128) -> Self {
        Self::from_u128(v)
    }
}

impl From<Uuid> for u128 {
    fn from(uuid: Uuid) -> Self {
        uuid.as_u128()
    }
}

impl AsRef<[u8]> for Uuid {
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<uuid::Uuid> for Uuid {
    fn as_ref(&self) -> &uuid::Uuid {
        &self.0
    }
}

/// An error that occurred while parsing a UUID string.
///
/// This error is returned when attempting to parse an invalid UUID string
/// via [`Uuid::parse_str`] or the [`FromStr`] implementation.
///
/// # Examples
///
/// ```
/// use switchy_uuid::Uuid;
///
/// let err = Uuid::parse_str("not-a-uuid").unwrap_err();
/// assert!(err.to_string().contains("invalid UUID"));
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError(String);

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "invalid UUID: {}", self.0)
    }
}

impl std::error::Error for ParseError {}

#[cfg(feature = "serde")]
mod serde_impl {
    use super::Uuid;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    impl Serialize for Uuid {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            self.0.serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for Uuid {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            uuid::Uuid::deserialize(deserializer).map(Self)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_nil() {
        let nil = Uuid::nil();
        assert!(nil.is_nil());
        assert_eq!(nil.as_bytes(), &[0u8; 16]);
        assert_eq!(nil.to_string(), "00000000-0000-0000-0000-000000000000");
    }

    #[test]
    fn test_max() {
        let max = Uuid::max();
        assert!(max.is_max());
        assert_eq!(max.as_bytes(), &[0xffu8; 16]);
    }

    #[test]
    fn test_from_bytes() {
        let bytes = [
            0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44,
            0x00, 0x00,
        ];
        let uuid = Uuid::from_bytes(bytes);
        assert_eq!(uuid.as_bytes(), &bytes);
    }

    #[test]
    fn test_parse_str() {
        let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        assert_eq!(uuid.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_parse_str_simple() {
        let uuid = Uuid::parse_str("550e8400e29b41d4a716446655440000").unwrap();
        assert_eq!(uuid.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_parse_str_braced() {
        let uuid = Uuid::parse_str("{550e8400-e29b-41d4-a716-446655440000}").unwrap();
        assert_eq!(uuid.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_parse_str_urn() {
        let uuid = Uuid::parse_str("urn:uuid:550e8400-e29b-41d4-a716-446655440000").unwrap();
        assert_eq!(uuid.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_parse_str_invalid() {
        assert!(Uuid::parse_str("not-a-uuid").is_err());
        assert!(Uuid::parse_str("").is_err());
    }

    #[test]
    fn test_from_str() {
        let uuid: Uuid = "550e8400-e29b-41d4-a716-446655440000".parse().unwrap();
        assert_eq!(uuid.to_string(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_format_methods() {
        let uuid = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        assert_eq!(uuid.hyphenated(), "550e8400-e29b-41d4-a716-446655440000");
        assert_eq!(uuid.simple(), "550e8400e29b41d4a716446655440000");
        assert_eq!(uuid.urn(), "urn:uuid:550e8400-e29b-41d4-a716-446655440000");
        assert_eq!(uuid.braced(), "{550e8400-e29b-41d4-a716-446655440000}");
    }

    #[test]
    fn test_from_u128() {
        let v: u128 = 0x550e_8400_e29b_41d4_a716_4466_5544_0000;
        let uuid = Uuid::from_u128(v);
        assert_eq!(uuid.as_u128(), v);
    }

    #[test]
    fn test_equality() {
        let uuid1 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        let uuid3 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440001").unwrap();

        assert_eq!(uuid1, uuid2);
        assert_ne!(uuid1, uuid3);
    }

    #[test]
    fn test_ordering() {
        let uuid1 = Uuid::parse_str("00000000-0000-0000-0000-000000000001").unwrap();
        let uuid2 = Uuid::parse_str("00000000-0000-0000-0000-000000000002").unwrap();

        assert!(uuid1 < uuid2);
    }

    #[test]
    fn test_hash() {
        use std::collections::BTreeSet;

        let mut set = BTreeSet::new();
        let uuid1 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();
        let uuid2 = Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap();

        set.insert(uuid1);
        assert!(!set.insert(uuid2)); // Should return false as it's a duplicate
        assert_eq!(set.len(), 1);
    }

    #[test]
    fn test_default() {
        let uuid = Uuid::default();
        assert!(uuid.is_nil());
    }

    #[test]
    fn test_from_inner() {
        let inner = uuid::Uuid::nil();
        let wrapped = Uuid::from_inner(inner);
        assert!(wrapped.is_nil());
        assert_eq!(wrapped.into_inner(), inner);
    }

    #[test]
    fn test_conversions() {
        let bytes = [
            0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44,
            0x00, 0x00,
        ];

        // From bytes
        let uuid: Uuid = bytes.into();
        assert_eq!(uuid.as_bytes(), &bytes);

        // To bytes
        let result: [u8; 16] = uuid.into();
        assert_eq!(result, bytes);
    }

    #[test]
    fn test_from_slice() {
        let bytes = [
            0x55, 0x0e, 0x84, 0x00, 0xe2, 0x9b, 0x41, 0xd4, 0xa7, 0x16, 0x44, 0x66, 0x55, 0x44,
            0x00, 0x00,
        ];
        let uuid = Uuid::from_slice(&bytes).unwrap();
        assert_eq!(uuid.as_bytes(), &bytes);

        // Invalid slice length
        assert!(Uuid::from_slice(&[0u8; 15]).is_err());
        assert!(Uuid::from_slice(&[0u8; 17]).is_err());
    }
}