domain 0.12.2

A DNS library for Rust.
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
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
//! Labels in domain names.

use core::{
    borrow::{Borrow, BorrowMut},
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    iter::FusedIterator,
    ops::{Deref, DerefMut},
    str::FromStr,
};

use crate::new::base::parse::{
    ParseMessageBytes, SplitMessageBytes, split_without_compression,
};
use crate::new::base::wire::{
    AsBytes, BuildBytes, ParseBytes, ParseError, SplitBytes, TruncationError,
};
use crate::new::base::{
    build::{BuildInMessage, NameCompressor},
    parse::parse_without_compression,
};
use crate::utils::dst::{UnsizedCopy, UnsizedCopyFrom};

//----------- Label ----------------------------------------------------------

/// A label in a domain name.
///
/// A domain name like `www.example.org.` contains 4 labels: `www`, `example`,
/// `org`, and the root label. They are encoded (in the DNS wire format) like
/// `3 www 7 example 3 org 0`, where each number is called a _length octet_.
/// In general, a label consists of 0 to 63 (inclusive) bytes of arbitrary
/// data, preceded by a 1-byte length octet.
///
/// A `Label` is simple wrapper around `[u8]`, and must be used in similar
/// ways (e.g. `&Label`, `Box<Label>`). It is a byte slice beginning with a
/// length octet, followed by the specified number of bytes. A `Label` for
/// `www` would contain the bytes `\x03www`.
///
/// `Label`s are rarely used directly; the vast majority of their uses occur
/// as part of domain names like [`Name`](super::Name).
///
/// ## Constructing a `Label`
///
/// `Label` is a _dynamically sized type_ (DST), like `[u8]`, which makes it a
/// little unwieldy. It is most easily used by reference, i.e. `&Label`.
///
/// You can parse a `Label` from the DNS wire format using
/// [`<&Label>::split_bytes()`] (when the input might contain data after the
/// label) or [`<&Label>::parse_bytes()`] (when the input ends right after
/// the label).
///
/// [`<&Label>::split_bytes()`]: #method.split_bytes
/// [`<&Label>::parse_bytes()`]: #method.parse_bytes
///
/// The [`label`] macro is helpful for writing tests, and it shows up in many
/// of the tests and examples here. It constructs a label from a hard-coded
/// (byte) string literal.
///
/// ```
/// # use domain::new::base::name::{Label, label};
/// # use domain::new::base::wire::{ParseError, ParseBytes, SplitBytes};
/// #
/// let input = b"\x03www\x07example\x03org\x00";
/// let (label, input) = <&Label>::split_bytes(input)?;
/// assert_eq!(label.contents(), b"www");
/// let (label, input) = <&Label>::split_bytes(input)?;
/// assert_eq!(label.contents(), b"example");
/// let (label, input) = <&Label>::split_bytes(input)?;
/// assert_eq!(label.contents(), b"org");
/// let (label, input) = <&Label>::split_bytes(input)?;
/// assert_eq!(label.contents(), b"");
///
/// let input = b"\x07example";
/// let label: &Label = <&Label>::parse_bytes(input)?;
/// assert_eq!(label.contents(), b"example");
/// assert_eq!(label.as_wire(), b"\x07example");
/// // `label` is not a copy of the input; it refers to the same address.
/// assert_eq!(label.as_wire().as_ptr(), input.as_ptr());
///
/// // You may see `label!` used in examples here.
/// // It generates a `&'static Label` for hard-coded labels.
/// assert_eq!(label, label!(b"example"));
/// #
/// # Ok::<(), ParseError>(())
/// ```
///
/// While `&Label` is the preferred way of handling labels, you may sometimes
/// need to store them 'on their own', without a lifetime. With a byte slice,
/// you could achieve this using `Box<[u8]>` or `Vec<u8>`. For `Label`, you
/// can use `Box<Label>` or [`LabelBuf`].
///
/// ```
/// # #![cfg(feature = "alloc")]
/// # use domain::new::base::name::{Label, LabelBuf, label};
/// # use domain::new::base::wire::ParseBytes;
/// # use domain::utils::dst::{UnsizedCopy, UnsizedCopyFrom};
/// #
/// let label: &Label = label!(b"example");
///
/// // Copy into a fixed-size buffer (ideal for modification):
/// let buffer: LabelBuf = label.to_buf();
/// let buffer: LabelBuf = label.unsized_copy_into();
/// let buffer: LabelBuf = LabelBuf::copy_from(label);
/// let buffer: LabelBuf = LabelBuf::unsized_copy_from(label);
///
/// // Copy into a heap allocation (ideal for long-term storage):
/// let boxed: Box<Label> = label.to_boxed();
/// let boxed: Box<Label> = label.unsized_copy_into();
/// let boxed: Box<Label> = Box::unsized_copy_from(label);
/// ```
///
/// ## Accessing the bytes
///
/// `Label` does not implement [`AsRef<[u8]>`] or provide other conveniences
/// to access the underlying bytes, because it is unclear whether the
/// implementation should include the length octet with those bytes.
///
/// [`AsRef<[u8]>`]: core::convert::AsRef
///
/// The preferred ways to access the bytes are [`Self::as_wire()`] (which
/// explicitly includes the length octet) and [`Self::contents()`] (which
/// explicitly does not).
///
/// `Label`'s implementation of [`AsBytes`] includes the length octet, as
/// [`AsBytes`] is primarily intended for encoding into a byte stream as in
/// the DNS wire format.
#[derive(AsBytes, UnsizedCopy)]
#[repr(transparent)]
pub struct Label([u8]);

//--- Associated Constants

impl Label {
    /// The root label.
    pub const ROOT: &'static Self = {
        // SAFETY: This is a correctly encoded label.
        unsafe { Self::from_bytes_unchecked(&[0]) }
    };

    /// The wildcard label.
    pub const WILDCARD: &'static Self = {
        // SAFETY: This is a correctly encoded label.
        unsafe { Self::from_bytes_unchecked(&[1, b'*']) }
    };

    /// Printable ASCII characters that can appear in labels printed in zone
    /// files without escaping.
    ///
    /// Rationale is described in [`Label#zone-file-formatting`].
    const UNESCAPED_ZONEFILE_CHARS: &[u8] = b"\
        ABCDEFGHIJKLMNOPQRSTUVWXYZ\
        abcdefghijklmnopqrstuvwxyz\
        0123456789\
        !#$%&'*+,-^_`{|}~";
}

//--- Construction

impl Label {
    /// Assume a byte slice is a valid label.
    ///
    /// This can be used to cast a label encoded in the wire format into the
    /// [`Label`] type without copying.
    ///
    /// For a checked, safe version, use [`<&Label>::parse_bytes()`].
    ///
    /// [`<&Label>::parse_bytes()`]: #method.parse_bytes
    ///
    /// ```
    /// # use domain::new::base::name::Label;
    /// #
    /// let encoded: &[u8] = b"\x07example";
    /// let label: &Label = unsafe { Label::from_bytes_unchecked(encoded) };
    /// ```
    ///
    /// # Safety
    ///
    /// The following conditions must hold for this call to be sound:
    /// - `bytes.len() <= 64`
    /// - `bytes[0] as usize + 1 == bytes.len()`
    #[must_use]
    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
        // SAFETY: 'Label' is 'repr(transparent)' to '[u8]'.
        unsafe { core::mem::transmute(bytes) }
    }

    /// Assume a mutable byte slice is a valid label.
    ///
    /// This can be used to cast a label encoded in the wire format into the
    /// [`Label`] type without copying, while retaining mutable access.
    ///
    /// ```
    /// # use domain::new::base::name::Label;
    /// #
    /// let mut encoded: [u8; 8] = *b"\x07example";
    /// let label: &mut Label = unsafe {
    ///     Label::from_mut_bytes_unchecked(&mut encoded)
    /// };
    /// ```
    ///
    /// # Safety
    ///
    /// The following conditions must hold for this call to be sound:
    /// - `bytes.len() <= 64`
    /// - `bytes[0] as usize + 1 == bytes.len()`
    #[must_use]
    pub const unsafe fn from_mut_bytes_unchecked(
        bytes: &mut [u8],
    ) -> &mut Self {
        // SAFETY: 'Label' is 'repr(transparent)' to '[u8]'.
        unsafe { core::mem::transmute(bytes) }
    }
}

//--- Manipulation

impl Label {
    /// Copy the label into a [`LabelBuf`].
    ///
    /// This is equivalent to [`LabelBuf::copy_from()`], but may be more
    /// convenient to use in some cases.
    ///
    /// This is a concrete, inherent, and `const` version of
    /// [`Self::unsized_copy_into()`].
    #[must_use]
    pub const fn to_buf(&self) -> LabelBuf {
        LabelBuf::copy_from(self)
    }

    /// Copy the label into a [`Box<Label>`].
    ///
    /// [`Box<Label>`]: alloc::boxed::Box
    ///
    /// This is a concrete, inherent version of [`Self::unsized_copy_into()`].
    #[must_use]
    #[cfg(feature = "alloc")]
    pub fn to_boxed(&self) -> alloc::boxed::Box<Label> {
        self.unsized_copy_into()
    }

    /// Lowercase the label.
    ///
    /// All ASCII uppercase characters in the label will be lowercased.
    ///
    /// ```
    /// # use domain::new::base::name::label_buf;
    /// #
    /// let mut buffer = label_buf!(b"eXAMpLE");
    /// buffer.make_lowercase();
    /// assert_eq!(buffer.contents(), b"example");
    /// ```
    pub const fn make_lowercase(&mut self) {
        // We include the length octet. It is strictly less than 64, so is
        // never a valid ASCII alphabetic character, and so it will not be
        // affected.
        self.0.make_ascii_lowercase()
    }
}

//--- Parsing from DNS messages

impl<'a> ParseMessageBytes<'a> for &'a Label {
    fn parse_message_bytes(
        contents: &'a [u8],
        start: usize,
    ) -> Result<Self, ParseError> {
        parse_without_compression(contents, start)
    }
}

impl<'a> SplitMessageBytes<'a> for &'a Label {
    fn split_message_bytes(
        contents: &'a [u8],
        start: usize,
    ) -> Result<(Self, usize), ParseError> {
        split_without_compression(contents, start)
    }
}

//--- Building into DNS messages

impl BuildInMessage for Label {
    fn build_in_message(
        &self,
        contents: &mut [u8],
        start: usize,
        _compressor: &mut NameCompressor,
    ) -> Result<usize, TruncationError> {
        let bytes = self.as_wire();
        let end = start + bytes.len();
        contents
            .get_mut(start..end)
            .ok_or(TruncationError)?
            .copy_from_slice(bytes);
        Ok(end)
    }
}

//--- Parsing from bytes

impl<'a> SplitBytes<'a> for &'a Label {
    fn split_bytes(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), ParseError> {
        let &size = bytes.first().ok_or(ParseError)?;
        if size < 64 && bytes.len() > size as usize {
            let (label, rest) = bytes.split_at(1 + size as usize);
            // SAFETY:
            // - 'label.len() = 1 + size <= 64'
            // - 'label[0] = size + 1 == label.len()'
            Ok((unsafe { Label::from_bytes_unchecked(label) }, rest))
        } else {
            Err(ParseError)
        }
    }
}

impl<'a> ParseBytes<'a> for &'a Label {
    fn parse_bytes(bytes: &'a [u8]) -> Result<Self, ParseError> {
        match Self::split_bytes(bytes) {
            Ok((this, &[])) => Ok(this),
            _ => Err(ParseError),
        }
    }
}

//--- Building into byte sequences

/// Serializing a [`Label`] as bytes.
///
/// Labels are serialized exactly as [`Label::as_wire()`], their encoding in
/// the DNS wire format: a one-byte length octet (between 0 and 63, inclusive)
/// followed by that many bytes.
impl BuildBytes for Label {
    fn build_bytes<'b>(
        &self,
        bytes: &'b mut [u8],
    ) -> Result<&'b mut [u8], TruncationError> {
        self.as_wire().build_bytes(bytes)
    }

    fn built_bytes_size(&self) -> usize {
        self.as_wire().len()
    }
}

//--- Inspection

impl Label {
    /// Whether this is the root label.
    ///
    /// Equivalent to `self == Label::ROOT`.
    #[must_use]
    pub const fn is_root(&self) -> bool {
        // We don't need to look at the length octet directly; it is always
        // equal to `self.0.len() - 1`.
        self.0.len() == 1
    }

    /// Whether this is a wildcard label.
    ///
    /// Equivalent to `self == Label::WILDCARD`.
    #[must_use]
    pub const fn is_wildcard(&self) -> bool {
        matches!(self.0, [1, b'*'])
    }

    /// The encoding of the label in the DNS wire format.
    ///
    /// This includes the length octet. It is also accessible via
    /// [`Self::as_bytes()`] and [`Self::build_bytes()`]. If you don't need
    /// the length octet, use [`Self::contents()`].
    ///
    /// ```
    /// # use domain::new::base::name::label;
    /// #
    /// let label = label!(b"example");
    /// assert_eq!(label.as_wire(), b"\x07example");
    /// assert_eq!(label.contents(), b"example");
    /// ```
    #[must_use]
    pub const fn as_wire(&self) -> &[u8] {
        &self.0
    }

    /// The contents of the label.
    ///
    /// This does not include the length octet. If you need the length octet,
    /// use [`Self::as_wire()`]. Use [`Self::contents_mut()`] for a mutable
    /// view.
    ///
    /// ```
    /// # use domain::new::base::name::label;
    /// #
    /// let label = label!(b"example");
    /// assert_eq!(label.contents(), b"example");
    /// assert_eq!(label.as_wire(), b"\x07example");
    /// ```
    #[must_use]
    pub const fn contents(&self) -> &[u8] {
        // TODO: direct slicing is not possible in `const` yet.
        //   See <https://github.com/rust-lang/rust/issues/143775>.
        // SAFETY: A `Label` always has a length octet.
        unsafe { self.0.split_at_unchecked(1).1 }
    }

    /// The contents of the label, mutably.
    ///
    /// This does not include the length octet. There is no method to get a
    /// mutable byte slice from [`Label`] including the length octet, because
    /// modifying it would result in an invalid label.
    ///
    /// ```
    /// # use domain::new::base::name::{Label, label_buf};
    /// # use domain::new::base::wire::ParseBytes;
    /// #
    /// let mut buffer = label_buf!(b"example");
    /// let label: &mut Label = buffer.as_mut_label();
    /// assert_eq!(label.contents_mut(), b"example");
    /// ```
    #[must_use]
    pub const fn contents_mut(&mut self) -> &mut [u8] {
        // NOTE: `Label`'s only safety invariant is that the length octet is
        // well-formed (it is consistent with the slice length and is less
        // than 64). No matter what the caller does with the returned bytes,
        // they cannot violate that invariant.
        //
        // TODO: slicing is not possible in `const` yet.
        // SAFETY: A `Label` always has a length octet.
        unsafe { self.0.split_at_mut_unchecked(1).1 }
    }
}

//--- Cloning

#[cfg(feature = "alloc")]
impl Clone for alloc::boxed::Box<Label> {
    fn clone(&self) -> Self {
        (*self).unsized_copy_into()
    }
}

//--- Comparison

impl PartialEq for Label {
    /// Compare two labels for equality.
    ///
    /// Labels are compared ASCII-case-insensitively, as is conventional for
    /// DNS. For a case-sensitive comparison, you can compare the byte slices
    /// (from [`Self::contents()`], not [`Self::as_wire()`]!) manually.
    ///
    /// ```
    /// # use domain::new::base::name::label;
    /// #
    /// let a = label!(b"example");
    /// let b = label!(b"eXAMpLE");
    /// let c = label!(b"unrelated");
    /// assert_eq!(a, b);
    /// assert_ne!(a.contents(), b.contents());
    /// assert_ne!(a, c);
    /// ```
    fn eq(&self, other: &Self) -> bool {
        // The length octet is strictly less than 64, so it cannot be an ASCII
        // alphabetic character. This means that it is safe to include in an
        // ASCII-case-insensitive comparison.
        //
        // We don't need to include it, because the lengths of the slices will
        // be checked already. But it is probably more efficient this way.
        // Maybe we'll benchmark it one day and find out.
        self.as_wire().eq_ignore_ascii_case(other.as_wire())
    }
}

impl Eq for Label {}

//--- Ordering

impl PartialOrd for Label {
    /// Determine the order between two labels.
    ///
    /// See [`Label::cmp()`].
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Label {
    /// Determine the order between two labels.
    ///
    /// Labels are compared ASCII-case-insensitively by their contents, as is
    /// conventional for DNS. Labels are equal if their corresponding bytes
    /// are equal (ignoring ASCII case). If their corresponding bytes are not
    /// equal, the ordering is determined by the first mismatched byte. If one
    /// label is a prefix of the other (i.e. all their corresponding bytes are
    /// equal, but one has fewer bytes), it is considered less than the other.
    ///
    /// For a case-sensitive comparison, you can compare the byte slices (from
    /// [`Self::contents()`], not [`Self::as_wire()`]!) manually.
    ///
    /// ```
    /// # use domain::new::base::name::label;
    /// #
    /// let a = label!(b"example");
    /// let b = label!(b"example-");
    /// let c = label!(b"org");
    /// assert!(a < b);
    /// assert!(a < c);
    /// assert!(b < c);
    /// ```
    fn cmp(&self, other: &Self) -> Ordering {
        // NOTE: The standard library provides `eq_ignore_ascii_case()`, but
        // not `cmp_ignore_ascii_case()`. So we implement it manually.
        let this = self.contents().iter().map(u8::to_ascii_lowercase);
        let that = other.contents().iter().map(u8::to_ascii_lowercase);
        this.cmp(that)
    }
}

//--- Hashing

impl Hash for Label {
    /// Hash this label.
    ///
    /// All uppercase ASCII characters are lowercased before being hashed.
    /// Thus, the hash is case-independent, consistent with how labels are
    /// compared and ordered. The length octet is also hashed.
    ///
    /// ```
    /// # use std::collections::hash_map::RandomState;
    /// # use std::hash::BuildHasher;
    /// # use domain::new::base::name::label;
    /// #
    /// # let hasher = RandomState::default();
    /// let a = label!(b"example");
    /// let b = label!(b"eXAMpLE");
    /// assert_eq!(a, b);
    /// assert_ne!(a.contents(), b.contents());
    /// assert_eq!(hasher.hash_one(a), hasher.hash_one(b));
    /// ```
    fn hash<H: Hasher>(&self, state: &mut H) {
        // NOTE: The length octet is unaffected by `to_ascii_lowercase()`
        // because it is strictly less than 64.
        for &byte in self.as_wire() {
            state.write_u8(byte.to_ascii_lowercase())
        }
    }
}

//--- Formatting

impl fmt::Display for Label {
    /// Print a label.
    ///
    /// There is no one convention for formatting DNS labels. Labels are
    /// usually formatted as part of a domain name, and it is not entirely
    /// clear how they should be formatted on their own. See the examples
    /// here to understand how this implementation works.
    ///
    /// To parse a label _from_ this format, see [`LabelBuf::from_str()`].
    /// [`Label`] cannot implement [`FromStr`] itself.
    ///
    /// The root label is printed as an empty string. Labels are usually
    /// delimited by `.`s when printing domain names, so this should be
    /// consistent with formatting domain names like `example.org.`.
    ///
    /// Certain characters are escaped using backslashes. There are two
    /// escape formats: `\\X`, where `X` is the character being escaped
    /// (used when `X` is a printable ASCII character), and `\\DDD`, where
    /// `DDD` is the byte value in decimal, zero-padded to three characters.
    ///
    /// The following printable ASCII characters are escaped by this version
    /// of the implementation:
    ///
    /// - `"` (`0x22`), `(` (`0x28`), `)` (`0x29`), `@` (`0x40`), `\\`
    ///   (`0x5C`): these characters are interpreted specially in zone files.
    ///
    /// - `/` (`0x2F`), `:` (`0x3A`), `;` (`0x3B`), `<` (`0x3C`), `=`
    ///   (`0x3D`), `>` (`0x3E`), `?` (`0x3F`) `[` (`0x5B`), `]` (`0x5D`):
    ///   these characters are sometimes used to delimit URLs, which may be
    ///   nothing more than domain names.
    ///
    /// The following printable ASCII characters are _not_ escaped by this
    /// version of the implementation: `!`, `#`, `$`, `%`, `&`, `'`, `*`, `+`,
    /// `,`, `-`, `^`, `_`, `\``, `~`, `{`, `|`, `}`.
    ///
    /// Note that ASCII space ` ` is not considered a printable character; it
    /// will be printed as `\\032`.
    ///
    /// Because the zone file format (which is the primary motivation for
    /// this implementation) is quite under-specified, the details of this
    /// implementation may change over time. Some printable ASCII characters
    /// that are not escaped today may be escaped in the future. Characters
    /// that are escaped using `\\X` syntax today could be escaped using
    /// `\\DDD` syntax in the future.
    ///
    /// ```
    /// # use domain::new::base::name::{Label, label};
    /// #
    /// // The simple case is pretty simple.
    /// assert_eq!(label!(b"example").to_string(), "example");
    ///
    /// // Uppercase characters are printed as such.
    /// assert_eq!(label!(b"eXAMplE").to_string(), "eXAMplE");
    ///
    /// // The root label is an empty string.
    /// assert_eq!(Label::ROOT.to_string(), "");
    ///
    /// // Non-ASCII characters are escaped.
    /// let label = label!(b"helloworld\xF0\x9F\x8F\xB3\xEF\xB8\x8F\xE2\x80\x8D\xE2\x9A\xA7\xEF\xB8\x8F");
    /// assert_eq!(label.to_string(),
    ///     r"helloworld\240\159\143\179\239\184\143\226\128\141\226\154\167\239\184\143");
    ///
    /// // Uncommon and non-printable ASCII characters are escaped too.
    /// let label = label!(b"\x00\x0A!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\x7F");
    /// assert_eq!(label.to_string(),
    ///     r##"\000\010!\"#$%&'\(\)*+,-\.\/\:\;\<\=\>\?\@\[\\\]^_`{|}~\127"##);
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.contents().iter().try_for_each(|&byte| {
            if Label::UNESCAPED_ZONEFILE_CHARS.contains(&byte) {
                write!(f, "{}", byte as char)
            } else if byte.is_ascii_graphic() {
                write!(f, "\\{}", byte as char)
            } else {
                write!(f, "\\{:03}", byte)
            }
        })
    }
}

impl fmt::Debug for Label {
    /// Print a label for debugging purposes.
    ///
    /// The format used might change in the future, and is not documented to
    /// prevent it from being relied upon.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Label(\"{self}\")")
    }
}

//--- Serialize

#[cfg(feature = "serde")]
impl serde::Serialize for Label {
    /// Serialize a label.
    ///
    /// See [the Serde data model](https://serde.rs/data-model.html) for an
    /// understanding of the terms here.
    ///
    /// Labels are serialized as `newtype_struct`s of name `Label`. For
    /// human-readable formats (e.g. JSON and TOML), they are serialized
    /// as per [`<Label as Display>::fmt()`]. For compact formats (e.g.
    /// Postcard), they are serialized as byte slices (specifically
    /// [`Self::contents()`], excluding the length octet).
    ///
    /// [`<Label as Display>::fmt()`]: #method.fmt
    ///
    /// To deserialize a label, see [`LabelBuf::deserialize()`] or
    /// [`<Box<Label>>::deserialize()`]. They use exactly the same format.
    /// [`Label`] cannot implement [`serde::Deserialize`] itself.
    ///
    /// [`LabelBuf::deserialize()`]: struct.LabelBuf.html#method.deserialize
    /// [`<Box<Label>>::deserialize()`]: #method.deserialize
    ///
    /// ```
    /// # use serde_test::{Configure, Token, assert_ser_tokens};
    /// # use domain::new::base::name::label;
    /// #
    /// assert_ser_tokens(&label!(b"example\x7Fabc").readable(), &[
    ///     Token::NewtypeStruct { name: "Label" },
    ///     Token::String("example\\127abc"),
    /// ]);
    /// assert_ser_tokens(&label!(b"example\x7Fabc").compact(), &[
    ///     Token::NewtypeStruct { name: "Label" },
    ///     Token::Bytes(b"example\x7Fabc"),
    /// ]);
    /// ```
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if serializer.is_human_readable() {
            serializer
                .serialize_newtype_struct("Label", &format_args!("{self}"))
        } else {
            // `impl Serialize for [u8]` serializes to `Seq`, not `Bytes`.

            struct NV<'a>(&'a [u8]);

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

            serializer.serialize_newtype_struct("Label", &NV(self.contents()))
        }
    }
}

//----------- LabelBuf -------------------------------------------------------

/// A 64-byte buffer holding a [`Label`].
#[derive(Clone)]
#[repr(transparent)]
pub struct LabelBuf {
    /// The label bytes.
    data: [u8; 64],
}

//--- Construction

impl LabelBuf {
    /// Construct a new, empty [`LabelBuf`].
    ///
    /// The resulting buffer contains the root label. It can be appended to.
    #[must_use]
    pub const fn new() -> Self {
        Self { data: [0u8; 64] }
    }

    /// Copy a [`Label`] into a buffer.
    ///
    /// This is a concrete, inherent, and `const` version of
    /// [`Self::unsized_copy_from()`].
    ///
    /// ```
    /// # use domain::new::base::name::{LabelBuf, label};
    /// # use domain::new::base::wire::ParseBytes;
    /// #
    /// let buffer: LabelBuf = LabelBuf::copy_from(label!(b"example"));
    /// assert_eq!(buffer.as_wire(), b"\x07example");
    /// ```
    #[must_use]
    pub const fn copy_from(label: &Label) -> Self {
        let bytes = label.as_wire();
        let mut data = [0u8; 64];
        // TODO: `for` loops and slicing aren't `const` yet.
        let mut index = 0usize;
        while index < bytes.len() {
            data[index] = bytes[index];
            index += 1;
        }
        Self { data }
    }
}

impl Default for LabelBuf {
    fn default() -> Self {
        Self::new()
    }
}

impl UnsizedCopyFrom for LabelBuf {
    type Source = Label;

    fn unsized_copy_from(value: &Self::Source) -> Self {
        Self::copy_from(value)
    }
}

//--- Manipulation

impl LabelBuf {
    /// Append bytes to the label.
    ///
    /// The length octet will be adjusted automatically.
    ///
    /// ```
    /// # use domain::new::base::name::LabelBuf;
    /// #
    /// let mut buffer = LabelBuf::new();
    /// buffer.append(b"hello").unwrap();
    /// buffer.append(b"world").unwrap();
    /// assert_eq!(buffer.as_wire(), b"\x0Ahelloworld");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TruncationError`] if the bytes do not fit in the buffer.
    /// The buffer will be unmodified.
    pub const fn append(
        &mut self,
        bytes: &[u8],
    ) -> Result<(), TruncationError> {
        let len = self.data[0] as usize;
        // PANIC: `len < 64`, and `bytes.len() <= isize::MAX` as that is the
        // largest legal size of an allocation. So this addition will not
        // overflow.
        let new_len = len + bytes.len();
        if new_len >= 64 {
            return Err(TruncationError);
        }

        // TODO: direct slicing is not possible in `const` yet.
        //   See <https://github.com/rust-lang/rust/issues/143775>.
        // SAFETY:
        // - `1 + len <= 64 = data.len()`.
        // - `new_len = len + bytes.len() < 64`.
        // - Thus `bytes.len() < 64 - len`.
        // - Thus `bytes.len() <= 64 - (1 + len)`.
        let target = unsafe {
            self.data
                .split_at_mut_unchecked(1 + len)
                .1
                .split_at_mut_unchecked(bytes.len())
                .0
        };
        target.copy_from_slice(bytes);
        self.data[0] = new_len as u8;

        Ok(())
    }

    /// Append a single byte to the label.
    ///
    /// The length octet will be adjusted automatically.
    ///
    /// Also see [`Self::append()`].
    ///
    /// ```
    /// # use domain::new::base::name::LabelBuf;
    /// #
    /// let mut buffer = LabelBuf::new();
    /// buffer.append(b"hello").unwrap();
    /// buffer.push(b'4').unwrap();
    /// buffer.push(b'2').unwrap();
    /// assert_eq!(buffer.as_wire(), b"\x07hello42");
    /// ```
    ///
    /// # Errors
    ///
    /// Returns [`TruncationError`] if the byte does not fit in the buffer.
    /// The buffer will be unmodified.
    pub const fn push(&mut self, byte: u8) -> Result<(), TruncationError> {
        let len = self.data[0] as usize;
        if len >= 63 {
            return Err(TruncationError);
        }

        self.data[1 + len] = byte;
        self.data[0] = 1 + len as u8;
        Ok(())
    }

    /// Truncate the label to a particular length.
    ///
    /// The length octet will be adjusted automatically.
    ///
    /// ```
    /// # use domain::new::base::name::LabelBuf;
    /// #
    /// let mut buffer = LabelBuf::new();
    /// buffer.append(b"example");
    /// assert_eq!(buffer.as_wire(), b"\x07example");
    /// buffer.truncate(4);
    /// assert_eq!(buffer.as_wire(), b"\x04exam");
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the label is strictly shorter than `new_len`.
    pub const fn truncate(&mut self, new_len: usize) {
        // TODO: Include `len` and `new_len` in the assert message once it is
        // `const`-safe to do so.
        let len = self.data[0] as usize;
        assert!(new_len <= len, "Label is shorter than desired length");
        self.data[0] = new_len as u8;
    }
}

//--- Parsing from DNS messages

impl ParseMessageBytes<'_> for LabelBuf {
    fn parse_message_bytes(
        contents: &'_ [u8],
        start: usize,
    ) -> Result<Self, ParseError> {
        parse_without_compression(contents, start)
    }
}

impl SplitMessageBytes<'_> for LabelBuf {
    fn split_message_bytes(
        contents: &'_ [u8],
        start: usize,
    ) -> Result<(Self, usize), ParseError> {
        split_without_compression(contents, start)
    }
}

//--- Building into DNS messages

impl BuildInMessage for LabelBuf {
    fn build_in_message(
        &self,
        contents: &mut [u8],
        start: usize,
        compressor: &mut NameCompressor,
    ) -> Result<usize, TruncationError> {
        Label::build_in_message(self, contents, start, compressor)
    }
}

//--- Parsing from byte sequences

impl ParseBytes<'_> for LabelBuf {
    fn parse_bytes(bytes: &[u8]) -> Result<Self, ParseError> {
        <&Label>::parse_bytes(bytes).map(Self::copy_from)
    }
}

impl SplitBytes<'_> for LabelBuf {
    fn split_bytes(bytes: &'_ [u8]) -> Result<(Self, &'_ [u8]), ParseError> {
        <&Label>::split_bytes(bytes)
            .map(|(label, rest)| (Self::copy_from(label), rest))
    }
}

//--- Building into byte sequences

impl BuildBytes for LabelBuf {
    fn build_bytes<'b>(
        &self,
        bytes: &'b mut [u8],
    ) -> Result<&'b mut [u8], TruncationError> {
        (**self).build_bytes(bytes)
    }

    fn built_bytes_size(&self) -> usize {
        (**self).built_bytes_size()
    }
}

//--- Access to the underlying 'Label'

impl LabelBuf {
    /// Access the underlying [`Label`].
    ///
    /// This is a `const` version of [`Self::deref()`].
    #[must_use]
    pub const fn as_label(&self) -> &Label {
        let size = self.data[0];
        // TODO: slicing is not possible in `const` yet.
        // SAFETY: `size < 64`.
        let label = unsafe {
            core::slice::from_raw_parts(self.data.as_ptr(), 1 + size as usize)
        };
        // SAFETY: A `LabelBuf` always contains a valid `Label`.
        unsafe { Label::from_bytes_unchecked(label) }
    }

    /// Access the underlying [`Label`] mutably.
    ///
    /// This is a `const` version of [`Self::deref_mut()`].
    #[must_use]
    pub const fn as_mut_label(&mut self) -> &mut Label {
        let size = self.data[0];
        // TODO: slicing is not possible in `const` yet.
        // SAFETY: `size < 64`.
        let label = unsafe {
            core::slice::from_raw_parts_mut(
                self.data.as_mut_ptr(),
                1 + size as usize,
            )
        };
        // SAFETY: A `LabelBuf` always contains a valid `Label`.
        unsafe { Label::from_mut_bytes_unchecked(label) }
    }
}

impl Deref for LabelBuf {
    type Target = Label;

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

impl DerefMut for LabelBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.as_mut_label()
    }
}

impl Borrow<Label> for LabelBuf {
    fn borrow(&self) -> &Label {
        self
    }
}

impl BorrowMut<Label> for LabelBuf {
    fn borrow_mut(&mut self) -> &mut Label {
        self
    }
}

impl AsRef<Label> for LabelBuf {
    fn as_ref(&self) -> &Label {
        self
    }
}

impl AsMut<Label> for LabelBuf {
    fn as_mut(&mut self) -> &mut Label {
        self
    }
}

//--- Forwarding equality, comparison, and hashing

impl PartialEq for LabelBuf {
    /// See [`Label::eq()`].
    fn eq(&self, that: &Self) -> bool {
        **self == **that
    }
}

impl Eq for LabelBuf {}

impl PartialOrd for LabelBuf {
    /// See [`Label::partial_cmp()`].
    fn partial_cmp(&self, that: &Self) -> Option<Ordering> {
        Some(self.cmp(that))
    }
}

impl Ord for LabelBuf {
    /// See [`Label::cmp()`].
    fn cmp(&self, that: &Self) -> Ordering {
        (**self).cmp(&**that)
    }
}

impl Hash for LabelBuf {
    /// See [`Label::hash()`].
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

//--- Forwarding formatting

impl fmt::Display for LabelBuf {
    /// See [`<Label as Display>::fmt()`].
    ///
    /// [`<Label as Display>::fmt()`]: struct.Label.html#method.fmt
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

impl fmt::Debug for LabelBuf {
    /// Print a label for debugging purposes.
    ///
    /// The format used might change in the future, and is not documented to
    /// prevent it from being relied upon.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "LabelBuf(\"{self}\")")
    }
}

//--- Parsing from strings

impl LabelBuf {
    /// Parse a printed label.
    ///
    /// This will parse a label from the format used by [`<Label as
    /// Display>::fmt()`]. Labels are usually parsed as part of a domain name,
    /// and it is not entirely clear how they should be parsed on their own.
    /// See the examples here to understand how this implementation works.
    ///
    /// [`<Label as Display>::fmt()`]: struct.Label.html#method.fmt
    ///
    /// This function is a direct inverse of [`<Label as Display>::fmt()`],
    /// but it cannot be used to parse a label embedded within a larger
    /// string. For that, see [`LabelBuf::split_str()`].
    ///
    /// ```
    /// # use domain::new::base::name::{LabelBuf, LabelParseError, label_buf};
    /// #
    /// assert_eq!(
    ///     LabelBuf::parse_str(b"example"),
    ///     Ok(label_buf!(b"example")));
    ///
    /// assert_eq!(
    ///     LabelBuf::parse_str(b"foo\\.b\\010r"),
    ///     Ok(label_buf!(b"foo.b\x0Ar")));
    ///
    /// // An empty input is parsed as the root label.
    /// assert_eq!(
    ///     LabelBuf::parse_str(b""),
    ///     Ok(LabelBuf::new()));
    ///
    /// // Irregular characters cause failure.
    /// assert_eq!(
    ///     LabelBuf::parse_str(b"example.com."),
    ///     Err(LabelParseError::InvalidChar));
    /// ```
    pub fn parse_str(mut s: &[u8]) -> Result<Self, LabelParseError> {
        // The buffer we'll fill into.
        let mut this = Self::new();

        // Parse character by character.
        loop {
            let &[b, ref rest @ ..] = s else {
                // The entire input has been consumed.
                return Ok(this);
            };
            s = rest;
            if Label::UNESCAPED_ZONEFILE_CHARS.contains(&b) {
                // A regular label character.
                this.push(b).map_err(|_| LabelParseError::Overlong)?;
            } else if b == b'\\' {
                // An escape character.
                let &[b, ref rest @ ..] = s else {
                    return Err(LabelParseError::PartialEscape);
                };
                let value = if b.is_ascii_digit() {
                    let (digits, rest) = s
                        .split_at_checked(3)
                        .ok_or(LabelParseError::PartialEscape)?;
                    s = rest;
                    let digits = core::str::from_utf8(digits)
                        .map_err(|_| LabelParseError::InvalidEscape)?;
                    digits
                        .parse()
                        .map_err(|_| LabelParseError::InvalidEscape)?
                } else if b.is_ascii_graphic() {
                    s = rest;
                    b
                } else {
                    return Err(LabelParseError::InvalidEscape);
                };
                this.push(value).map_err(|_| LabelParseError::Overlong)?;
            } else {
                return Err(LabelParseError::InvalidChar);
            };
        }
    }

    /// Parse a printed label from a larger string.
    ///
    /// This will parse a label from the format used by [`<Label as
    /// Display>::fmt()`]. Labels are usually parsed as part of a domain name,
    /// and it is not entirely clear how they should be parsed on their own.
    /// See the examples here to understand how this implementation works.
    ///
    /// [`<Label as Display>::fmt()`]: struct.Label.html#method.fmt
    ///
    /// This function is designed for use when parsing labels embedded within
    /// some larger string (e.g. a zone file). The string may be buffered,
    /// so only a part of it is provided; the string is considered to be
    /// infinitely long. A label is only parsed successfully once a delimiting
    /// byte (one that lies _after_ it) is found. As such, this function is
    /// **not** a perfect inverse of [`<Label as Display>::fmt()`]. For such
    /// an inverse, see [`LabelBuf::parse_str()`].
    ///
    /// ```
    /// # use domain::new::base::name::{LabelBuf, LabelSplitError, label_buf};
    /// #
    /// assert_eq!(
    ///     LabelBuf::split_str(b"example.com."),
    ///     Ok((label_buf!(b"example"), &b".com."[..])));
    ///
    /// assert_eq!(
    ///     LabelBuf::split_str(b"foo\\.b\\010r.com."),
    ///     Ok((label_buf!(b"foo.b\x0Ar"), &b".com."[..])));
    ///
    /// // Even though this looks like a valid label, there is no delimiting
    /// // byte, so it cannot be parsed successfully.
    /// assert_eq!(
    ///     LabelBuf::split_str(b"example"),
    ///     Err(LabelSplitError::ShortInput));
    ///
    /// // Any "uncommon" ASCII character, non-printable ASCII character, or
    /// // non-ASCII character can serve as the delimiting byte.
    /// assert_eq!(
    ///     LabelBuf::split_str(b"com:22"),
    ///     Ok((label_buf!(b"com"), &b":22"[..])));
    /// ```
    pub fn split_str(mut s: &[u8]) -> Result<(Self, &[u8]), LabelSplitError> {
        // The buffer we'll fill into.
        let mut this = Self::new();

        // Parse character by character.
        loop {
            let full = s;
            let &[b, ref rest @ ..] = s else {
                return Err(LabelSplitError::ShortInput);
            };
            s = rest;
            if Label::UNESCAPED_ZONEFILE_CHARS.contains(&b) {
                // A regular label character.
                this.push(b).map_err(|_| LabelSplitError::Overlong)?;
            } else if b == b'\\' {
                // An escape character.
                let &[b, ref rest @ ..] = s else {
                    return Err(LabelSplitError::ShortInput);
                };
                let value = if b.is_ascii_digit() {
                    let (digits, rest) = s
                        .split_at_checked(3)
                        .ok_or(LabelSplitError::ShortInput)?;
                    s = rest;
                    let digits = core::str::from_utf8(digits)
                        .map_err(|_| LabelSplitError::InvalidEscape)?;
                    digits
                        .parse()
                        .map_err(|_| LabelSplitError::InvalidEscape)?
                } else if b.is_ascii_graphic() {
                    s = rest;
                    b
                } else {
                    return Err(LabelSplitError::InvalidEscape);
                };
                this.push(value).map_err(|_| LabelSplitError::Overlong)?;
            } else {
                // An invalid character has been reached; the label has ended.
                break Ok((this, full));
            };
        }
    }
}

impl FromStr for LabelBuf {
    type Err = LabelParseError;

    /// Parse a printed label.
    ///
    /// See [`LabelBuf::parse_str()`].
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse_str(s.as_bytes())
    }
}

//--- Serialize, Deserialize

#[cfg(feature = "serde")]
impl serde::Serialize for LabelBuf {
    /// See [`Label::serialize()`].
    ///
    /// [`Label::serialize()`]: struct.Label.html#method.serialize
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        (**self).serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl<'a> serde::Deserialize<'a> for LabelBuf {
    /// Deserialize a label.
    ///
    /// See [`Label::serialize()`] for a discussion of the format.
    ///
    /// [`Label::serialize()`]: struct.Label.html#method.serialize
    ///
    /// ```
    /// # use serde_test::{Configure, Token, assert_tokens};
    /// # use domain::new::base::name::label_buf;
    /// #
    /// assert_tokens(&label_buf!(b"example\x7Fabc").readable(), &[
    ///     Token::NewtypeStruct { name: "Label" },
    ///     Token::String("example\\127abc"),
    /// ]);
    /// assert_tokens(&label_buf!(b"example\x7Fabc").compact(), &[
    ///     Token::NewtypeStruct { name: "Label" },
    ///     Token::Bytes(b"example\x7Fabc"),
    /// ]);
    /// ```
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        if deserializer.is_human_readable() {
            struct V;

            impl serde::de::Visitor<'_> for V {
                type Value = LabelBuf;

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("a label, in the DNS zonefile format")
                }

                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    v.parse().map_err(|err| E::custom(err))
                }
            }

            struct NV;

            impl<'a> serde::de::Visitor<'a> for NV {
                type Value = LabelBuf;

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("a DNS label")
                }

                fn visit_newtype_struct<D>(
                    self,
                    deserializer: D,
                ) -> Result<Self::Value, D::Error>
                where
                    D: serde::Deserializer<'a>,
                {
                    deserializer.deserialize_str(V)
                }
            }

            deserializer.deserialize_newtype_struct("Label", NV)
        } else {
            struct V;

            impl serde::de::Visitor<'_> for V {
                type Value = LabelBuf;

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("the contents of a DNS label")
                }

                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    let mut buf = LabelBuf::new();
                    buf.append(v).map_err(|_| {
                        E::custom(
                            "misformatted label for the DNS wire format",
                        )
                    })?;
                    Ok(buf)
                }
            }

            struct NV;

            impl<'a> serde::de::Visitor<'a> for NV {
                type Value = LabelBuf;

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("a DNS label")
                }

                fn visit_newtype_struct<D>(
                    self,
                    deserializer: D,
                ) -> Result<Self::Value, D::Error>
                where
                    D: serde::Deserializer<'a>,
                {
                    deserializer.deserialize_bytes(V)
                }
            }

            deserializer.deserialize_newtype_struct("Label", NV)
        }
    }
}

#[cfg(all(feature = "serde", feature = "alloc"))]
impl<'a> serde::Deserialize<'a> for alloc::boxed::Box<Label> {
    /// Deserialize a label and allocate it on the heap.
    ///
    /// See [`LabelBuf::deserialize()`].
    ///
    /// [`LabelBuf::deserialize()`]: struct.LabelBuf.html#method.deserialize
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        LabelBuf::deserialize(deserializer)
            .map(|this| this.unsized_copy_into())
    }
}

//----------- LabelIter ------------------------------------------------------

/// An iterator over encoded [`Label`]s.
#[derive(Clone)]
pub struct LabelIter<'a> {
    /// The buffer being read from.
    ///
    /// It is assumed to contain valid encoded labels.
    bytes: &'a [u8],
}

//--- Construction

impl<'a> LabelIter<'a> {
    /// Construct a new [`LabelIter`].
    ///
    /// # Safety
    ///
    /// The byte sequence must contain a sequence of valid encoded labels.
    pub const unsafe fn new_unchecked(bytes: &'a [u8]) -> Self {
        Self { bytes }
    }
}

//--- Inspection

impl<'a> LabelIter<'a> {
    /// The remaining labels.
    pub const fn remaining(&self) -> &'a [u8] {
        self.bytes
    }

    /// Whether the iterator is empty.
    pub const fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }
}

//--- Iteration

impl<'a> Iterator for LabelIter<'a> {
    type Item = &'a Label;

    fn next(&mut self) -> Option<Self::Item> {
        if self.bytes.is_empty() {
            return None;
        }

        // SAFETY: 'bytes' is assumed to only contain valid labels.
        let (head, tail) =
            unsafe { <&Label>::split_bytes(self.bytes).unwrap_unchecked() };
        self.bytes = tail;
        Some(head)
    }
}

impl FusedIterator for LabelIter<'_> {}

//--- Formatting

impl fmt::Debug for LabelIter<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        struct Labels<'a>(&'a LabelIter<'a>);

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

        f.debug_tuple("LabelIter").field(&Labels(self)).finish()
    }
}

//============ Macros ========================================================

/// Construct a hard-coded [`Label`] at compile time.
///
/// This is a convenience function for writing example-based tests; it
/// provides a simple, convenient way to build [`Label`]s with hard-coded
/// values. It takes a byte slice and returns a label with those contents.
///
/// ```
/// # use domain::new::base::name::{Label, label};
/// #
/// let foo: &'static Label = label!(b"example");
/// assert_eq!(foo.as_wire(), b"\x07example");
///
/// // Escapes in the label are not processed.
/// let foo: &'static Label = label!(b"ex\x0Amp\\e");
/// assert_eq!(foo.as_wire(), b"\x07ex\x0Amp\\e");
///
/// // You can pass non-UTF-8 content.
/// let foo: &'static Label = label!(b"ex\xFFmple");
/// assert_eq!(foo.as_wire(), b"\x07ex\xFFmple");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! new_base_name_label {
    ($value:literal) => {
        const {
            const BUFFER: &$crate::new::base::name::LabelBuf =
                &$crate::new::base::name::label_buf!($value);
            BUFFER.as_label()
        }
    };
}
pub use crate::new_base_name_label as label;

/// Construct a hard-coded [`LabelBuf`] at compile time.
///
/// This is a convenience function for writing example-based tests; it
/// provides a simple, convenient way to build [`LabelBuf`]s with hard-coded
/// values. It takes a byte slice and returns a label with those contents.
///
/// ```
/// # use domain::new::base::name::{LabelBuf, label_buf};
/// #
/// let foo: LabelBuf = label_buf!(b"example");
/// assert_eq!(foo.as_wire(), b"\x07example");
///
/// // Escapes in the label are not processed.
/// let foo: LabelBuf = label_buf!(b"ex\x0Amp\\e");
/// assert_eq!(foo.as_wire(), b"\x07ex\x0Amp\\e");
///
/// // You can pass non-UTF-8 content.
/// let foo: LabelBuf = label_buf!(b"ex\xFFmple");
/// assert_eq!(foo.as_wire(), b"\x07ex\xFFmple");
/// ```
#[doc(hidden)]
#[macro_export]
macro_rules! new_base_name_label_buf {
    ($value:literal) => {
        const {
            let mut buffer = $crate::new::base::name::LabelBuf::new();
            assert!(buffer.append($value).is_ok());
            buffer
        }
    };
}
pub use crate::new_base_name_label_buf as label_buf;

//============ Errors ========================================================

//------------ LabelParseError -----------------------------------------------

/// An error in parsing a [`Label`] from a string.
///
/// This can be returned by [`LabelBuf::from_str()`]. It is not used when
/// parsing labels from the zonefile format, which uses a different mechanism.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelParseError {
    /// The label was too large.
    ///
    /// Valid labels are between 1 and 63 bytes, inclusive.
    Overlong,

    /// An invalid character was used.
    ///
    /// Only alphanumeric characters and hyphens are allowed in labels. This
    /// prevents the encoding of perfectly valid labels containing non-ASCII
    /// bytes, but they're fairly rare anyway.
    InvalidChar,

    /// A partial escape was used.
    ///
    /// An escape must be `\\DDD`, where `DDD` are 3 ASCII decimal digits
    /// representing an unsigned 8-bit integer; or `\\X`, where `X` is a
    /// graphical, non-digit ASCII character.
    PartialEscape,

    /// An invalid escape was used.
    ///
    /// An escape must be `\\DDD`, where `DDD` are 3 ASCII decimal digits
    /// representing an unsigned 8-bit integer; or `\\X`, where `X` is a
    /// graphical, non-digit ASCII character.
    InvalidEscape,
}

impl core::error::Error for LabelParseError {}

impl fmt::Display for LabelParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Overlong => "the label was too large",
            Self::InvalidChar => "the label contained an invalid character",
            Self::PartialEscape => "the label contained an incomplete escape",
            Self::InvalidEscape => "the label contained an invalid escape",
        })
    }
}

//------------ LabelSplitError -----------------------------------------------

/// An error in parsing a [`Label`] from a larger string.
///
/// This can be returned by [`LabelBuf::split_str()`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LabelSplitError {
    /// The label was too large.
    ///
    /// Valid labels are between 1 and 63 bytes, inclusive.
    Overlong,

    /// An invalid character was used.
    ///
    /// Only alphanumeric characters and hyphens are allowed in labels. This
    /// prevents the encoding of perfectly valid labels containing non-ASCII
    /// bytes, but they're fairly rare anyway.
    InvalidChar,

    /// An invalid escape was used.
    ///
    /// An escape must be `\\DDD`, where `DDD` are 3 ASCII decimal digits
    /// representing an unsigned 8-bit integer; or `\\X`, where `X` is a
    /// graphical, non-digit ASCII character.
    InvalidEscape,

    /// The input was too short to parse the label.
    ///
    /// The input did not sufficiently delimit the label. More input (if any)
    /// needs to be collected to correctly parse the entire label.
    ShortInput,
}

impl core::error::Error for LabelSplitError {}

impl fmt::Display for LabelSplitError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Overlong => "the label was too large",
            Self::InvalidChar => "the label contained an invalid character",
            Self::InvalidEscape => "the label contained an invalid escape",
            Self::ShortInput => "the input was too short to parse the label",
        })
    }
}

//============ Tests =========================================================

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

    use crate::new::base::wire::{ParseBytes, ParseError, SplitBytes};

    #[test]
    fn parsing() {
        let good = [
            b"\x00abc" as &[u8],
            b"\x07example\x03org\x00",
            b"\x07f\x00\x00&\x8Fbar-foo",
            b"\x3Fthis is a label of the longest valid length and it's surprising(ly big)",
        ];

        for input in good {
            // Try parsing input with some bytes following it.
            let expected_len = input[0] as usize + 1;
            assert_eq!(<&Label>::parse_bytes(input), Err(ParseError));
            let (actual, rest) = <&Label>::split_bytes(input).unwrap();
            assert_eq!(actual.as_wire().len(), expected_len);
            assert_eq!(actual.as_wire().as_ptr(), input.as_ptr());
            assert_eq!(actual.as_wire().len() + rest.len(), input.len());
            assert_eq!(
                rest.as_ptr(),
                input.as_ptr().wrapping_add(expected_len)
            );

            // Try parsing input that _only_ contains a label.
            let min_input = &input[..expected_len];
            let (actual, rest) = <&Label>::split_bytes(min_input).unwrap();
            assert_eq!(actual.as_wire().as_ptr(), min_input.as_ptr());
            assert_eq!(actual.as_wire().len(), min_input.len());
            assert_eq!(rest, &[] as &[u8]);
            let actual = <&Label>::parse_bytes(min_input).unwrap();
            assert_eq!(actual.as_wire().as_ptr(), min_input.as_ptr());
            assert_eq!(actual.as_wire().len(), min_input.len());

            // Try parsing input that's a byte too short.
            let short_input = &input[..expected_len - 1];
            assert_eq!(<&Label>::split_bytes(short_input), Err(ParseError));
            assert_eq!(<&Label>::parse_bytes(short_input), Err(ParseError));
        }

        let bad = [
            b"\x40this is not a valid label but it would be if 64 was a valid label length" as &[u8],
        ];

        for input in bad {
            assert_eq!(<&Label>::split_bytes(input), Err(ParseError));
            assert_eq!(<&Label>::parse_bytes(input), Err(ParseError));
        }
    }
}