shortguid 0.4.0

Short URL-safe Base64 encoded UUIDs
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
//! Provides short, URL-safe UUID representations.
//!
//! ```
//! # use shortguid::ShortGuid;
//! let from_uuid = ShortGuid::try_parse("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap();
//! let from_short = ShortGuid::try_parse("yaZG05xhTLe_ze4lIsj2Mw").unwrap();
//! assert_eq!(from_uuid, "yaZG05xhTLe_ze4lIsj2Mw");
//! assert_eq!(from_uuid, from_short);
//!
//! let random = ShortGuid::new_random();
//! assert_ne!(from_uuid, random);
//! ```

// only enables the `doc_cfg` feature when
// the `docsrs` configuration attribute is defined
#![cfg_attr(docsrs, feature(doc_cfg))]

use base64::{DecodeError, Engine};
use std::borrow::Borrow;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use uuid::Uuid;

/// A short, URL-safe UUID representation.
///
/// ## Example
///
/// The [`ShortGuid`] can be constructed from an existing [`Uuid`]:
///
/// ```
/// # use uuid::Uuid;
/// # use shortguid::ShortGuid;
/// let uuid = Uuid::try_parse("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap();
/// let short_guid = ShortGuid::from(uuid);
/// assert_eq!(short_guid, "yaZG05xhTLe_ze4lIsj2Mw");
/// assert_eq!(short_guid, uuid);
/// ```
///
/// Alternatively, it can be directly parsed from a UUID:
///
/// ```
/// # use shortguid::ShortGuid;
/// let short_guid_a = ShortGuid::try_parse("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap();
/// let short_guid_b = ShortGuid::try_parse("yaZG05xhTLe_ze4lIsj2Mw").unwrap();
/// assert_eq!(short_guid_a, "yaZG05xhTLe_ze4lIsj2Mw");
/// assert_eq!(short_guid_a, short_guid_b);
/// ```
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[repr(transparent)]
pub struct ShortGuid(Uuid);

/// A short UUID format.
impl ShortGuid {
    /// Generates a new [`ShortGuid`] based on a random UUID v4.
    #[cfg_attr(docsrs, doc(cfg(feature = "random")))]
    #[cfg(feature = "random")]
    #[inline(always)]
    pub fn new_random() -> Self {
        Self::new_from_uuid(Uuid::new_v4())
    }

    /// Creates a new [`ShortGuid`] based on the provided [`Uuid`].
    #[inline(always)]
    pub const fn new_from_uuid(uuid: Uuid) -> Self {
        Self(uuid)
    }

    /// Tries to parse the value as a [`ShortGuid`] or [`Uuid`] string, and outputs an actual
    /// [`ShortGuid`] instance.
    pub fn try_parse<S: AsRef<str>>(value: S) -> Result<Self, ParseError> {
        if let Ok(uuid) = Uuid::try_parse(value.as_ref()) {
            return Ok(Self(uuid));
        }

        let uuid = Self::try_decode(value)?;
        Ok(Self(uuid))
    }

    /// Constructs a [`ShortGuid`] instance based on a byte slice.
    ///
    /// ## Notes
    /// This will clone the underlying data. If you wish to return a
    /// transparent reference around the provided slice, use [`ShortGuid::from_bytes_ref`]
    /// instead.
    #[inline]
    pub fn from_bytes(bytes: &[u8; 16]) -> Self {
        Self(Uuid::from_bytes_ref(bytes).clone())
    }

    /// Returns a slice of 16 octets containing the value.
    ///
    /// This method borrows the underlying byte value of the UUID.
    ///
    /// # Examples
    ///
    /// ```
    /// # use shortguid::ShortGuid;
    /// let bytes1 = [
    ///     0xa1, 0xa2, 0xa3, 0xa4,
    ///     0xb1, 0xb2,
    ///     0xc1, 0xc2,
    ///     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
    /// ];
    /// let uuid1 = ShortGuid::from_bytes_ref(&bytes1);
    ///
    /// let bytes2 = uuid1.as_bytes();
    /// let uuid2 = ShortGuid::from_bytes_ref(bytes2);
    ///
    /// assert_eq!(uuid1, uuid2);
    ///
    /// assert!(std::ptr::eq(
    ///     uuid2 as *const ShortGuid as *const u8,
    ///     &bytes1 as *const [u8; 16] as *const u8,
    /// ));
    /// ```
    #[inline]
    pub const fn from_bytes_ref(bytes: &[u8; 16]) -> &Self {
        // SAFETY: `Bytes`, `Uuid` and `ShortGuid have the same ABI
        unsafe { &*(bytes as *const [u8; 16] as *const Uuid as *const ShortGuid) }
    }

    /// Tests if this [`ShortGuid`] is all zeros.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.0.is_nil()
    }

    /// Returns the underlying [`Uuid`] instance.
    #[inline]
    pub const fn as_uuid(&self) -> &Uuid {
        &self.0
    }

    /// Returns a slice of 16 octets containing the value.
    ///
    /// This method borrows the underlying byte value of the UUID.
    ///
    /// # Examples
    ///
    /// ```
    /// # use shortguid::ShortGuid;
    /// let bytes1 = [
    ///     0xa1, 0xa2, 0xa3, 0xa4,
    ///     0xb1, 0xb2,
    ///     0xc1, 0xc2,
    ///     0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8,
    /// ];
    /// let uuid1 = ShortGuid::from_bytes_ref(&bytes1);
    ///
    /// let bytes2 = uuid1.as_bytes();
    /// let uuid2 = ShortGuid::from_bytes_ref(bytes2);
    ///
    /// assert_eq!(uuid1, uuid2);
    ///
    /// assert!(std::ptr::eq(
    ///     uuid2 as *const ShortGuid as *const u8,
    ///     &bytes1 as *const [u8; 16] as *const u8,
    /// ));
    /// ```
    #[inline]
    pub fn as_bytes(&self) -> &[u8; 16] {
        self.0.as_bytes()
    }

    /// Returns the bytes of the [`ShortGuid`] in little-endian order.
    ///
    /// The bytes will be flipped to convert into little-endian order. This is
    /// based on the endianness of the underlying UUID, rather than the target environment
    /// so bytes will be flipped on both big and little endian machines.
    ///
    /// # Examples
    ///
    /// ```
    /// # use shortguid::ShortGuid;
    ///
    /// # fn main() -> Result<(), shortguid::ParseError> {
    /// let uuid = ShortGuid::try_parse("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8")?;
    ///
    /// assert_eq!(
    ///     uuid.to_bytes_le(),
    ///     ([
    ///         0xa4, 0xa3, 0xa2, 0xa1, 0xb2, 0xb1, 0xc2, 0xc1, 0xd1, 0xd2,
    ///         0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8
    ///     ])
    /// );
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub const fn to_bytes_le(&self) -> [u8; 16] {
        self.0.to_bytes_le()
    }

    /// Decodes the given value to a [`Uuid`].
    ///
    /// ## Arguments
    /// * `value` - A 22 character ShortGuid URL-safe Base64 string.
    fn try_decode<S: AsRef<str>>(value: S) -> Result<Uuid, ParseError> {
        let value = value.as_ref();
        if value.is_empty() {
            return Ok(Uuid::default());
        }

        if value.len() != 22 {
            return Err(ParseError::InvalidLength(value.len()));
        }

        // This particular alphabet replaces '/' with '_' and '+' with '-'.
        let engine = &base64::engine::general_purpose::URL_SAFE_NO_PAD;
        let value = engine.decode(value)?;
        if value.len() != 16 {
            return Err(ParseError::InvalidLength(value.len()));
        }

        let bytes: [u8; 16] = value.try_into().expect("array has 16 elements");
        let uuid = Uuid::from_bytes(bytes);
        Ok(uuid)
    }

    /// Encodes the given [`Uuid`] value to an encoded [`ShortGuid`] string.
    /// The encoding is similar to base-64, with some non-URL safe characters replaced
    /// and padding removed.
    ///
    /// ## Returns
    /// A 22 character ShortGuid URL-safe Base64 string.
    fn encode<U: Borrow<Uuid>>(value: U) -> String {
        let bytes = value.borrow().as_bytes();

        // This particular alphabet replaces '/' with '_' and '+' with '-'.
        let engine = &base64::engine::general_purpose::URL_SAFE_NO_PAD;

        let mut buf = String::with_capacity(22);
        engine.encode_string(bytes, &mut buf);
        debug_assert_eq!(buf.len(), 22);
        buf
    }
}

impl Debug for ShortGuid {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{short} ({long})",
            short = Self::encode(&self.0),
            long = self.0
        )
    }
}

impl Display for ShortGuid {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{short}", short = Self::encode(&self.0))
    }
}

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

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

impl TryFrom<String> for ShortGuid {
    type Error = ParseError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        ShortGuid::try_parse(value)
    }
}

impl TryFrom<&str> for ShortGuid {
    type Error = ParseError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        ShortGuid::try_parse(value)
    }
}

impl PartialEq<Uuid> for ShortGuid {
    fn eq(&self, other: &Uuid) -> bool {
        self.0.eq(other)
    }
}

impl PartialEq<String> for ShortGuid {
    fn eq(&self, other: &String) -> bool {
        if let Ok(uuid) = ShortGuid::try_decode(other) {
            return self.0.eq(&uuid);
        }

        if let Ok(uuid) = Uuid::try_parse(other) {
            return self.0.eq(&uuid);
        }

        false
    }
}

impl PartialEq<str> for ShortGuid {
    fn eq(&self, other: &str) -> bool {
        if let Ok(uuid) = ShortGuid::try_decode(other) {
            return self.0.eq(&uuid);
        }

        if let Ok(uuid) = Uuid::try_parse(other) {
            return self.0.eq(&uuid);
        }

        false
    }
}

impl PartialEq<&str> for ShortGuid {
    fn eq(&self, other: &&str) -> bool {
        self.eq(*other)
    }
}

impl PartialEq<Vec<u8>> for ShortGuid {
    fn eq(&self, other: &Vec<u8>) -> bool {
        other.len() == 16 && self.as_bytes().eq(other.as_slice())
    }
}

impl PartialEq<&[u8]> for ShortGuid {
    fn eq(&self, other: &&[u8]) -> bool {
        other.len() == 16 && self.as_bytes().eq(other)
    }
}

impl PartialEq<&[u8; 16]> for ShortGuid {
    fn eq(&self, other: &&[u8; 16]) -> bool {
        self.as_bytes().eq(*other)
    }
}

impl PartialEq<[u8; 16]> for ShortGuid {
    fn eq(&self, other: &[u8; 16]) -> bool {
        self.as_bytes().eq(other)
    }
}

impl Borrow<Uuid> for ShortGuid {
    fn borrow(&self) -> &Uuid {
        self.as_uuid()
    }
}

impl AsRef<Uuid> for ShortGuid {
    fn as_ref(&self) -> &Uuid {
        self.as_uuid()
    }
}

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

/// A parsing error.
#[derive(Eq, PartialEq)]
pub enum ParseError {
    /// The provided input had an invalid length.
    /// The contained value is the actual size.
    InvalidLength(usize),
    /// The provided input had an invalid format.
    /// The contained value is the underlying decoding error.
    InvalidFormat(DecodeError),
}

impl From<DecodeError> for ParseError {
    fn from(value: DecodeError) -> Self {
        Self::InvalidFormat(value)
    }
}

impl Debug for ParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self)
    }
}

impl Display for ParseError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ParseError::InvalidLength(len) => write!(
                f,
                "Invalid ID length; expected 22 characters, but got {len}"
            ),
            ParseError::InvalidFormat(err) => write!(f, "Invalid ID format: {err}"),
        }
    }
}

impl Error for ParseError {}

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

    #[test]
    fn debug_works() {
        assert_eq!(
            format!("{:?}", ShortGuid::default()),
            "AAAAAAAAAAAAAAAAAAAAAA (00000000-0000-0000-0000-000000000000)".to_string()
        );
    }

    #[test]
    fn display_works() {
        assert_eq!(
            format!("{}", ShortGuid::default()),
            "AAAAAAAAAAAAAAAAAAAAAA".to_string()
        );
    }

    #[test]
    fn is_empty_works() {
        assert!(ShortGuid::default().is_empty());
    }

    #[test]
    fn new_random_works() {
        let a = ShortGuid::new_random();
        let b = ShortGuid::new_random();
        assert_ne!(a, b);
        assert_ne!(a, ShortGuid::default());
    }

    #[test]
    fn try_parse_works() {
        assert_eq!(
            ShortGuid::try_parse("AAAAAAAAAAAAAAAAAAAAAA").unwrap(),
            "00000000-0000-0000-0000-000000000000"
        );
        assert_eq!(
            ShortGuid::try_parse("00000000-0000-0000-0000-000000000000").unwrap(),
            ShortGuid::default()
        );

        assert_eq!(
            ShortGuid::try_parse("yaZG05xhTLe_ze4lIsj2Mw").unwrap(),
            "c9a646d3-9c61-4cb7-bfcd-ee2522c8f633"
        );
        assert_eq!(
            ShortGuid::try_parse("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap(),
            "c9a646d3-9c61-4cb7-bfcd-ee2522c8f633"
        );

        assert_eq!(
            ShortGuid::try_parse("ELina62d0RGAtADAT9QwyA").unwrap(),
            "10b8a76b-ad9d-d111-80b4-00c04fd430c8"
        );
        assert_eq!(
            ShortGuid::try_parse("10b8a76b-ad9d-d111-80b4-00c04fd430c8").unwrap(),
            "10b8a76b-ad9d-d111-80b4-00c04fd430c8"
        );

        assert_eq!(
            ShortGuid::try_parse("4ZOgWsqcM1iE3YmYWinsBA").unwrap(),
            Uuid::from_str("e193a05a-ca9c-3358-84dd-89985a29ec04").unwrap()
        );
        assert_eq!(
            ShortGuid::try_parse("e193a05a-ca9c-3358-84dd-89985a29ec04").unwrap(),
            Uuid::from_str("e193a05a-ca9c-3358-84dd-89985a29ec04").unwrap()
        );
    }

    #[test]
    fn try_decode_works() {
        assert_eq!(
            ShortGuid::try_decode("yaZG05xhTLe_ze4lIsj2Mw").unwrap(),
            Uuid::from_str("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap()
        );
        assert_eq!(
            ShortGuid::try_decode("ELina62d0RGAtADAT9QwyA").unwrap(),
            Uuid::from_str("10b8a76b-ad9d-d111-80b4-00c04fd430c8").unwrap()
        );
        assert_eq!(
            ShortGuid::try_decode("4ZOgWsqcM1iE3YmYWinsBA").unwrap(),
            Uuid::from_str("e193a05a-ca9c-3358-84dd-89985a29ec04").unwrap()
        );
        assert_eq!(
            ShortGuid::try_decode("AAAAAAAAAAAAAAAAAAAAAA").unwrap(),
            Uuid::from_str("00000000-0000-0000-0000-000000000000").unwrap()
        );
    }

    #[test]
    fn try_decode_with_invalid_input_of_correct_length_fails() {
        assert!(matches!(
            ShortGuid::try_decode("Nothing to see here...").unwrap_err(),
            ParseError::InvalidFormat(..)
        ));
    }

    #[test]
    fn try_decode_with_invalid_input_fails() {
        assert!(matches!(
            ShortGuid::try_decode("Nothing to see here").unwrap_err(),
            ParseError::InvalidLength(..)
        ));
    }

    #[test]
    fn encode_works() {
        assert_eq!(
            ShortGuid::encode(Uuid::from_str("c9a646d3-9c61-4cb7-bfcd-ee2522c8f633").unwrap()),
            "yaZG05xhTLe_ze4lIsj2Mw"
        );
        assert_eq!(
            ShortGuid::encode(Uuid::from_str("10b8a76b-ad9d-d111-80b4-00c04fd430c8").unwrap()),
            "ELina62d0RGAtADAT9QwyA"
        );
        assert_eq!(
            ShortGuid::encode(Uuid::from_str("e193a05a-ca9c-3358-84dd-89985a29ec04").unwrap()),
            "4ZOgWsqcM1iE3YmYWinsBA"
        );
        assert_eq!(
            ShortGuid::encode(Uuid::from_str("00000000-0000-0000-0000-000000000000").unwrap()),
            "AAAAAAAAAAAAAAAAAAAAAA"
        );
    }

    #[test]
    fn eq_array_works() {
        let id = ShortGuid::try_parse("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
        let array: [u8; 16] = [
            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
            0xd7, 0xd8,
        ];
        assert_eq!(id, array);
    }

    #[test]
    fn eq_slice_works() {
        let id = ShortGuid::try_parse("a1a2a3a4-b1b2-c1c2-d1d2-d3d4d5d6d7d8").unwrap();
        let slice: &[u8] = &[
            0xa1, 0xa2, 0xa3, 0xa4, 0xb1, 0xb2, 0xc1, 0xc2, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6,
            0xd7, 0xd8,
        ];
        assert_eq!(id, slice);
    }
}