ferroid 2.0.0

High-performance ULID and Snowflake-style IDs. Unique, monotonic, and lexicographically sortable IDs optimized for low-latency services and async workloads.
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
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
use core::{fmt, marker::PhantomData};

use super::interface::Base32Ext;
use crate::{
    base32::Error,
    generator::Result,
    id::{BeBytes, Id, SnowflakeId},
};

/// Extension trait for Crockford Base32 encoding and decoding of ID types.
///
/// This trait enables converting IDs backed by integer types into fixed-length,
/// lexicographically sortable Base32 representation using the [Crockford
/// Base32](https://www.crockford.com/base32.html) alphabet.
pub trait Base32SnowExt: SnowflakeId
where
    Self::Ty: BeBytes,
{
    /// Returns a stack-allocated, zero-initialized buffer of the backing
    /// primitive in the ID.
    ///
    /// This is a convenience method that returns a [`BeBytes::ByteArray`]
    #[must_use]
    fn byte_array() -> <<Self as Id>::Ty as BeBytes>::ByteArray {
        Self::inner_byte_array()
    }

    /// Returns a stack-allocated, zero-initialized buffer for Base32 encoding.
    ///
    /// This is a convenience method that returns a [`BeBytes::Base32Array`]
    /// suitable for use with [`Base32SnowExt::encode_to_buf`]. The returned
    /// buffer is stack-allocated, has a fixed size known at compile time, and
    /// is guaranteed to match the Crockford Base32 output size for the backing
    /// integer type.
    ///
    /// See also: [`Base32SnowExt::encode_to_buf`] for usage.
    #[must_use]
    fn base32_array() -> <<Self as Id>::Ty as BeBytes>::Base32Array {
        Self::inner_base32_array()
    }
    /// Returns a formatter containing the Crockford Base32 representation of
    /// the ID.
    ///
    /// The formatter is a lightweight, zero-allocation view over that internal
    /// buffer that implements [`core::fmt::Display`] and [`AsRef<str>`].
    ///
    /// # Example
    /// ```
    /// use std::fmt::Write;
    ///
    /// use ferroid::{base32::Base32SnowExt, id::SnowflakeTwitterId};
    ///
    /// let id = SnowflakeTwitterId::from_raw(2_424_242_424_242_424_242);
    ///
    /// // Formatter is a view over the internal encoded buffer
    /// let formatter = id.encode();
    ///
    /// assert_eq!(formatter, "23953MG16DJDJ");
    /// ```
    fn encode(&self) -> Base32SnowFormatter<Self> {
        Base32SnowFormatter::new(self)
    }
    /// Encodes this ID into the provided buffer without heap allocation and
    /// returns a formatter view over the buffer similar to
    /// [`Base32SnowExt::encode`].
    ///
    /// The buffer must be exactly [`BeBytes::BASE32_SIZE`] bytes long, which is
    /// guaranteed at compile time when using [`Base32SnowExt::base32_array`].
    /// # Example
    /// ```
    /// use ferroid::{
    ///     base32::Base32SnowExt,
    ///     id::{BeBytes, Id, SnowflakeTwitterId},
    /// };
    ///
    /// let id = SnowflakeTwitterId::from_raw(2_424_242_424_242_424_242);
    ///
    /// // Stack-allocated buffer of the correct size.
    /// let mut buf = SnowflakeTwitterId::base32_array();
    ///
    /// // Formatter is a view over the external buffer
    /// let formatter = id.encode_to_buf(&mut buf);
    ///
    /// assert_eq!(formatter, "23953MG16DJDJ");
    ///
    /// // Or access the raw bytes directly:
    /// let as_str = unsafe { core::str::from_utf8_unchecked(buf.as_ref()) };
    /// assert_eq!(as_str, "23953MG16DJDJ");
    /// ```
    ///
    /// See also: [`Base32SnowExt::encode`] for a version that manages its own
    /// buffer.
    fn encode_to_buf<'buf>(
        &self,
        buf: &'buf mut <<Self as Id>::Ty as BeBytes>::Base32Array,
    ) -> Base32SnowFormatterRef<'buf, Self> {
        Base32SnowFormatterRef::new(self, buf)
    }
    /// Decodes a Base32-encoded string back into an ID.
    ///
    /// # ⚠️ Note
    /// This method structurally decodes a Crockford base32 string into an
    /// integer representing a Snowflake ID, regardless of whether the input is
    /// a canonical Snowflake ID.
    ///
    /// - If the input string's Crockford encoding is larger than the
    ///   Snowflake's maximum (i.e. "FZZZZZZZZZZZZ" for 64-bit integers), the
    ///   excess bit is automatically ignored (i.e., the top 1 bit of the
    ///   decoded value is discarded), so no overflow or error occurs.
    /// - As a result, base32 strings that are technically invalid (i.e.,
    ///   lexicographically greater than the max Snowflake string) will still
    ///   successfully decode.
    /// - **However**, if your ID type reserves bits (e.g., reserved or unused
    ///   bits in your layout), decoding a string with excess bits may set these
    ///   reserved bits to 1, causing `.is_valid()` to fail, and decode to
    ///   return an error.
    ///
    /// # Errors
    ///
    /// Returns an error if the input string:
    /// - is not the expected fixed length of the backing integer representation
    ///   (i.e. 13 chars for u64, 26 chars for u128)
    /// - contains invalid UTF8 or invalid ASCII characters (i.e., not in the
    ///   Crockford Base32 alphabet)
    /// - sets reserved bits that make the decoded value invalid for this ID
    ///   type
    ///
    /// # Example
    /// ```
    /// use ferroid::{
    ///     base32::{Base32SnowExt, Error},
    ///     id::{Id, SnowflakeId, SnowflakeTwitterId},
    /// };
    ///
    /// // Crockford Base32 encodes values in 5-bit chunks, so encoding a u64
    /// // (64 bits)
    /// // requires 13 characters (13 × 5 = 65 bits). Since u64 can only hold 64
    /// // bits, the highest (leftmost) bit is discarded during decoding.
    /// //
    /// // This means *any* 13-character Base32 string will decode into a u64, even
    /// // if it represents a value that exceeds the canonical range of a specific
    /// // ID type.
    /// //
    /// // Many ID formats (such as Twitter Snowflake IDs) reserve one or more high
    /// // bits for future use. These reserved bits **must remain unset** for the
    /// // decoded value to be considered valid.
    /// //
    /// // For example, in a `SnowflakeTwitterId`, "7ZZZZZZZZZZZZ" represents the
    /// // largest lexicographically valid encoding that fills all non-reserved bits
    /// // with ones. Lexicographically larger values like "QZZZZZZZZZZZZ" decode to
    /// // the *same* ID because their first character differs only in the highest
    /// // (65th) bit, which is discarded:
    /// // - '7' = 0b00111 → top bit 0, reserved bit 0, rest = 111...
    /// // - 'Q' = 0b10111 → top bit 1, reserved bit 0, rest = 111...
    /// //            ↑↑↑↑ identical after discarding MSB
    /// let id1 = SnowflakeTwitterId::decode("7ZZZZZZZZZZZZ").unwrap();
    /// let id2 = SnowflakeTwitterId::decode("QZZZZZZZZZZZZ").unwrap();
    /// assert_eq!(id1, id2);
    ///
    /// // In contrast, "PZZZZZZZZZZZZ" differs in more significant bits and decodes
    /// // to a distinct value:
    /// // - 'P' = 0b10110 → top bit 1, reserved bit 0, rest = 110...
    /// //               ↑ alters bits within the ID layout beyond the reserved region
    /// let id3 = SnowflakeTwitterId::decode("PZZZZZZZZZZZZ").unwrap();
    /// assert_ne!(id1, id3);
    ///
    /// // If the reserved bits are set (e.g., 'F' = 0b01111 or 'Z' = 0b11111),
    /// // decoding fails and the invalid ID is returned:
    /// // - 'F' = 0b01111 → top bit 0, reserved bit 1, rest = 111...
    /// //            ↑ reserved bit is set - ID is invalid
    /// let id = SnowflakeTwitterId::decode("FZZZZZZZZZZZZ")
    ///     .or_else(|err| {
    ///         match err {
    ///             Error::DecodeOverflow { id } => {
    ///                 debug_assert!(!id.is_valid());
    ///                 // clears reserved bits
    ///                 let valid = id.into_valid();
    ///                 debug_assert!(valid.is_valid());
    ///                 Ok(valid)
    ///             }
    ///             other => Err(other),
    ///         }
    ///     })
    ///     .expect("should produce a valid ID");
    /// ```
    fn decode(input: impl AsRef<[u8]>) -> Result<Self, Error<Self>> {
        let decoded = Self::inner_decode(input)?;
        if !decoded.is_valid() {
            return Err(Error::DecodeOverflow { id: decoded });
        }
        Ok(decoded)
    }
}

impl<ID> Base32SnowExt for ID
where
    ID: SnowflakeId,
    ID::Ty: BeBytes,
{
}

/// A reusable builder that owns the Base32 buffer and formats an ID.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Base32SnowFormatter<T>
where
    T: Base32SnowExt,
    T::Ty: BeBytes,
{
    _id: PhantomData<T>,
    buf: <T::Ty as BeBytes>::Base32Array,
}

impl<T: Base32SnowExt> Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    pub fn new(id: &T) -> Self {
        let mut buf = T::base32_array();
        id.inner_encode_to_buf(&mut buf);
        Self {
            _id: PhantomData,
            buf,
        }
    }

    /// Returns the underlying bytes of the base32 encoding.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.buf.as_ref()
    }

    /// Returns a `&str` view of the base32 encoding.
    #[must_use]
    pub fn as_str(&self) -> &str {
        // SAFETY: `self.buf` holds only valid Crockford Base32 ASCII characters
        unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
    }

    /// Returns an allocated `String` of the base32 encoding.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn as_string(&self) -> alloc::string::String {
        // SAFETY: `self.buf` holds only valid Crockford Base32 ASCII characters
        unsafe { alloc::string::String::from_utf8_unchecked(self.as_bytes().to_vec()) }
    }

    /// Consumes the formatter and returns the raw buffer.
    pub const fn into_inner(self) -> <T::Ty as BeBytes>::Base32Array {
        self.buf
    }
}

impl<T: Base32SnowExt> core::hash::Hash for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

impl<T: Base32SnowExt> fmt::Display for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl<T: Base32SnowExt> fmt::Debug for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Base32SnowFormatter")
            .field(&self.as_str())
            .finish()
    }
}

#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> From<&Base32SnowFormatter<T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn from(formatter: &Base32SnowFormatter<T>) -> Self {
        formatter.as_string()
    }
}
#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> From<Base32SnowFormatter<T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn from(formatter: Base32SnowFormatter<T>) -> Self {
        formatter.as_string()
    }
}

impl<T: Base32SnowExt> AsRef<str> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> AsRef<[u8]> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<T: Base32SnowExt> core::ops::Deref for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> core::borrow::Borrow<str> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> PartialEq<str> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl<T: Base32SnowExt> PartialEq<&str> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}

impl<T: Base32SnowExt> PartialEq<Base32SnowFormatter<T>> for &str
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &Base32SnowFormatter<T>) -> bool {
        other == *self
    }
}

#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> PartialEq<alloc::string::String> for Base32SnowFormatter<T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &alloc::string::String) -> bool {
        self.as_str() == other.as_str()
    }
}
#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> PartialEq<Base32SnowFormatter<T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &Base32SnowFormatter<T>) -> bool {
        self.as_str() == other.as_str()
    }
}

/// A builder that borrows a user-supplied buffer for Base32 formatting.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Base32SnowFormatterRef<'a, T>
where
    T: Base32SnowExt,
    T::Ty: BeBytes,
{
    _id: PhantomData<T>,
    buf: &'a <T::Ty as BeBytes>::Base32Array,
}

impl<'a, T: Base32SnowExt> Base32SnowFormatterRef<'a, T>
where
    T::Ty: BeBytes,
{
    pub fn new(id: &T, buf: &'a mut <T::Ty as BeBytes>::Base32Array) -> Self {
        id.inner_encode_to_buf(buf);
        Self {
            _id: PhantomData,
            buf,
        }
    }

    /// Returns the underlying bytes of the base32 encoding.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8] {
        self.buf.as_ref()
    }

    /// Returns a `&str` view of the base32 encoding.
    #[must_use]
    pub fn as_str(&self) -> &str {
        // SAFETY: `self.buf` holds only valid Crockford Base32 ASCII characters
        unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
    }

    /// Returns an allocated `String` of the base32 encoding.
    #[cfg(feature = "alloc")]
    #[must_use]
    pub fn as_string(&self) -> alloc::string::String {
        // SAFETY: `self.buf` holds only valid Crockford Base32 ASCII characters
        unsafe { alloc::string::String::from_utf8_unchecked(self.as_bytes().to_vec()) }
    }
}

impl<T: Base32SnowExt> core::hash::Hash for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

impl<T: Base32SnowExt> fmt::Display for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl<T: Base32SnowExt> fmt::Debug for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("Base32SnowFormatterRef")
            .field(&self.as_str())
            .finish()
    }
}

#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> From<&Base32SnowFormatterRef<'_, T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn from(formatter: &Base32SnowFormatterRef<'_, T>) -> Self {
        formatter.as_string()
    }
}
#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> From<Base32SnowFormatterRef<'_, T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn from(formatter: Base32SnowFormatterRef<'_, T>) -> Self {
        formatter.as_string()
    }
}

impl<T: Base32SnowExt> AsRef<str> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> AsRef<[u8]> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<T: Base32SnowExt> core::ops::Deref for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    type Target = str;

    fn deref(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> core::borrow::Borrow<str> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<T: Base32SnowExt> PartialEq<str> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}
impl<T: Base32SnowExt> PartialEq<&str> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}
impl<T: Base32SnowExt> PartialEq<Base32SnowFormatterRef<'_, T>> for &str
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &Base32SnowFormatterRef<'_, T>) -> bool {
        other == *self
    }
}

#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> PartialEq<alloc::string::String> for Base32SnowFormatterRef<'_, T>
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &alloc::string::String) -> bool {
        self.as_str() == other.as_str()
    }
}
#[cfg(feature = "alloc")]
impl<T: Base32SnowExt> PartialEq<Base32SnowFormatterRef<'_, T>> for alloc::string::String
where
    T::Ty: BeBytes,
{
    fn eq(&self, other: &Base32SnowFormatterRef<'_, T>) -> bool {
        self.as_str() == other.as_str()
    }
}

#[cfg(all(test, feature = "alloc", feature = "snowflake"))]
mod alloc_test {
    use alloc::string::ToString;

    use crate::{
        base32::Base32SnowExt,
        id::{SnowflakeDiscordId, SnowflakeInstagramId, SnowflakeMastodonId, SnowflakeTwitterId},
    };

    #[test]
    fn twitter_display() {
        let id = SnowflakeTwitterId::decode("01ARZ3NDEKTSV").unwrap();
        assert_eq!(alloc::format!("{id}"), "01ARZ3NDEKTSV");
        assert_eq!(id.to_string(), "01ARZ3NDEKTSV");
    }
    #[test]
    fn instagram_display() {
        let id = SnowflakeInstagramId::decode("01ARZ3NDEKTSV").unwrap();
        assert_eq!(alloc::format!("{id}"), "01ARZ3NDEKTSV");
        assert_eq!(id.to_string(), "01ARZ3NDEKTSV");
    }
    #[test]
    fn mastodon_display() {
        let id = SnowflakeMastodonId::decode("01ARZ3NDEKTSV").unwrap();
        assert_eq!(alloc::format!("{id}"), "01ARZ3NDEKTSV");
        assert_eq!(id.to_string(), "01ARZ3NDEKTSV");
    }
    #[test]
    fn discord_display() {
        let id = SnowflakeDiscordId::decode("01ARZ3NDEKTSV").unwrap();
        assert_eq!(alloc::format!("{id}"), "01ARZ3NDEKTSV");
        assert_eq!(id.to_string(), "01ARZ3NDEKTSV");
    }
}

#[cfg(all(test, feature = "snowflake"))]
mod test {
    use crate::{
        base32::{Base32SnowExt, Error},
        id::{SnowflakeDiscordId, SnowflakeInstagramId, SnowflakeMastodonId, SnowflakeTwitterId},
    };

    #[test]
    fn snow_try_from() {
        // Don't need to test all IDs
        let id = SnowflakeTwitterId::try_from("01ARZ3NDEKTSV").unwrap();
        let encoded = id.encode();
        assert_eq!(encoded, "01ARZ3NDEKTSV");
    }

    #[test]
    fn snow_from_str() {
        // Don't need to test all IDs
        use core::str::FromStr;
        let id = SnowflakeTwitterId::from_str("01ARZ3NDEKTSV").unwrap();
        let encoded = id.encode();
        assert_eq!(encoded, "01ARZ3NDEKTSV");
    }

    #[test]
    fn twitter_max() {
        let id = SnowflakeTwitterId::from_components(
            SnowflakeTwitterId::max_timestamp(),
            SnowflakeTwitterId::max_machine_id(),
            SnowflakeTwitterId::max_sequence(),
        );
        assert_eq!(id.timestamp(), SnowflakeTwitterId::max_timestamp());
        assert_eq!(id.machine_id(), SnowflakeTwitterId::max_machine_id());
        assert_eq!(id.sequence(), SnowflakeTwitterId::max_sequence());

        let encoded = id.encode();
        assert_eq!(encoded, "7ZZZZZZZZZZZZ");
        let decoded = SnowflakeTwitterId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), SnowflakeTwitterId::max_timestamp());
        assert_eq!(decoded.machine_id(), SnowflakeTwitterId::max_machine_id());
        assert_eq!(decoded.sequence(), SnowflakeTwitterId::max_sequence());
        assert_eq!(id, decoded);
    }

    #[test]
    fn twitter_zero() {
        let id = SnowflakeTwitterId::from_components(0, 0, 0);
        assert_eq!(id.timestamp(), 0);
        assert_eq!(id.machine_id(), 0);
        assert_eq!(id.sequence(), 0);

        let encoded = id.encode();
        assert_eq!(encoded, "0000000000000");
        let decoded = SnowflakeTwitterId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), 0);
        assert_eq!(decoded.machine_id(), 0);
        assert_eq!(decoded.sequence(), 0);
        assert_eq!(id, decoded);
    }

    #[test]
    fn discord_max() {
        let id = SnowflakeDiscordId::from_components(
            SnowflakeDiscordId::max_timestamp(),
            SnowflakeDiscordId::max_machine_id(),
            SnowflakeDiscordId::max_sequence(),
        );
        assert_eq!(id.timestamp(), SnowflakeDiscordId::max_timestamp());
        assert_eq!(id.machine_id(), SnowflakeDiscordId::max_machine_id());
        assert_eq!(id.sequence(), SnowflakeDiscordId::max_sequence());

        let encoded = id.encode();
        assert_eq!(encoded, "FZZZZZZZZZZZZ");
        let decoded = SnowflakeDiscordId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), SnowflakeDiscordId::max_timestamp());
        assert_eq!(decoded.machine_id(), SnowflakeDiscordId::max_machine_id());
        assert_eq!(decoded.sequence(), SnowflakeDiscordId::max_sequence());
        assert_eq!(id, decoded);
    }

    #[test]
    fn discord_zero() {
        let id = SnowflakeDiscordId::from_components(0, 0, 0);
        assert_eq!(id.timestamp(), 0);
        assert_eq!(id.machine_id(), 0);
        assert_eq!(id.sequence(), 0);

        let encoded = id.encode();
        assert_eq!(encoded, "0000000000000");
        let decoded = SnowflakeDiscordId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), 0);
        assert_eq!(decoded.machine_id(), 0);
        assert_eq!(decoded.sequence(), 0);
        assert_eq!(id, decoded);
    }

    #[test]
    fn instagram_max() {
        let id = SnowflakeInstagramId::from_components(
            SnowflakeInstagramId::max_timestamp(),
            SnowflakeInstagramId::max_machine_id(),
            SnowflakeInstagramId::max_sequence(),
        );
        assert_eq!(id.timestamp(), SnowflakeInstagramId::max_timestamp());
        assert_eq!(id.machine_id(), SnowflakeInstagramId::max_machine_id());
        assert_eq!(id.sequence(), SnowflakeInstagramId::max_sequence());

        let encoded = id.encode();
        assert_eq!(encoded, "FZZZZZZZZZZZZ");
        let decoded = SnowflakeInstagramId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), SnowflakeInstagramId::max_timestamp());
        assert_eq!(decoded.machine_id(), SnowflakeInstagramId::max_machine_id());
        assert_eq!(decoded.sequence(), SnowflakeInstagramId::max_sequence());
        assert_eq!(id, decoded);
    }

    #[test]
    fn instagram_zero() {
        let id = SnowflakeInstagramId::from_components(0, 0, 0);
        assert_eq!(id.timestamp(), 0);
        assert_eq!(id.machine_id(), 0);
        assert_eq!(id.sequence(), 0);

        let encoded = id.encode();
        assert_eq!(encoded, "0000000000000");
        let decoded = SnowflakeInstagramId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), 0);
        assert_eq!(decoded.machine_id(), 0);
        assert_eq!(decoded.sequence(), 0);
        assert_eq!(id, decoded);
    }

    #[test]
    fn mastodon_max() {
        let id = SnowflakeMastodonId::from_components(
            SnowflakeMastodonId::max_timestamp(),
            SnowflakeMastodonId::max_machine_id(),
            SnowflakeMastodonId::max_sequence(),
        );
        assert_eq!(id.timestamp(), SnowflakeMastodonId::max_timestamp());
        assert_eq!(id.machine_id(), SnowflakeMastodonId::max_machine_id());
        assert_eq!(id.sequence(), SnowflakeMastodonId::max_sequence());

        let encoded = id.encode();
        assert_eq!(encoded, "FZZZZZZZZZZZZ");
        let decoded = SnowflakeMastodonId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), SnowflakeMastodonId::max_timestamp());
        assert_eq!(decoded.machine_id(), SnowflakeMastodonId::max_machine_id());
        assert_eq!(decoded.sequence(), SnowflakeMastodonId::max_sequence());
        assert_eq!(id, decoded);
    }

    #[test]
    fn mastodon_zero() {
        let id = SnowflakeMastodonId::from_components(0, 0, 0);
        assert_eq!(id.timestamp(), 0);
        assert_eq!(id.machine_id(), 0);
        assert_eq!(id.sequence(), 0);

        let encoded = id.encode();
        assert_eq!(encoded, "0000000000000");
        let decoded = SnowflakeMastodonId::decode(encoded).unwrap();

        assert_eq!(decoded.timestamp(), 0);
        assert_eq!(decoded.machine_id(), 0);
        assert_eq!(decoded.sequence(), 0);
        assert_eq!(id, decoded);
    }

    #[test]
    fn decode_invalid_character_fails() {
        // Base32 Crockford disallows symbols like `@`
        let invalid = "000000@000000";
        let res = SnowflakeTwitterId::decode(invalid);
        assert_eq!(
            res.unwrap_err(),
            Error::DecodeInvalidAscii {
                byte: b'@',
                index: 6,
            }
        );
    }

    #[test]
    fn decode_invalid_length_fails() {
        // Shorter than 13-byte base32 for u64
        let too_short = "012345678901";
        let res = SnowflakeTwitterId::decode(too_short);
        assert_eq!(res.unwrap_err(), Error::DecodeInvalidLen { len: 12 });

        // Longer than 13-byte base32 for u64
        let too_long = "01234567890123";
        let res = SnowflakeTwitterId::decode(too_long);

        assert_eq!(res.unwrap_err(), Error::DecodeInvalidLen { len: 14 });
    }
}