nexus-id 1.0.0

High-performance ID generators for low-latency systems
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
//! Newtype wrappers for ID values.
//!
//! These types provide type safety and encapsulation for generated IDs.
//! Each type wraps an internal representation and provides methods for
//! conversion, parsing, and access to the underlying data.

use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::ops::Deref;
use core::str::FromStr;

use nexus_ascii::AsciiString;

use crate::parse::{self, DecodeError, ParseError, UuidParseError};

// ============================================================================
// UUID Types
// ============================================================================

/// UUID in standard dashed format.
///
/// Format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` (36 characters)
///
/// This type wraps the string representation of a UUID. It implements
/// `Copy`, `Hash`, `Eq`, and `Deref<Target = str>` for ergonomic usage.
///
/// # Example
///
/// ```rust
/// use nexus_id::uuid::UuidV4;
///
/// let mut generator = UuidV4::new(12345);
/// let id = generator.next();
///
/// // Use as &str via Deref
/// println!("{}", &*id);
///
/// // Or explicitly
/// println!("{}", id.as_str());
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Uuid(pub(crate) AsciiString<40>);

impl Uuid {
    /// Create a Uuid from raw (hi, lo) 64-bit components.
    ///
    /// The `hi` value contains the upper 64 bits and `lo` the lower 64 bits
    /// of the 128-bit UUID. This is the inverse of [`decode()`](Self::decode).
    ///
    /// Any (hi, lo) pair produces a valid UUID string. No validation is needed.
    #[inline]
    pub fn from_raw(hi: u64, lo: u64) -> Self {
        Self(crate::encode::uuid_dashed(hi, lo))
    }

    /// Construct from a 16-byte big-endian binary representation.
    ///
    /// This is the inverse of [`to_bytes()`](Self::to_bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidLength`] if `bytes.len() != 16`.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        if bytes.len() != 16 {
            return Err(ParseError::InvalidLength {
                expected: 16,
                got: bytes.len(),
            });
        }
        let hi = u64::from_be_bytes(bytes[0..8].try_into().unwrap());
        let lo = u64::from_be_bytes(bytes[8..16].try_into().unwrap());
        Ok(Self::from_raw(hi, lo))
    }

    /// Construct from a byte slice without length validation.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `bytes.len() >= 16`. Reads the first
    /// 16 bytes as a big-endian UUID.
    #[inline]
    pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
        debug_assert!(bytes.len() >= 16);
        // SAFETY: caller guarantees bytes.len() >= 16
        unsafe {
            let hi = u64::from_be_bytes(bytes.get_unchecked(0..8).try_into().unwrap_unchecked());
            let lo = u64::from_be_bytes(bytes.get_unchecked(8..16).try_into().unwrap_unchecked());
            Self::from_raw(hi, lo)
        }
    }

    /// Returns the UUID as a string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    /// Returns the UUID as a byte slice.
    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Decode the UUID back to raw (hi, lo) bytes.
    ///
    /// This parses the hex digits and reconstructs the 128-bit value.
    pub fn decode(&self) -> (u64, u64) {
        let bytes = self.0.as_bytes();
        // Parse hex chars, skipping dashes at positions 8, 13, 18, 23
        let mut hi: u64 = 0;
        let mut lo: u64 = 0;

        // Bytes 0-7 (chars 0-7) -> hi bits 32-63
        for &b in &bytes[0..8] {
            hi = (hi << 4) | hex_digit(b) as u64;
        }
        // Bytes 9-12 (chars 9-12, skip dash at 8) -> hi bits 16-31
        for &b in &bytes[9..13] {
            hi = (hi << 4) | hex_digit(b) as u64;
        }
        // Bytes 14-17 (chars 14-17, skip dash at 13) -> hi bits 0-15
        for &b in &bytes[14..18] {
            hi = (hi << 4) | hex_digit(b) as u64;
        }
        // Bytes 19-22 (chars 19-22, skip dash at 18) -> lo bits 48-63
        for &b in &bytes[19..23] {
            lo = (lo << 4) | hex_digit(b) as u64;
        }
        // Bytes 24-35 (chars 24-35, skip dash at 23) -> lo bits 0-47
        for &b in &bytes[24..36] {
            lo = (lo << 4) | hex_digit(b) as u64;
        }

        (hi, lo)
    }

    /// Extract the UUID version (4 bits).
    #[inline]
    pub fn version(&self) -> u8 {
        // Version is char at position 14
        hex_digit(self.0.as_bytes()[14])
    }

    /// Parse a UUID from a dashed string.
    ///
    /// Accepts format: `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` (36 chars).
    /// Case-insensitive for hex digits.
    ///
    /// # Errors
    ///
    /// Returns [`UuidParseError`] if the input has wrong length, invalid hex
    /// characters, or missing/misplaced dashes.
    pub fn parse(s: &str) -> Result<Self, UuidParseError> {
        let bytes = s.as_bytes();
        if bytes.len() != 36 {
            return Err(UuidParseError::InvalidLength {
                expected: 36,
                got: bytes.len(),
            });
        }

        // Validate dashes at positions 8, 13, 18, 23
        if bytes[8] != b'-' || bytes[13] != b'-' || bytes[18] != b'-' || bytes[23] != b'-' {
            return Err(UuidParseError::InvalidFormat);
        }

        // SAFETY: We verified bytes.len() == 36.
        let input: &[u8; 36] = unsafe { &*(bytes.as_ptr().cast::<[u8; 36]>()) };

        // Decode via SIMD path: compacts dashes out, decodes 32 hex chars in parallel.
        let (hi, lo) = crate::simd::uuid_parse_dashed(input).map_err(|pos| {
            // Map compacted 32-byte position back to 36-byte input position.
            let input_pos = match pos {
                0..=7 => pos,       // segment 1: no offset
                8..=11 => pos + 1,  // segment 2: skip dash at 8
                12..=15 => pos + 2, // segment 3: skip dashes at 8, 13
                16..=19 => pos + 3, // segment 4: skip dashes at 8, 13, 18
                _ => pos + 4,       // segment 5: skip all 4 dashes
            };
            UuidParseError::InvalidChar {
                position: input_pos,
                byte: bytes[input_pos],
            }
        })?;

        Ok(Self::from_raw(hi, lo))
    }

    /// Convert to compact format (no dashes).
    #[inline]
    pub fn to_compact(&self) -> UuidCompact {
        let (hi, lo) = self.decode();
        UuidCompact::from_raw(hi, lo)
    }

    /// Check if this is the nil UUID (all zeros).
    #[inline]
    pub fn is_nil(&self) -> bool {
        let (hi, lo) = self.decode();
        hi == 0 && lo == 0
    }

    /// Extract the timestamp for UUID v7 (milliseconds since Unix epoch).
    ///
    /// Returns `None` if this is not a v7 UUID.
    #[inline]
    pub fn timestamp_ms(&self) -> Option<u64> {
        if self.version() != 7 {
            return None;
        }
        let (hi, _) = self.decode();
        Some(hi >> 16)
    }

    /// Get the raw 128-bit value as big-endian bytes.
    pub fn to_bytes(&self) -> [u8; 16] {
        let (hi, lo) = self.decode();
        let mut out = [0u8; 16];
        out[..8].copy_from_slice(&hi.to_be_bytes());
        out[8..].copy_from_slice(&lo.to_be_bytes());
        out
    }
}

impl Deref for Uuid {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for Uuid {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for Uuid {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl Ord for Uuid {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        // Lexicographic order = time order for v7 UUIDs
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for Uuid {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl FromStr for Uuid {
    type Err = UuidParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// UUID Compact (no dashes)
// ============================================================================

/// UUID in compact format (no dashes).
///
/// Format: `xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx` (32 characters)
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct UuidCompact(pub(crate) AsciiString<32>);

impl UuidCompact {
    /// Create a UuidCompact from raw (hi, lo) 64-bit components.
    ///
    /// The `hi` value contains the upper 64 bits and `lo` the lower 64 bits
    /// of the 128-bit UUID. This is the inverse of [`decode()`](Self::decode).
    #[inline]
    pub fn from_raw(hi: u64, lo: u64) -> Self {
        Self(crate::encode::hex_u128(hi, lo))
    }

    /// Construct from a 16-byte big-endian binary representation.
    ///
    /// This is the inverse of [`to_bytes()`](Self::to_bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidLength`] if `bytes.len() != 16`.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        if bytes.len() != 16 {
            return Err(ParseError::InvalidLength {
                expected: 16,
                got: bytes.len(),
            });
        }
        let hi = u64::from_be_bytes(bytes[0..8].try_into().unwrap());
        let lo = u64::from_be_bytes(bytes[8..16].try_into().unwrap());
        Ok(Self::from_raw(hi, lo))
    }

    /// Construct from a byte slice without length validation.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `bytes.len() >= 16`.
    #[inline]
    pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
        debug_assert!(bytes.len() >= 16);
        // SAFETY: caller guarantees bytes.len() >= 16
        unsafe {
            let hi = u64::from_be_bytes(bytes.get_unchecked(0..8).try_into().unwrap_unchecked());
            let lo = u64::from_be_bytes(bytes.get_unchecked(8..16).try_into().unwrap_unchecked());
            Self::from_raw(hi, lo)
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Decode back to raw (hi, lo) bytes.
    pub fn decode(&self) -> (u64, u64) {
        let bytes: &[u8; 32] = self.0.as_bytes().try_into().unwrap();
        // SAFETY: Data was validated at construction; decode cannot fail.
        unsafe { crate::simd::hex_decode_32(bytes).unwrap_unchecked() }
    }

    /// Parse a compact UUID from a hex string (no dashes).
    ///
    /// Accepts format: 32 hex characters. Case-insensitive.
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        let bytes = s.as_bytes();
        if bytes.len() != 32 {
            return Err(ParseError::InvalidLength {
                expected: 32,
                got: bytes.len(),
            });
        }

        // SIMD path: validates and decodes in a single pass
        let hex_bytes: &[u8; 32] = bytes.try_into().unwrap();
        let (hi, lo) =
            crate::simd::hex_decode_32(hex_bytes).map_err(|pos| ParseError::InvalidChar {
                position: pos,
                byte: bytes[pos],
            })?;

        Ok(Self::from_raw(hi, lo))
    }

    /// Convert to dashed format.
    #[inline]
    pub fn to_dashed(&self) -> Uuid {
        let (hi, lo) = self.decode();
        Uuid::from_raw(hi, lo)
    }

    /// Check if this is the nil UUID.
    #[inline]
    pub fn is_nil(&self) -> bool {
        let (hi, lo) = self.decode();
        hi == 0 && lo == 0
    }

    /// Get the raw 128-bit value as big-endian bytes.
    pub fn to_bytes(&self) -> [u8; 16] {
        let (hi, lo) = self.decode();
        let mut out = [0u8; 16];
        out[..8].copy_from_slice(&hi.to_be_bytes());
        out[8..].copy_from_slice(&lo.to_be_bytes());
        out
    }
}

impl Deref for UuidCompact {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for UuidCompact {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for UuidCompact {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl Ord for UuidCompact {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for UuidCompact {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl FromStr for UuidCompact {
    type Err = ParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// HexId64 - Hex-encoded u64
// ============================================================================

/// Hex-encoded 64-bit ID.
///
/// Format: 16 lowercase hex characters.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct HexId64(pub(crate) AsciiString<16>);

impl HexId64 {
    /// Encode a u64 as hex.
    #[inline]
    pub fn encode(value: u64) -> Self {
        Self(crate::encode::hex_u64(value))
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Decode back to u64.
    pub fn decode(&self) -> u64 {
        let bytes: &[u8; 16] = self.0.as_bytes().try_into().unwrap();
        // SAFETY: Data was validated at construction; decode cannot fail.
        unsafe { crate::simd::hex_decode_16(bytes).unwrap_unchecked() }
    }

    /// Parse a hex ID from a 16-character hex string. Case-insensitive.
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        let bytes = s.as_bytes();
        if bytes.len() != 16 {
            return Err(ParseError::InvalidLength {
                expected: 16,
                got: bytes.len(),
            });
        }

        // SIMD path: validates and decodes in a single pass
        let hex_bytes: &[u8; 16] = bytes.try_into().unwrap();
        let value =
            crate::simd::hex_decode_16(hex_bytes).map_err(|pos| ParseError::InvalidChar {
                position: pos,
                byte: bytes[pos],
            })?;

        Ok(Self::encode(value))
    }
}

impl Deref for HexId64 {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for HexId64 {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for HexId64 {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl FromStr for HexId64 {
    type Err = ParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// Base62Id - Base62-encoded u64
// ============================================================================

/// Base62-encoded 64-bit ID.
///
/// Format: 11 alphanumeric characters (0-9, A-Z, a-z).
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Base62Id(pub(crate) AsciiString<16>);

impl Base62Id {
    /// Encode a u64 as base62.
    #[inline]
    pub fn encode(value: u64) -> Self {
        Self(crate::encode::base62_u64(value))
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Decode back to u64.
    pub fn decode(&self) -> u64 {
        let bytes = self.0.as_bytes();
        let mut value: u64 = 0;
        for &b in bytes {
            value = value * 62 + base62_digit(b) as u64;
        }
        value
    }

    /// Parse a base62 ID from an 11-character string.
    pub fn parse(s: &str) -> Result<Self, DecodeError> {
        let bytes = s.as_bytes();
        if bytes.len() != 11 {
            return Err(DecodeError::InvalidLength {
                expected: 11,
                got: bytes.len(),
            });
        }

        let mut value: u64 = 0;
        let mut i = 0;
        while i < 11 {
            let d = parse::validate_base62(bytes[i], i)?;
            value = value
                .checked_mul(62)
                .and_then(|v| v.checked_add(d as u64))
                .ok_or(DecodeError::Overflow)?;
            i += 1;
        }

        Ok(Self::encode(value))
    }
}

impl Deref for Base62Id {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for Base62Id {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for Base62Id {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl FromStr for Base62Id {
    type Err = DecodeError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// Base36Id - Base36-encoded u64
// ============================================================================

/// Base36-encoded 64-bit ID.
///
/// Format: 13 alphanumeric characters (0-9, a-z), case-insensitive.
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Base36Id(pub(crate) AsciiString<16>);

impl Base36Id {
    /// Encode a u64 as base36.
    #[inline]
    pub fn encode(value: u64) -> Self {
        Self(crate::encode::base36_u64(value))
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Decode back to u64.
    pub fn decode(&self) -> u64 {
        let bytes = self.0.as_bytes();
        let mut value: u64 = 0;
        for &b in bytes {
            value = value * 36 + base36_digit(b) as u64;
        }
        value
    }

    /// Parse a base36 ID from a 13-character string. Case-insensitive.
    pub fn parse(s: &str) -> Result<Self, DecodeError> {
        let bytes = s.as_bytes();
        if bytes.len() != 13 {
            return Err(DecodeError::InvalidLength {
                expected: 13,
                got: bytes.len(),
            });
        }

        let mut value: u64 = 0;
        let mut i = 0;
        while i < 13 {
            let d = parse::validate_base36(bytes[i], i)?;
            value = value
                .checked_mul(36)
                .and_then(|v| v.checked_add(d as u64))
                .ok_or(DecodeError::Overflow)?;
            i += 1;
        }

        Ok(Self::encode(value))
    }
}

impl Deref for Base36Id {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for Base36Id {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for Base36Id {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl FromStr for Base36Id {
    type Err = DecodeError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// ULID
// ============================================================================

/// ULID (Universally Unique Lexicographically Sortable Identifier).
///
/// Format: 26 Crockford Base32 characters (128 bits total)
/// - First 10 chars: 48-bit timestamp (milliseconds since Unix epoch)
/// - Last 16 chars: 80 bits of randomness
///
/// ULIDs are lexicographically sortable and monotonically increasing.
///
/// # Example
///
/// ```rust
/// use std::time::{Instant, SystemTime, UNIX_EPOCH};
/// use nexus_id::ulid::UlidGenerator;
///
/// let epoch = Instant::now();
/// let unix_base = SystemTime::now()
///     .duration_since(UNIX_EPOCH)
///     .unwrap()
///     .as_millis() as u64;
///
/// let mut generator = UlidGenerator::new(epoch, unix_base, 12345);
/// let id = generator.next(Instant::now());
/// assert_eq!(id.len(), 26);
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
pub struct Ulid(pub(crate) AsciiString<32>);

impl Ulid {
    /// Create a ULID from raw components.
    ///
    /// - `timestamp_ms`: 48-bit millisecond timestamp (upper bits ignored)
    /// - `rand_hi`: upper 16 bits of the 80-bit random field
    /// - `rand_lo`: lower 64 bits of the 80-bit random field
    #[inline]
    pub fn from_raw(timestamp_ms: u64, rand_hi: u16, rand_lo: u64) -> Self {
        Self(crate::encode::ulid_encode(timestamp_ms, rand_hi, rand_lo))
    }

    /// Construct from a 16-byte big-endian binary representation.
    ///
    /// Layout: `[timestamp: 6 bytes][rand_hi: 2 bytes][rand_lo: 8 bytes]`
    ///
    /// This is the inverse of [`to_bytes()`](Self::to_bytes).
    ///
    /// # Errors
    ///
    /// Returns [`ParseError::InvalidLength`] if `bytes.len() != 16`.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        if bytes.len() != 16 {
            return Err(ParseError::InvalidLength {
                expected: 16,
                got: bytes.len(),
            });
        }
        // Timestamp: bytes 0-5 (48 bits, big-endian)
        let mut ts_buf = [0u8; 8];
        ts_buf[2..8].copy_from_slice(&bytes[0..6]);
        let timestamp_ms = u64::from_be_bytes(ts_buf);

        let rand_hi = u16::from_be_bytes(bytes[6..8].try_into().unwrap());
        let rand_lo = u64::from_be_bytes(bytes[8..16].try_into().unwrap());

        Ok(Self::from_raw(timestamp_ms, rand_hi, rand_lo))
    }

    /// Construct from a byte slice without length validation.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that `bytes.len() >= 16`.
    #[inline]
    pub unsafe fn from_bytes_unchecked(bytes: &[u8]) -> Self {
        debug_assert!(bytes.len() >= 16);
        // SAFETY: caller guarantees bytes.len() >= 16
        unsafe {
            let mut ts_buf = [0u8; 8];
            core::ptr::copy_nonoverlapping(bytes.as_ptr(), ts_buf.as_mut_ptr().add(2), 6);
            let timestamp_ms = u64::from_be_bytes(ts_buf);

            let rand_hi =
                u16::from_be_bytes(bytes.get_unchecked(6..8).try_into().unwrap_unchecked());
            let rand_lo =
                u64::from_be_bytes(bytes.get_unchecked(8..16).try_into().unwrap_unchecked());

            Self::from_raw(timestamp_ms, rand_hi, rand_lo)
        }
    }

    #[inline]
    pub fn as_str(&self) -> &str {
        self.0.as_str()
    }

    #[inline]
    pub fn as_bytes(&self) -> &[u8] {
        self.0.as_bytes()
    }

    /// Extract the timestamp (milliseconds since Unix epoch).
    pub fn timestamp_ms(&self) -> u64 {
        let bytes = self.0.as_bytes();
        let mut ts: u64 = 0;

        // Decode first 10 characters (48 bits of timestamp)
        // Char 0: 3 bits, Chars 1-9: 5 bits each = 3 + 45 = 48 bits
        ts = (ts << 3) | crockford32_digit(bytes[0]) as u64;
        for &b in &bytes[1..10] {
            ts = (ts << 5) | crockford32_digit(b) as u64;
        }

        ts
    }

    /// Parse a ULID from a 26-character Crockford Base32 string.
    ///
    /// Case-insensitive. Accepts Crockford aliases (I/L → 1, O → 0).
    pub fn parse(s: &str) -> Result<Self, ParseError> {
        let bytes = s.as_bytes();
        if bytes.len() != 26 {
            return Err(ParseError::InvalidLength {
                expected: 26,
                got: bytes.len(),
            });
        }

        // Single-pass: validate and decode simultaneously via lookup table.
        // Decode timestamp (chars 0-9): 3 + 9×5 = 48 bits
        // First char encodes only 3 bits — values > 7 overflow the 48-bit timestamp.
        let first = parse::validate_crockford32(bytes[0], 0)?;
        if first > 7 {
            return Err(ParseError::InvalidChar {
                position: 0,
                byte: bytes[0],
            });
        }
        let mut ts: u64 = first as u64;
        let mut i = 1;
        while i < 10 {
            let d = parse::validate_crockford32(bytes[i], i)? as u64;
            ts = (ts << 5) | d;
            i += 1;
        }

        // Decode random (chars 10-25): 80 bits
        let c10 = parse::validate_crockford32(bytes[10], 10)? as u16;
        let c11 = parse::validate_crockford32(bytes[11], 11)? as u16;
        let c12 = parse::validate_crockford32(bytes[12], 12)? as u16;
        let c13 = parse::validate_crockford32(bytes[13], 13)? as u64;

        let rand_hi = (c10 << 11) | (c11 << 6) | (c12 << 1) | ((c13 >> 4) as u16);

        let mut rand_lo: u64 = c13 & 0x0F;
        i = 14;
        while i < 26 {
            let d = parse::validate_crockford32(bytes[i], i)? as u64;
            rand_lo = (rand_lo << 5) | d;
            i += 1;
        }

        Ok(Self::from_raw(ts, rand_hi, rand_lo))
    }

    /// Check if this is a nil ULID (all zeros).
    #[inline]
    pub fn is_nil(&self) -> bool {
        self.timestamp_ms() == 0 && {
            let (hi, lo) = self.random();
            hi == 0 && lo == 0
        }
    }

    /// Convert to a UUID v7-compatible format.
    ///
    /// Maps the ULID's 128-bit value into UUID v7 layout, setting version (7) and
    /// variant (RFC) bits.
    ///
    /// # Data Loss
    ///
    /// This conversion is **lossy**. ULID has 80 random bits, but UUID v7 reserves
    /// 6 bits for version+variant, leaving only 74 bits for randomness. The bottom
    /// 6 bits of `rand_lo` are discarded. The conversion is not reversible.
    pub fn to_uuid(&self) -> Uuid {
        let ts = self.timestamp_ms();
        let (rand_hi, rand_lo) = self.random();

        // Pack into UUID v7 layout
        // hi: [timestamp: 48][version=7: 4][rand_a: 12]
        let rand_a = (rand_hi >> 4) as u64; // top 12 bits of rand_hi
        let hi = (ts << 16) | (0x7 << 12) | (rand_a & 0xFFF);

        // lo: [variant=10: 2][rand_b: 62]
        // Use remaining bits from rand_hi (4 bits) + rand_lo (64 bits) → take 62 bits
        let remaining = ((rand_hi as u64 & 0x0F) << 58) | (rand_lo >> 6);
        let lo = (0b10u64 << 62) | (remaining & 0x3FFF_FFFF_FFFF_FFFF);

        Uuid::from_raw(hi, lo)
    }

    /// Get the raw 128-bit value as big-endian bytes.
    pub fn to_bytes(&self) -> [u8; 16] {
        let ts = self.timestamp_ms();
        let (rand_hi, rand_lo) = self.random();

        let mut out = [0u8; 16];
        // Timestamp in bytes 0-5 (48 bits, big-endian)
        let ts_bytes = ts.to_be_bytes();
        out[0..6].copy_from_slice(&ts_bytes[2..8]);
        // Random hi in bytes 6-7 (16 bits)
        out[6..8].copy_from_slice(&rand_hi.to_be_bytes());
        // Random lo in bytes 8-15 (64 bits)
        out[8..16].copy_from_slice(&rand_lo.to_be_bytes());
        out
    }

    /// Decode the random portion as (hi: u16, lo: u64).
    pub fn random(&self) -> (u16, u64) {
        let bytes = self.0.as_bytes();

        // Chars 10-13 contain rand_hi (16 bits) spread across boundaries
        // Char 10: bits 11-15 of rand_hi (5 bits)
        // Char 11: bits 6-10 of rand_hi (5 bits)
        // Char 12: bits 1-5 of rand_hi (5 bits)
        // Char 13: bit 0 of rand_hi (1 bit) + bits 60-63 of rand_lo (4 bits)

        let c10 = crockford32_digit(bytes[10]) as u16;
        let c11 = crockford32_digit(bytes[11]) as u16;
        let c12 = crockford32_digit(bytes[12]) as u16;
        let c13 = crockford32_digit(bytes[13]) as u64;

        let rand_hi = (c10 << 11) | (c11 << 6) | (c12 << 1) | ((c13 >> 4) as u16);

        // Chars 13-25 contain rand_lo (64 bits)
        // Char 13 contributes 4 bits (already extracted above for rand_hi)
        let mut rand_lo: u64 = c13 & 0x0F;
        for &b in &bytes[14..26] {
            rand_lo = (rand_lo << 5) | crockford32_digit(b) as u64;
        }

        (rand_hi, rand_lo)
    }
}

impl Deref for Ulid {
    type Target = str;

    #[inline]
    fn deref(&self) -> &str {
        self.0.as_str()
    }
}

impl AsRef<str> for Ulid {
    #[inline]
    fn as_ref(&self) -> &str {
        self.0.as_str()
    }
}

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

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

impl Hash for Ulid {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.hash(state);
    }
}

impl Ord for Ulid {
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        // Lexicographic order = time order (timestamp in MSB chars)
        self.0.cmp(&other.0)
    }
}

impl PartialOrd for Ulid {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl FromStr for Ulid {
    type Err = ParseError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}

// ============================================================================
// Cross-type From impls
// ============================================================================

impl From<Uuid> for UuidCompact {
    /// Lossless conversion: strip dashes.
    #[inline]
    fn from(u: Uuid) -> Self {
        u.to_compact()
    }
}

impl From<UuidCompact> for Uuid {
    /// Lossless conversion: add dashes.
    #[inline]
    fn from(u: UuidCompact) -> Self {
        u.to_dashed()
    }
}

impl From<Ulid> for Uuid {
    /// Convert ULID to UUID v7 format (sets version and variant bits).
    ///
    /// **Lossy**: 6 bits of randomness are discarded. See [`Ulid::to_uuid()`].
    #[inline]
    fn from(u: Ulid) -> Self {
        u.to_uuid()
    }
}

// ============================================================================
// Helper functions
// ============================================================================

/// Convert Crockford Base32 character to value (0-31) via lookup table.
/// For already-validated data (from our own encode output).
#[inline]
fn crockford32_digit(b: u8) -> u8 {
    parse::CROCKFORD32_DECODE[b as usize]
}

/// Convert hex character to value (0-15).
#[inline]
const fn hex_digit(b: u8) -> u8 {
    match b {
        b'0'..=b'9' => b - b'0',
        b'a'..=b'f' => b - b'a' + 10,
        b'A'..=b'F' => b - b'A' + 10,
        _ => 0, // Should never happen for valid IDs
    }
}

/// Convert base62 character to value (0-61).
#[inline]
const fn base62_digit(b: u8) -> u8 {
    match b {
        b'0'..=b'9' => b - b'0',
        b'A'..=b'Z' => b - b'A' + 10,
        b'a'..=b'z' => b - b'a' + 36,
        _ => 0,
    }
}

/// Convert base36 character to value (0-35).
#[inline]
const fn base36_digit(b: u8) -> u8 {
    match b {
        b'0'..=b'9' => b - b'0',
        b'a'..=b'z' => b - b'a' + 10,
        b'A'..=b'Z' => b - b'A' + 10, // Case insensitive
        _ => 0,
    }
}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;

    #[test]
    fn uuid_decode_roundtrip() {
        let hi = 0x0123_4567_89AB_CDEF_u64;
        let lo = 0xFEDC_BA98_7654_3210_u64;

        let uuid = Uuid::from_raw(hi, lo);
        let (decoded_hi, decoded_lo) = uuid.decode();

        assert_eq!(hi, decoded_hi);
        assert_eq!(lo, decoded_lo);
    }

    #[test]
    fn uuid_compact_decode_roundtrip() {
        let hi = 0x0123_4567_89AB_CDEF_u64;
        let lo = 0xFEDC_BA98_7654_3210_u64;

        let uuid = UuidCompact::from_raw(hi, lo);
        let (decoded_hi, decoded_lo) = uuid.decode();

        assert_eq!(hi, decoded_hi);
        assert_eq!(lo, decoded_lo);
    }

    #[test]
    fn hex_id64_decode_roundtrip() {
        for value in [0, 1, 12345, u64::MAX, 0xDEAD_BEEF_CAFE_BABE] {
            let id = HexId64::encode(value);
            assert_eq!(id.decode(), value);
        }
    }

    #[test]
    fn base62_id_decode_roundtrip() {
        for value in [0, 1, 12345, u64::MAX] {
            let id = Base62Id::encode(value);
            assert_eq!(id.decode(), value);
        }
    }

    #[test]
    fn base36_id_decode_roundtrip() {
        for value in [0, 1, 12345, u64::MAX] {
            let id = Base36Id::encode(value);
            assert_eq!(id.decode(), value);
        }
    }

    #[test]
    fn uuid_version() {
        // V4 UUID
        let hi = 0x0123_4567_89AB_4DEF_u64; // version 4 at position
        let lo = 0x8EDC_BA98_7654_3210_u64;
        let uuid = Uuid::from_raw(hi, lo);
        assert_eq!(uuid.version(), 4);

        // V7 UUID
        let hi = 0x0123_4567_89AB_7DEF_u64; // version 7 at position
        let uuid = Uuid::from_raw(hi, lo);
        assert_eq!(uuid.version(), 7);
    }

    #[test]
    fn display_works() {
        let uuid = Uuid::from_raw(0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210);
        let s = format!("{}", uuid);
        assert_eq!(s, "01234567-89ab-cdef-fedc-ba9876543210");
    }

    #[test]
    fn deref_works() {
        let uuid = Uuid::from_raw(0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210);
        let s: &str = &uuid;
        assert_eq!(s, "01234567-89ab-cdef-fedc-ba9876543210");
    }

    #[test]
    fn uuid_from_bytes_roundtrip() {
        let original = Uuid::from_raw(0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210);
        let bytes = original.to_bytes();
        let recovered = Uuid::from_bytes(&bytes).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn uuid_from_bytes_wrong_length() {
        assert!(Uuid::from_bytes(&[0u8; 15]).is_err());
        assert!(Uuid::from_bytes(&[0u8; 17]).is_err());
        assert!(Uuid::from_bytes(&[]).is_err());
    }

    #[test]
    fn uuid_from_bytes_unchecked_roundtrip() {
        let original = Uuid::from_raw(0xDEAD_BEEF_CAFE_BABE, 0x0123_4567_89AB_CDEF);
        let bytes = original.to_bytes();
        let recovered = unsafe { Uuid::from_bytes_unchecked(&bytes) };
        assert_eq!(original, recovered);
    }

    #[test]
    fn uuid_compact_from_bytes_roundtrip() {
        let original = UuidCompact::from_raw(0x0123_4567_89AB_CDEF, 0xFEDC_BA98_7654_3210);
        let bytes = original.to_bytes();
        let recovered = UuidCompact::from_bytes(&bytes).unwrap();
        assert_eq!(original, recovered);
    }

    #[test]
    fn uuid_compact_from_bytes_wrong_length() {
        assert!(UuidCompact::from_bytes(&[0u8; 15]).is_err());
        assert!(UuidCompact::from_bytes(&[0u8; 17]).is_err());
    }

    #[test]
    fn ulid_from_bytes_roundtrip() {
        let original = Ulid::from_raw(1_700_000_000_000, 0xABCD, 0xDEAD_BEEF_CAFE_BABE);
        let bytes = original.to_bytes();
        let recovered = Ulid::from_bytes(&bytes).unwrap();
        assert_eq!(original.timestamp_ms(), recovered.timestamp_ms());
        assert_eq!(original.random(), recovered.random());
        assert_eq!(original, recovered);
    }

    #[test]
    fn ulid_from_bytes_wrong_length() {
        assert!(Ulid::from_bytes(&[0u8; 15]).is_err());
        assert!(Ulid::from_bytes(&[0u8; 17]).is_err());
    }

    #[test]
    fn ulid_from_bytes_unchecked_roundtrip() {
        let original = Ulid::from_raw(1_700_000_000_000, 0x1234, 0x0123_4567_89AB_CDEF);
        let bytes = original.to_bytes();
        let recovered = unsafe { Ulid::from_bytes_unchecked(&bytes) };
        assert_eq!(original, recovered);
    }

    #[test]
    fn ulid_parse_rejects_overflow_first_char() {
        // First char value > 7 overflows the 48-bit timestamp.
        // '8' decodes to value 8 in Crockford Base32.
        let overflow = "80000000000000000000000000";
        assert!(Ulid::parse(overflow).is_err());

        // 'Z' decodes to value 31 — also invalid.
        let z_first = "Z0000000000000000000000000";
        assert!(Ulid::parse(z_first).is_err());

        // '7' (value 7) is the max valid first char.
        let max_valid = "70000000000000000000000000";
        assert!(Ulid::parse(max_valid).is_ok());
    }

    // ====================================================================
    // Overflow detection
    // ====================================================================

    #[test]
    fn base62_parse_overflow() {
        use crate::parse::DecodeError;

        // "zzzzzzzzzzz" (11 z's) = 61*(62^10 + 62^9 + ... + 1) > u64::MAX
        let result = Base62Id::parse("zzzzzzzzzzz");
        assert_eq!(result, Err(DecodeError::Overflow));

        // u64::MAX encodes to "LygHa16AHYF" — should round-trip
        let max_id = Base62Id::encode(u64::MAX);
        let parsed = Base62Id::parse(max_id.as_str()).unwrap();
        assert_eq!(parsed.decode(), u64::MAX);
    }

    #[test]
    fn base36_parse_overflow() {
        use crate::parse::DecodeError;

        // "zzzzzzzzzzzzz" (13 z's) = 35*(36^12 + ...) > u64::MAX
        let result = Base36Id::parse("zzzzzzzzzzzzz");
        assert_eq!(result, Err(DecodeError::Overflow));

        // u64::MAX should round-trip
        let max_id = Base36Id::encode(u64::MAX);
        let parsed = Base36Id::parse(max_id.as_str()).unwrap();
        assert_eq!(parsed.decode(), u64::MAX);
    }

    // ====================================================================
    // Uuid::parse negative cases
    // ====================================================================

    #[test]
    fn uuid_parse_wrong_length() {
        use crate::parse::UuidParseError;

        let result = Uuid::parse("01234567-89ab-cdef-fedc-ba987654321"); // 35 chars
        assert!(matches!(result, Err(UuidParseError::InvalidLength { .. })));

        let result = Uuid::parse("01234567-89ab-cdef-fedc-ba98765432100"); // 37 chars
        assert!(matches!(result, Err(UuidParseError::InvalidLength { .. })));

        let result = Uuid::parse("");
        assert!(matches!(result, Err(UuidParseError::InvalidLength { .. })));
    }

    #[test]
    fn uuid_parse_bad_dashes() {
        use crate::parse::UuidParseError;

        // Missing dash at position 8
        let result = Uuid::parse("01234567089ab-cdef-fedc-ba9876543210");
        assert!(matches!(result, Err(UuidParseError::InvalidFormat)));

        // Missing dash at position 13
        let result = Uuid::parse("01234567-89ab0cdef-fedc-ba9876543210");
        assert!(matches!(result, Err(UuidParseError::InvalidFormat)));

        // Missing dash at position 18
        let result = Uuid::parse("01234567-89ab-cdef0fedc-ba9876543210");
        assert!(matches!(result, Err(UuidParseError::InvalidFormat)));

        // Missing dash at position 23
        let result = Uuid::parse("01234567-89ab-cdef-fedc0ba9876543210");
        assert!(matches!(result, Err(UuidParseError::InvalidFormat)));
    }

    #[test]
    fn uuid_parse_invalid_hex_char() {
        use crate::parse::UuidParseError;

        // 'g' is not a valid hex character
        let result = Uuid::parse("g1234567-89ab-cdef-fedc-ba9876543210");
        assert!(matches!(
            result,
            Err(UuidParseError::InvalidChar { position: 0, .. })
        ));

        // Invalid in the middle segment
        let result = Uuid::parse("01234567-89xb-cdef-fedc-ba9876543210");
        assert!(matches!(
            result,
            Err(UuidParseError::InvalidChar { position: 11, .. })
        ));
    }

    // ====================================================================
    // is_nil() tests
    // ====================================================================

    #[test]
    fn uuid_is_nil() {
        let nil = Uuid::from_raw(0, 0);
        assert!(nil.is_nil());

        let not_nil = Uuid::from_raw(0, 1);
        assert!(!not_nil.is_nil());

        let not_nil = Uuid::from_raw(1, 0);
        assert!(!not_nil.is_nil());
    }

    #[test]
    fn uuid_compact_is_nil() {
        let nil = UuidCompact::from_raw(0, 0);
        assert!(nil.is_nil());

        let not_nil = UuidCompact::from_raw(0, 1);
        assert!(!not_nil.is_nil());
    }

    #[test]
    fn ulid_is_nil() {
        let nil = Ulid::from_raw(0, 0, 0);
        assert!(nil.is_nil());

        // Non-zero timestamp
        let not_nil = Ulid::from_raw(1, 0, 0);
        assert!(!not_nil.is_nil());

        // Non-zero rand_hi
        let not_nil = Ulid::from_raw(0, 1, 0);
        assert!(!not_nil.is_nil());

        // Non-zero rand_lo
        let not_nil = Ulid::from_raw(0, 0, 1);
        assert!(!not_nil.is_nil());
    }

    // ====================================================================
    // Crockford Base32 alias handling
    // ====================================================================

    #[test]
    fn ulid_parse_crockford_aliases() {
        // Crockford spec: I/i/L/l → 1, O/o → 0
        // "01" prefix with aliases should parse the same as canonical "01"
        let canonical = Ulid::parse("01000000000000000000000000").unwrap();

        // 'O' → 0 (alias for zero)
        let with_o = Ulid::parse("O1000000000000000000000000").unwrap();
        assert_eq!(canonical, with_o);

        // 'I' → 1
        let with_i = Ulid::parse("0I000000000000000000000000").unwrap();
        assert_eq!(canonical, with_i);

        // 'L' → 1
        let with_l = Ulid::parse("0L000000000000000000000000").unwrap();
        assert_eq!(canonical, with_l);

        // 'i' → 1 (lowercase)
        let with_i_lower = Ulid::parse("0i000000000000000000000000").unwrap();
        assert_eq!(canonical, with_i_lower);

        // 'o' → 0 (lowercase)
        let with_o_lower = Ulid::parse("o1000000000000000000000000").unwrap();
        assert_eq!(canonical, with_o_lower);

        // 'l' → 1 (lowercase)
        let with_l_lower = Ulid::parse("0l000000000000000000000000").unwrap();
        assert_eq!(canonical, with_l_lower);
    }

    // ====================================================================
    // Ulid::to_uuid() lossy conversion
    // ====================================================================

    #[test]
    fn ulid_to_uuid_preserves_timestamp() {
        let ts = 1_700_000_000_000u64;
        let ulid = Ulid::from_raw(ts, 0x1234, 0xDEAD_BEEF_CAFE_BABE);
        let uuid = ulid.to_uuid();

        // Version should be 7
        assert_eq!(uuid.version(), 7);

        // Timestamp should survive the conversion (top 48 bits of hi)
        let (hi, _) = uuid.decode();
        let extracted_ts = hi >> 16;
        assert_eq!(extracted_ts, ts);
    }

    #[test]
    fn ulid_to_uuid_is_lossy() {
        // Two ULIDs that differ only in the bottom 6 bits of rand_lo
        // should map to the same UUID (those bits are discarded).
        let ulid_a = Ulid::from_raw(1_700_000_000_000, 0x1234, 0xDEAD_BEEF_CAFE_BA00);
        let ulid_b = Ulid::from_raw(1_700_000_000_000, 0x1234, 0xDEAD_BEEF_CAFE_BA3F);

        // Different ULIDs
        assert_ne!(ulid_a, ulid_b);

        // Same UUID (bottom 6 bits lost)
        assert_eq!(ulid_a.to_uuid(), ulid_b.to_uuid());
    }

    #[test]
    fn ulid_to_uuid_sets_variant_bits() {
        let ulid = Ulid::from_raw(1_700_000_000_000, 0xFFFF, u64::MAX);
        let uuid = ulid.to_uuid();
        let (_, lo) = uuid.decode();

        // Top 2 bits of lo must be 0b10 (RFC variant)
        assert_eq!(lo >> 62, 0b10);
    }
}