reliakit-primitives 0.4.3

Reusable type-safe primitives for constrained and reliability-oriented Rust values.
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
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
use crate::{PrimitiveError, PrimitiveResult};
use alloc::string::String;
use core::{fmt, ops::Deref, str::FromStr};

// ── Slug ─────────────────────────────────────────────────────────────────────

/// URL-safe slug: lowercase ASCII alphanumeric characters and hyphens.
///
/// Rules: non-empty, only `[a-z0-9-]`, does not start or end with `-`,
/// no consecutive `--`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Slug(String);

impl Slug {
    /// Creates a new `Slug`. Returns `Invalid` if the value violates slug rules.
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        if !is_valid_slug(&value) {
            return Err(PrimitiveError::Invalid {
                message: "slug must be lowercase alphanumeric with hyphens, must not start or end with a hyphen, and must not contain consecutive hyphens",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying slug string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

fn is_valid_slug(s: &str) -> bool {
    if s.starts_with('-') || s.ends_with('-') {
        return false;
    }
    let mut prev = ' ';
    for c in s.chars() {
        if !matches!(c, 'a'..='z' | '0'..='9' | '-') {
            return false;
        }
        if c == '-' && prev == '-' {
            return false;
        }
        prev = c;
    }
    true
}

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

impl AsRef<str> for Slug {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Slug {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Slug {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Slug {
    type Error = PrimitiveError;

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

impl FromStr for Slug {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Slug {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Slug {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Slug> for String {
    fn from(value: Slug) -> Self {
        value.into_inner()
    }
}

// ── Email ─────────────────────────────────────────────────────────────────────

/// Email address with basic structural validation.
///
/// Checks: exactly one `@`, non-empty local part and domain, domain contains
/// at least one `.`, domain labels are non-empty, no whitespace. Not a full
/// RFC 5321 validator.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Email(String);

impl Email {
    /// Creates a new `Email`. Returns `Invalid` if the value fails structural checks.
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        if !is_valid_email(&value) {
            return Err(PrimitiveError::Invalid {
                message: "invalid email address",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying email string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns the local part (before `@`).
    pub fn local(&self) -> &str {
        self.0.split('@').next().unwrap_or("")
    }

    /// Returns the domain part (after `@`).
    pub fn domain(&self) -> &str {
        self.0.split('@').nth(1).unwrap_or("")
    }
}

fn is_valid_email(s: &str) -> bool {
    if s.chars().any(|c| c.is_whitespace()) {
        return false;
    }
    let at_count = s.chars().filter(|&c| c == '@').count();
    if at_count != 1 {
        return false;
    }
    let mut parts = s.splitn(2, '@');
    let local = parts.next().unwrap_or("");
    let domain = parts.next().unwrap_or("");
    if local.is_empty() || domain.is_empty() {
        return false;
    }
    if !domain.contains('.') || domain.split('.').any(str::is_empty) {
        return false;
    }
    true
}

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

impl AsRef<str> for Email {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Email {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Email {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Email {
    type Error = PrimitiveError;

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

impl FromStr for Email {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Email {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Email {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Email> for String {
    fn from(value: Email) -> Self {
        value.into_inner()
    }
}

// ── HttpUrl ───────────────────────────────────────────────────────────────────

/// HTTP or HTTPS URL with scheme validation.
///
/// Must start with `http://` or `https://` and have a non-empty host.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HttpUrl(String);

impl HttpUrl {
    /// Creates a new `HttpUrl`. Returns `Invalid` if the scheme is missing or
    /// the host is empty.
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        let after_scheme = strip_http_scheme(&value).ok_or(PrimitiveError::Invalid {
            message: "URL must start with http:// or https://",
        })?;
        let host = after_scheme.split(['/', '?', '#']).next().unwrap_or("");
        if host.is_empty() || host.chars().all(|c| c.is_whitespace()) {
            return Err(PrimitiveError::Invalid {
                message: "URL must have a non-empty host",
            });
        }
        if after_scheme.chars().any(|c| c.is_whitespace()) {
            return Err(PrimitiveError::Invalid {
                message: "URL must not contain whitespace",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying URL string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` if the URL uses `https`.
    pub fn is_https(&self) -> bool {
        self.0.len() >= 8 && self.0[..8].eq_ignore_ascii_case("https://")
    }
}

fn strip_http_scheme(value: &str) -> Option<&str> {
    if value
        .as_bytes()
        .get(..8)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"https://"))
    {
        Some(&value[8..])
    } else if value
        .as_bytes()
        .get(..7)
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case(b"http://"))
    {
        Some(&value[7..])
    } else {
        None
    }
}

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

impl AsRef<str> for HttpUrl {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for HttpUrl {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for HttpUrl {
    type Error = PrimitiveError;

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

impl TryFrom<String> for HttpUrl {
    type Error = PrimitiveError;

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

impl FromStr for HttpUrl {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for HttpUrl {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for HttpUrl {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<HttpUrl> for String {
    fn from(value: HttpUrl) -> Self {
        value.into_inner()
    }
}

// ── HexString ─────────────────────────────────────────────────────────────────

/// String of valid hexadecimal characters, with optional `0x`/`0X` prefix.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HexString(String);

impl HexString {
    /// Creates a new `HexString`. Returns `Invalid` if any character is not a
    /// valid hex digit (after stripping an optional `0x`/`0X` prefix).
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        let hex_part = value
            .strip_prefix("0x")
            .or_else(|| value.strip_prefix("0X"))
            .unwrap_or(&value);
        if hex_part.is_empty() {
            return Err(PrimitiveError::Invalid {
                message: "hex string must not be empty after prefix",
            });
        }
        if !hex_part.chars().all(|c| c.is_ascii_hexdigit()) {
            return Err(PrimitiveError::Invalid {
                message: "hex string must contain only hexadecimal characters (0-9, a-f, A-F)",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying hex string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` if the value was stored with a `0x`/`0X` prefix.
    pub fn has_prefix(&self) -> bool {
        self.0.starts_with("0x") || self.0.starts_with("0X")
    }

    /// Returns only the hex digit characters, without any `0x`/`0X` prefix.
    pub fn hex_digits(&self) -> &str {
        self.0
            .strip_prefix("0x")
            .or_else(|| self.0.strip_prefix("0X"))
            .unwrap_or(&self.0)
    }
}

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

impl AsRef<str> for HexString {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for HexString {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for HexString {
    type Error = PrimitiveError;

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

impl TryFrom<String> for HexString {
    type Error = PrimitiveError;

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

impl FromStr for HexString {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for HexString {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for HexString {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<HexString> for String {
    fn from(value: HexString) -> Self {
        value.into_inner()
    }
}

// ── Base64 ────────────────────────────────────────────────────────────────────

/// Standard (RFC 4648) base64 string with required, correct padding.
///
/// Rules: non-empty, length is a multiple of `4`, every non-padding character is
/// in the standard alphabet (`A-Z`, `a-z`, `0-9`, `+`, `/`), and `=` padding (at
/// most two) appears only at the end. This is a *format* check; it does not
/// decode the data. The URL-safe alphabet (`-`/`_`) is not accepted.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Base64(String);

impl Base64 {
    /// Creates a new `Base64`. Returns an error if the value is empty or is not
    /// well-formed standard base64 (see the type docs for the exact rules).
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        let bytes = value.as_bytes();
        if bytes.len() % 4 != 0 {
            return Err(PrimitiveError::Invalid {
                message: "base64 length must be a multiple of 4",
            });
        }
        let pad = bytes.iter().rev().take_while(|&&b| b == b'=').count();
        if pad > 2 {
            return Err(PrimitiveError::Invalid {
                message: "base64 has at most two padding characters",
            });
        }
        // Every character before the padding must be in the standard alphabet;
        // because `=` is not in the alphabet, this also rejects interior padding.
        if !bytes[..bytes.len() - pad]
            .iter()
            .all(|&b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
        {
            return Err(PrimitiveError::Invalid {
                message: "base64 contains a character outside the standard alphabet",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying base64 string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` if the value carries `=` padding.
    pub fn is_padded(&self) -> bool {
        self.0.ends_with('=')
    }

    /// Returns the number of bytes this base64 string decodes to.
    pub fn decoded_len(&self) -> usize {
        let pad = self.0.bytes().rev().take_while(|&b| b == b'=').count();
        self.0.len() / 4 * 3 - pad
    }
}

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

impl AsRef<str> for Base64 {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Base64 {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Base64 {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Base64 {
    type Error = PrimitiveError;

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

impl FromStr for Base64 {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Base64 {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Base64 {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Base64> for String {
    fn from(value: Base64) -> Self {
        value.into_inner()
    }
}

// ── Base32 ────────────────────────────────────────────────────────────────────

/// Standard (RFC 4648) base32 string with required, correct padding.
///
/// Rules: non-empty, length is a multiple of `8`, every non-padding character is
/// in the standard alphabet (`A-Z`, `2-7`), and `=` padding appears only at the
/// end in a valid amount (`1`, `3`, `4`, or `6` characters). This is a *format*
/// check; it does not decode the data. Lowercase letters and the extended-hex
/// alphabet are not accepted.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Base32(String);

impl Base32 {
    /// Creates a new `Base32`. Returns an error if the value is empty or is not
    /// well-formed standard base32 (see the type docs for the exact rules).
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        let bytes = value.as_bytes();
        if bytes.len() % 8 != 0 {
            return Err(PrimitiveError::Invalid {
                message: "base32 length must be a multiple of 8",
            });
        }
        let pad = bytes.iter().rev().take_while(|&&b| b == b'=').count();
        // Valid trailing-pad counts for base32 are 0, 1, 3, 4, or 6.
        if !matches!(pad, 0 | 1 | 3 | 4 | 6) {
            return Err(PrimitiveError::Invalid {
                message: "base32 has an invalid amount of padding",
            });
        }
        // Every character before the padding must be in the standard alphabet;
        // because `=` is not in the alphabet, this also rejects interior padding.
        if !bytes[..bytes.len() - pad]
            .iter()
            .all(|&b| b.is_ascii_uppercase() || (b'2'..=b'7').contains(&b))
        {
            return Err(PrimitiveError::Invalid {
                message: "base32 contains a character outside the standard alphabet",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying base32 string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Returns `true` if the value carries `=` padding.
    pub fn is_padded(&self) -> bool {
        self.0.ends_with('=')
    }

    /// Returns the number of bytes this base32 string decodes to.
    pub fn decoded_len(&self) -> usize {
        let pad = self.0.bytes().rev().take_while(|&b| b == b'=').count();
        let missing = match pad {
            6 => 4,
            4 => 3,
            3 => 2,
            1 => 1,
            _ => 0,
        };
        self.0.len() / 8 * 5 - missing
    }
}

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

impl AsRef<str> for Base32 {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Base32 {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Base32 {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Base32 {
    type Error = PrimitiveError;

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

impl FromStr for Base32 {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Base32 {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Base32 {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Base32> for String {
    fn from(value: Base32) -> Self {
        value.into_inner()
    }
}

// ── Identifier ────────────────────────────────────────────────────────────────

/// A conservative ASCII identifier: a letter or `_`, then letters, digits, or
/// `_`.
///
/// Rules: non-empty, the first character is `[A-Za-z_]`, and every remaining
/// character is `[A-Za-z0-9_]`. Useful for handles, keys, and machine-generated
/// names that must be safe across many systems.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Identifier(String);

impl Identifier {
    /// Creates a new `Identifier`. Returns an error if the value is empty or
    /// contains a character not allowed at its position (see the type docs).
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        let mut chars = value.chars();
        match chars.next() {
            None => return Err(PrimitiveError::Empty),
            Some(first) if !(first.is_ascii_alphabetic() || first == '_') => {
                return Err(PrimitiveError::Invalid {
                    message: "identifier must start with an ASCII letter or underscore",
                });
            }
            Some(_) => {}
        }
        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return Err(PrimitiveError::Invalid {
                message: "identifier may contain only ASCII letters, digits, and underscores",
            });
        }
        Ok(Self(value))
    }

    /// Returns the underlying identifier string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

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

impl AsRef<str> for Identifier {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Identifier {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Identifier {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Identifier {
    type Error = PrimitiveError;

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

impl FromStr for Identifier {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Identifier {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Identifier {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Identifier> for String {
    fn from(value: Identifier) -> Self {
        value.into_inner()
    }
}

// ── Hostname ──────────────────────────────────────────────────────────────────

/// A DNS hostname following the RFC 1123 rules.
///
/// Rules: non-empty, at most 253 characters total, split into dot-separated
/// labels where each label is 1–63 characters of `[A-Za-z0-9-]` and does not
/// start or end with a hyphen. Empty labels (a leading, trailing, or doubled
/// dot) are rejected. The check is case-preserving and does not resolve the name.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Hostname(String);

impl Hostname {
    /// Creates a new `Hostname`. Returns an error if the value is empty, too
    /// long, or has a label that violates the RFC 1123 rules (see the type docs).
    pub fn new(value: impl Into<String>) -> PrimitiveResult<Self> {
        let value = value.into();
        if value.is_empty() {
            return Err(PrimitiveError::Empty);
        }
        if value.len() > 253 {
            return Err(PrimitiveError::TooLong {
                max: 253,
                actual: value.len(),
            });
        }
        for label in value.split('.') {
            if label.is_empty() {
                return Err(PrimitiveError::Invalid {
                    message: "hostname label must not be empty",
                });
            }
            if label.len() > 63 {
                return Err(PrimitiveError::Invalid {
                    message: "hostname label must not exceed 63 characters",
                });
            }
            if label.starts_with('-') || label.ends_with('-') {
                return Err(PrimitiveError::Invalid {
                    message: "hostname label must not start or end with a hyphen",
                });
            }
            if !label
                .bytes()
                .all(|b| b.is_ascii_alphanumeric() || b == b'-')
            {
                return Err(PrimitiveError::Invalid {
                    message: "hostname label may contain only letters, digits, and hyphens",
                });
            }
        }
        Ok(Self(value))
    }

    /// Returns the underlying hostname string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the wrapper and returns the inner string.
    pub fn into_inner(self) -> String {
        self.0
    }

    /// Iterates over the dot-separated labels, from left to right.
    pub fn labels(&self) -> impl Iterator<Item = &str> + '_ {
        self.0.split('.')
    }
}

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

impl AsRef<str> for Hostname {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Hostname {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl TryFrom<&str> for Hostname {
    type Error = PrimitiveError;

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

impl TryFrom<String> for Hostname {
    type Error = PrimitiveError;

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

impl FromStr for Hostname {
    type Err = PrimitiveError;

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

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

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

impl PartialEq<String> for Hostname {
    fn eq(&self, other: &String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl PartialEq<&String> for Hostname {
    fn eq(&self, other: &&String) -> bool {
        self.as_str() == other.as_str()
    }
}

impl From<Hostname> for String {
    fn from(value: Hostname) -> Self {
        value.into_inner()
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::{Base32, Base64, Email, HexString, Hostname, HttpUrl, Identifier, Slug};
    use crate::{PrimitiveError, PrimitiveErrorKind};

    // Slug
    #[test]
    fn slug_accepts_valid() {
        assert_eq!(Slug::new("my-service").unwrap().as_str(), "my-service");
        assert_eq!(Slug::new("api-v2").unwrap().as_str(), "api-v2");
        assert_eq!(Slug::new("user123").unwrap().as_str(), "user123");
    }

    #[test]
    fn slug_rejects_empty() {
        assert_eq!(Slug::new("").unwrap_err(), PrimitiveError::Empty);
    }

    #[test]
    fn slug_rejects_uppercase() {
        assert!(Slug::new("MySlug").is_err());
    }

    #[test]
    fn slug_rejects_leading_hyphen() {
        assert!(Slug::new("-bad").is_err());
    }

    #[test]
    fn slug_rejects_trailing_hyphen() {
        assert!(Slug::new("bad-").is_err());
    }

    #[test]
    fn slug_rejects_consecutive_hyphens() {
        assert!(Slug::new("bad--slug").is_err());
    }

    #[test]
    fn slug_rejects_spaces() {
        assert!(Slug::new("has space").is_err());
    }

    #[test]
    fn slug_display() {
        use alloc::string::ToString;
        assert_eq!(Slug::new("hello").unwrap().to_string(), "hello");
    }

    #[test]
    fn slug_deref() {
        let s = Slug::new("hello").unwrap();
        assert_eq!(&*s, "hello");
    }

    #[test]
    fn slug_from_str_and_string_comparisons() {
        let slug = "hello".parse::<Slug>().unwrap();
        let owned = String::from("hello");
        assert_eq!(slug, "hello");
        assert_eq!(slug, owned);
        assert!("Hello".parse::<Slug>().is_err());
    }

    #[test]
    fn slug_converts_into_string() {
        let slug = Slug::new("hello").unwrap();
        let inner = String::from(slug);
        assert_eq!(inner, "hello");
    }

    // Email
    #[test]
    fn email_accepts_valid() {
        let e = Email::new("user@example.com").unwrap();
        assert_eq!(e.local(), "user");
        assert_eq!(e.domain(), "example.com");
    }

    #[test]
    fn email_rejects_empty() {
        assert_eq!(Email::new("").unwrap_err(), PrimitiveError::Empty);
    }

    #[test]
    fn email_rejects_missing_at() {
        assert!(Email::new("nodomain").is_err());
    }

    #[test]
    fn email_rejects_multiple_at() {
        assert!(Email::new("a@b@c.com").is_err());
    }

    #[test]
    fn email_rejects_no_dot_in_domain() {
        assert!(Email::new("user@nodot").is_err());
    }

    #[test]
    fn email_rejects_empty_domain_labels() {
        assert!(Email::new("user@example..com").is_err());
        assert!(Email::new("user@.example.com").is_err());
        assert!(Email::new("user@example.com.").is_err());
    }

    #[test]
    fn email_rejects_spaces() {
        assert!(Email::new("us er@example.com").is_err());
    }

    #[test]
    fn email_rejects_tab() {
        assert!(Email::new("user\t@example.com").is_err());
    }

    #[test]
    fn email_rejects_newline() {
        assert!(Email::new("user\n@example.com").is_err());
    }

    #[test]
    fn url_rejects_whitespace_host() {
        assert!(HttpUrl::new("http://   ").is_err());
    }

    #[test]
    fn url_rejects_whitespace_in_path() {
        assert!(HttpUrl::new("https://ex ample.com").is_err());
    }

    #[test]
    fn email_display() {
        use alloc::string::ToString;
        assert_eq!(Email::new("a@b.com").unwrap().to_string(), "a@b.com");
    }

    #[test]
    fn email_from_str_and_string_comparisons() {
        let email = "a@b.com".parse::<Email>().unwrap();
        let owned = String::from("a@b.com");
        assert_eq!(email, "a@b.com");
        assert_eq!(email, owned);
        assert!("bad".parse::<Email>().is_err());
    }

    #[test]
    fn email_string_ergonomics() {
        let email = Email::try_from(String::from("a@b.com")).unwrap();
        let borrowed: &str = email.as_ref();
        assert_eq!(borrowed, "a@b.com");
        assert_eq!(&*email, "a@b.com");

        let inner = String::from(email);
        assert_eq!(inner, "a@b.com");
    }

    // HttpUrl
    #[test]
    fn url_accepts_http() {
        let u = HttpUrl::new("http://example.com").unwrap();
        assert!(!u.is_https());
    }

    #[test]
    fn url_accepts_https() {
        let u = HttpUrl::new("https://example.com/path").unwrap();
        assert!(u.is_https());
    }

    #[test]
    fn url_rejects_empty() {
        assert_eq!(HttpUrl::new("").unwrap_err(), PrimitiveError::Empty);
    }

    #[test]
    fn url_rejects_missing_scheme() {
        assert!(HttpUrl::new("ftp://example.com").is_err());
    }

    #[test]
    fn url_rejects_empty_host() {
        assert!(HttpUrl::new("https://").is_err());
    }

    #[test]
    fn url_rejects_missing_host_before_path() {
        assert!(HttpUrl::new("https:///path").is_err());
    }

    #[test]
    fn url_display() {
        use alloc::string::ToString;
        let u = HttpUrl::new("https://example.com").unwrap();
        assert_eq!(u.to_string(), "https://example.com");
    }

    #[test]
    fn url_is_https_uppercase_scheme() {
        let u = HttpUrl::new("HTTPS://example.com").unwrap();
        assert!(u.is_https());
    }

    #[test]
    fn url_accepts_uppercase_http_scheme() {
        let u = HttpUrl::new("HTTP://example.com").unwrap();
        assert!(!u.is_https());
    }

    #[test]
    fn url_is_http_not_https() {
        let u = HttpUrl::new("http://example.com").unwrap();
        assert!(!u.is_https());
    }

    #[test]
    fn url_from_str_and_string_comparisons() {
        let url = "https://example.com".parse::<HttpUrl>().unwrap();
        let owned = String::from("https://example.com");
        assert_eq!(url, "https://example.com");
        assert_eq!(url, owned);
        assert!("ftp://example.com".parse::<HttpUrl>().is_err());
    }

    #[test]
    fn url_string_ergonomics() {
        let url = HttpUrl::try_from(String::from("https://example.com")).unwrap();
        let borrowed: &str = url.as_ref();
        assert_eq!(borrowed, "https://example.com");
        assert_eq!(&*url, "https://example.com");

        let inner = String::from(url);
        assert_eq!(inner, "https://example.com");
    }

    // HexString
    #[test]
    fn hex_accepts_plain() {
        let h = HexString::new("deadbeef").unwrap();
        assert_eq!(h.hex_digits(), "deadbeef");
        assert!(!h.has_prefix());
    }

    #[test]
    fn hex_accepts_prefixed() {
        let h = HexString::new("0xdeadbeef").unwrap();
        assert_eq!(h.hex_digits(), "deadbeef");
        assert!(h.has_prefix());
    }

    #[test]
    fn hex_accepts_uppercase() {
        assert!(HexString::new("DEADBEEF").is_ok());
    }

    #[test]
    fn hex_rejects_empty() {
        assert_eq!(HexString::new("").unwrap_err(), PrimitiveError::Empty);
    }

    #[test]
    fn hex_rejects_prefix_only() {
        assert!(HexString::new("0x").is_err());
    }

    #[test]
    fn hex_rejects_invalid_chars() {
        assert!(HexString::new("xyz").is_err());
    }

    #[test]
    fn hex_display() {
        use alloc::string::ToString;
        assert_eq!(HexString::new("ff00").unwrap().to_string(), "ff00");
    }

    #[test]
    fn hex_from_str_and_string_comparisons() {
        let hex = "ff00".parse::<HexString>().unwrap();
        let owned = String::from("ff00");
        assert_eq!(hex, "ff00");
        assert_eq!(hex, owned);
        assert!("xyz".parse::<HexString>().is_err());
    }

    #[test]
    fn hex_string_ergonomics() {
        let hex = HexString::try_from(String::from("ff00")).unwrap();
        let borrowed: &str = hex.as_ref();
        assert_eq!(borrowed, "ff00");
        assert_eq!(&*hex, "ff00");

        let inner = String::from(hex);
        assert_eq!(inner, "ff00");
    }

    #[test]
    fn base64_accepts_valid() {
        assert_eq!(Base64::new("aGVsbG8=").unwrap().as_str(), "aGVsbG8=");
        assert!(Base64::new("YWJjZA==").is_ok()); // two pads
        assert!(Base64::new("YWJjZGU+").is_ok()); // '+' and no pad
        assert!(Base64::new("ab/+ZZ90").is_ok());
    }

    #[test]
    fn base64_rejects_bad() {
        assert_eq!(
            Base64::new("").unwrap_err().kind(),
            PrimitiveErrorKind::Empty
        );
        assert_eq!(
            Base64::new("aGVsbG8").unwrap_err().kind(), // not a multiple of 4
            PrimitiveErrorKind::InvalidFormat
        );
        assert!(Base64::new("ab-_ZZ90").is_err()); // url-safe alphabet
        assert!(Base64::new("ab=cZZ90").is_err()); // interior padding
        assert!(Base64::new("ab======").is_err()); // too much padding
    }

    #[test]
    fn base64_padding_and_decoded_len() {
        let b = Base64::new("aGVsbG8=").unwrap(); // "hello" -> 5 bytes
        assert!(b.is_padded());
        assert_eq!(b.decoded_len(), 5);
        let b = Base64::new("YWJjZA==").unwrap(); // "abcd" -> 4 bytes
        assert_eq!(b.decoded_len(), 4);
        let b = Base64::new("YWJjZGZn").unwrap(); // 6 bytes, no pad
        assert!(!b.is_padded());
        assert_eq!(b.decoded_len(), 6);
    }

    // Base32 (RFC 4648 test vectors: f/fo/foo/foob/fooba/foobar)
    #[test]
    fn base32_accepts_valid() {
        assert_eq!(Base32::new("MZXW6YTB").unwrap().as_str(), "MZXW6YTB"); // "fooba"
        assert!(Base32::new("MY======").is_ok()); // "f"
        assert!(Base32::new("MZXQ====").is_ok()); // "fo"
        assert!(Base32::new("MZXW6===").is_ok()); // "foo"
        assert!(Base32::new("MZXW6YQ=").is_ok()); // "foob"
        assert!(Base32::new("MZXW6YTBOI======").is_ok()); // "foobar"
    }

    #[test]
    fn base32_rejects_bad() {
        assert_eq!(
            Base32::new("").unwrap_err().kind(),
            PrimitiveErrorKind::Empty
        );
        assert_eq!(
            Base32::new("MZXW6YT").unwrap_err().kind(), // not a multiple of 8
            PrimitiveErrorKind::InvalidFormat
        );
        assert!(Base32::new("mzxw6ytb").is_err()); // lowercase not accepted
        assert!(Base32::new("MZXW6YT1").is_err()); // '1' outside the 2-7 digits
        assert!(Base32::new("MZXW6Y==").is_err()); // invalid padding amount (2)
        assert!(Base32::new("M=XW6YTB").is_err()); // interior padding
    }

    #[test]
    fn base32_padding_and_decoded_len() {
        let b = Base32::new("MY======").unwrap(); // "f" -> 1 byte
        assert!(b.is_padded());
        assert_eq!(b.decoded_len(), 1);
        assert_eq!(Base32::new("MZXQ====").unwrap().decoded_len(), 2); // "fo"
        assert_eq!(Base32::new("MZXW6===").unwrap().decoded_len(), 3); // "foo"
        assert_eq!(Base32::new("MZXW6YQ=").unwrap().decoded_len(), 4); // "foob"
        let full = Base32::new("MZXW6YTB").unwrap(); // "fooba" -> 5 bytes
        assert!(!full.is_padded());
        assert_eq!(full.decoded_len(), 5);
        assert_eq!(Base32::new("MZXW6YTBOI======").unwrap().decoded_len(), 6); // "foobar"
    }

    #[test]
    fn identifier_accepts_valid() {
        assert_eq!(Identifier::new("user_id").unwrap().as_str(), "user_id");
        assert!(Identifier::new("_private").is_ok());
        assert!(Identifier::new("A1").is_ok());
        assert!(Identifier::new("x").is_ok());
    }

    #[test]
    fn identifier_rejects_bad() {
        assert_eq!(
            Identifier::new("").unwrap_err().kind(),
            PrimitiveErrorKind::Empty
        );
        assert!(Identifier::new("3bad").is_err()); // starts with digit
        assert!(Identifier::new("has space").is_err());
        assert!(Identifier::new("dash-no").is_err());
        assert!(Identifier::new("café").is_err()); // non-ascii
    }

    #[test]
    fn hostname_accepts_valid() {
        assert_eq!(
            Hostname::new("api.example.com").unwrap().as_str(),
            "api.example.com"
        );
        assert!(Hostname::new("localhost").is_ok());
        assert!(Hostname::new("a-b.c-d.example").is_ok());
        let h = Hostname::new("api.example.com").unwrap();
        let labels: alloc::vec::Vec<&str> = h.labels().collect();
        assert_eq!(labels, ["api", "example", "com"]);
    }

    #[test]
    fn hostname_rejects_bad() {
        assert_eq!(
            Hostname::new("").unwrap_err().kind(),
            PrimitiveErrorKind::Empty
        );
        assert!(Hostname::new("-bad.com").is_err()); // leading hyphen
        assert!(Hostname::new("bad-.com").is_err()); // trailing hyphen
        assert!(Hostname::new("a..b").is_err()); // empty label
        assert!(Hostname::new(".leading").is_err());
        assert!(Hostname::new("trailing.").is_err());
        assert!(Hostname::new("under_score.com").is_err()); // underscore not allowed
        assert!(Hostname::new(String::from("a").repeat(64)).is_err());
        let too_long = alloc::format!("{}.com", String::from("a").repeat(252));
        assert!(Hostname::new(too_long).is_err());
    }

    // The owned/reference comparisons below intentionally exercise the
    // `PartialEq<String>` and `PartialEq<&String>` impls, which `cmp_owned` and
    // `op_ref` would otherwise rewrite away.
    #[test]
    #[allow(clippy::cmp_owned, clippy::op_ref)]
    fn base64_conversions_and_traits() {
        let from_str: Base64 = "YWJj".parse().unwrap();
        let try_ref = Base64::try_from("YWJj").unwrap();
        let try_owned = Base64::try_from(String::from("YWJj")).unwrap();
        assert_eq!(from_str, try_ref);
        assert_eq!(try_ref, try_owned);

        assert_eq!(try_ref.to_string(), "YWJj"); // Display
        let as_ref: &str = try_ref.as_ref(); // AsRef
        assert_eq!(as_ref, "YWJj");
        assert_eq!(&*try_ref, "YWJj"); // Deref
        assert!(try_ref == "YWJj"); // PartialEq<&str>
        assert!(try_ref == *"YWJj"); // PartialEq<str>
        assert!(try_ref == String::from("YWJj")); // PartialEq<String>
        assert!(try_ref == &String::from("YWJj")); // PartialEq<&String>
        assert_eq!(String::from(try_owned), "YWJj"); // From<Base64> for String
    }

    #[test]
    #[allow(clippy::cmp_owned, clippy::op_ref)]
    fn identifier_conversions_and_traits() {
        let from_str: Identifier = "user_id".parse().unwrap();
        let try_ref = Identifier::try_from("user_id").unwrap();
        let try_owned = Identifier::try_from(String::from("user_id")).unwrap();
        assert_eq!(from_str, try_ref);
        assert_eq!(try_ref, try_owned);

        assert_eq!(try_ref.to_string(), "user_id");
        let as_ref: &str = try_ref.as_ref();
        assert_eq!(as_ref, "user_id");
        assert_eq!(&*try_ref, "user_id");
        assert!(try_ref == "user_id");
        assert!(try_ref == *"user_id");
        assert!(try_ref == String::from("user_id"));
        assert!(try_ref == &String::from("user_id"));
        assert_eq!(String::from(try_owned), "user_id");
    }

    #[test]
    #[allow(clippy::cmp_owned, clippy::op_ref)]
    fn hostname_conversions_and_traits() {
        let from_str: Hostname = "example.com".parse().unwrap();
        let try_ref = Hostname::try_from("example.com").unwrap();
        let try_owned = Hostname::try_from(String::from("example.com")).unwrap();
        assert_eq!(from_str, try_ref);
        assert_eq!(try_ref, try_owned);

        assert_eq!(try_ref.to_string(), "example.com");
        let as_ref: &str = try_ref.as_ref();
        assert_eq!(as_ref, "example.com");
        assert_eq!(&*try_ref, "example.com");
        assert!(try_ref == "example.com");
        assert!(try_ref == *"example.com");
        assert!(try_ref == String::from("example.com"));
        assert!(try_ref == &String::from("example.com"));
        assert_eq!(String::from(try_owned), "example.com");
    }
}