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
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
//! Uncompressed, relative domain names.
//!
//! This is a private module. Its public types are re-exported by the parent.

use super::super::wire::ParseError;
use super::builder::{DnameBuilder, FromStrError, PushError};
use super::chain::{Chain, LongChainError};
use super::dname::Dname;
use super::label::{Label, LabelTypeError, SplitLabelError};
use super::traits::{ToLabelIter, ToRelativeDname};
#[cfg(feature = "bytes")]
use bytes::Bytes;
use core::cmp::Ordering;
use core::ops::{Bound, RangeBounds};
use core::str::FromStr;
use core::{cmp, fmt, hash};
use octseq::builder::{
    EmptyBuilder, FreezeBuilder, FromBuilder, IntoBuilder, Truncate,
};
use octseq::octets::{Octets, OctetsFrom};
#[cfg(feature = "serde")]
use octseq::serde::{DeserializeOctets, SerializeOctets};
#[cfg(feature = "std")]
use std::vec::Vec;

//------------ RelativeDname -------------------------------------------------

/// An uncompressed, relative domain name.
///
/// A relative domain name is one that doesn’t end with the root label. As the
/// name suggests, it is relative to some other domain name. This type wraps
/// a octets sequence containing such a relative name similarly to the way
/// [`Dname`] wraps an absolute one. In fact, it behaves very similarly to
/// [`Dname`] taking into account differences when slicing and dicing names.
///
/// `RelativeDname` guarantees that the name is at most 254 bytes long. As the
/// length limit for a domain name is actually 255 bytes, this means that you
/// can always safely turn a `RelativeDname` into a `Dname` by adding the root
/// label (which is exactly one byte long).
///
/// [`Bytes`]: ../../../bytes/struct.Bytes.html
/// [`Dname`]: struct.Dname.html
#[derive(Clone)]
pub struct RelativeDname<Octs: ?Sized>(Octs);

/// # Creating Values
///
impl<Octs> RelativeDname<Octs> {
    /// Creates a relative domain name from octets without checking.
    ///
    /// Since the content of the octets sequence can be anything, really,
    /// this is an unsafe function.
    ///
    /// # Safety
    ///
    /// The octets sequence passed via `octets` must contain a correctly
    /// encoded relative domain name. It must be at most 254 octets long.
    /// There must be no root labels anywhere in the name.
    pub const unsafe fn from_octets_unchecked(octets: Octs) -> Self {
        RelativeDname(octets)
    }

    /// Creates a relative domain name from an octets sequence.
    ///
    /// This checks that `octets` contains a properly encoded relative domain
    /// name and fails if it doesn’t.
    pub fn from_octets(octets: Octs) -> Result<Self, RelativeDnameError>
    where
        Octs: AsRef<[u8]>,
    {
        RelativeDname::check_slice(octets.as_ref())?;
        Ok(unsafe { RelativeDname::from_octets_unchecked(octets) })
    }

    /// Creates an empty relative domain name.
    #[must_use]
    pub fn empty() -> Self
    where
        Octs: From<&'static [u8]>,
    {
        unsafe { RelativeDname::from_octets_unchecked(b"".as_ref().into()) }
    }

    /// Creates a relative domain name representing the wildcard label.
    ///
    /// The wildcard label is intended to match any label. There are special
    /// rules for names with wildcard labels. Note that the comparison traits
    /// implemented for domain names do *not* consider wildcards and treat
    /// them as regular labels.
    #[must_use]
    pub fn wildcard() -> Self
    where
        Octs: From<&'static [u8]>,
    {
        unsafe {
            RelativeDname::from_octets_unchecked(b"\x01*".as_ref().into())
        }
    }

    /// Creates a domain name from a sequence of characters.
    ///
    /// The sequence must result in a domain name in representation format.
    /// That is, its labels should be separated by dots.
    /// Actual dots, white space and backslashes should be escaped by a
    /// preceeding backslash, and any byte value that is not a printable
    /// ASCII character should be encoded by a backslash followed by its
    /// three digit decimal value.
    ///
    /// If Internationalized Domain Names are to be used, the labels already
    /// need to be in punycode-encoded form.
    pub fn from_chars<C>(chars: C) -> Result<Self, RelativeFromStrError>
    where
        Octs: FromBuilder,
        <Octs as FromBuilder>::Builder: EmptyBuilder
            + FreezeBuilder<Octets = Octs>
            + AsRef<[u8]>
            + AsMut<[u8]>,
        C: IntoIterator<Item = char>,
    {
        let mut builder = DnameBuilder::<Octs::Builder>::new();
        builder.append_chars(chars)?;
        if builder.in_label() || builder.is_empty() {
            Ok(builder.finish())
        } else {
            Err(RelativeFromStrError::AbsoluteName)
        }
    }
}

impl RelativeDname<[u8]> {
    /// Creates a domain name from an octet slice without checking.
    ///
    /// # Safety
    ///
    /// The same rules as for `from_octets_unchecked` apply.
    pub(super) unsafe fn from_slice_unchecked(slice: &[u8]) -> &Self {
        &*(slice as *const [u8] as *const RelativeDname<[u8]>)
    }

    /// Creates a relative domain name from an octet slice.
    ///
    /// Note that the input must be in wire format, as shown below.
    ///
    /// # Example
    ///
    /// ```
    /// use domain::base::name::RelativeDname;
    /// RelativeDname::from_slice(b"\x0c_submissions\x04_tcp");
    /// ```
    pub fn from_slice(slice: &[u8]) -> Result<&Self, RelativeDnameError> {
        Self::check_slice(slice)?;
        Ok(unsafe { Self::from_slice_unchecked(slice) })
    }

    /// Returns an empty relative name atop a unsized slice.
    #[must_use]
    pub fn empty_slice() -> &'static Self {
        unsafe { Self::from_slice_unchecked(b"") }
    }

    #[must_use]
    pub fn wildcard_slice() -> &'static Self {
        unsafe { Self::from_slice_unchecked(b"\x01*") }
    }

    /// Checks whether an octet slice contains a correctly encoded name.
    pub(super) fn check_slice(
        mut slice: &[u8],
    ) -> Result<(), RelativeDnameError> {
        if slice.len() > 254 {
            return Err(RelativeDnameError::LongName);
        }
        while !slice.is_empty() {
            let (label, tail) = Label::split_from(slice)?;
            if label.is_root() {
                return Err(RelativeDnameError::AbsoluteName);
            }
            slice = tail;
        }
        Ok(())
    }
}

impl RelativeDname<&'static [u8]> {
    /// Creates an empty relative name atop a slice reference.
    #[must_use]
    pub fn empty_ref() -> Self {
        Self::empty()
    }

    /// Creates a wildcard relative name atop a slice reference.
    #[must_use]
    pub fn wildcard_ref() -> Self {
        Self::wildcard()
    }
}

#[cfg(feature = "std")]
impl RelativeDname<Vec<u8>> {
    /// Creates an empty relative name atop a `Vec<u8>`.
    #[must_use]
    pub fn empty_vec() -> Self {
        Self::empty()
    }

    /// Creates a wildcard relative name atop a `Vec<u8>`.
    #[must_use]
    pub fn wildcard_vec() -> Self {
        Self::wildcard()
    }

    /// Parses a string into a relative name atop a `Vec<u8>`.
    pub fn vec_from_str(s: &str) -> Result<Self, RelativeFromStrError> {
        FromStr::from_str(s)
    }
}

#[cfg(feature = "bytes")]
impl RelativeDname<Bytes> {
    /// Creates an empty relative name atop a bytes value.
    pub fn empty_bytes() -> Self {
        Self::empty()
    }

    /// Creates a wildcard relative name atop a bytes value.
    pub fn wildcard_bytes() -> Self {
        Self::wildcard()
    }

    /// Parses a string into a relative name atop a `Bytes`.
    pub fn bytes_from_str(s: &str) -> Result<Self, RelativeFromStrError> {
        FromStr::from_str(s)
    }
}

/// # Conversions
///
impl<Octs: ?Sized> RelativeDname<Octs> {
    /// Returns a reference to the underlying octets.
    pub fn as_octets(&self) -> &Octs {
        &self.0
    }

    /// Converts the name into the underlying octets.
    pub fn into_octets(self) -> Octs
    where
        Octs: Sized,
    {
        self.0
    }

    /// Returns a domain name using a reference to the octets.
    pub fn for_ref(&self) -> RelativeDname<&Octs> {
        unsafe { RelativeDname::from_octets_unchecked(&self.0) }
    }

    /// Returns a reference to an octets slice with the content of the name.
    pub fn as_slice(&self) -> &[u8]
    where
        Octs: AsRef<[u8]>,
    {
        self.0.as_ref()
    }

    /// Returns a domain name for the octets slice of the content.
    pub fn for_slice(&self) -> &RelativeDname<[u8]>
    where
        Octs: AsRef<[u8]>,
    {
        unsafe { RelativeDname::from_slice_unchecked(self.0.as_ref()) }
    }

    /// Converts the name into its canonical form.
    pub fn make_canonical(&mut self)
    where
        Octs: AsMut<[u8]>,
    {
        Label::make_slice_canonical(self.0.as_mut());
    }
}

impl<Octs> RelativeDname<Octs> {
    /// Converts the name into a domain name builder for appending data.
    ///
    /// This method is only available for octets sequences that have an
    /// associated octets builder such as `Vec<u8>` or `Bytes`.
    pub fn into_builder(self) -> DnameBuilder<<Octs as IntoBuilder>::Builder>
    where
        Octs: IntoBuilder,
    {
        unsafe { DnameBuilder::from_builder_unchecked(self.0.into_builder()) }
    }

    /// Converts the name into an absolute name by appending the root label.
    ///
    /// This manipulates the name itself and thus is only available for
    /// octets sequences that can be converted into an octets builder and back
    /// such as `Vec<u8>`.
    ///
    /// [`chain_root`]: #method.chain_root
    pub fn into_absolute(self) -> Result<Dname<Octs>, PushError>
    where
        Octs: IntoBuilder,
        <Octs as IntoBuilder>::Builder:
            FreezeBuilder<Octets = Octs> + AsRef<[u8]> + AsMut<[u8]>,
    {
        self.into_builder().into_dname()
    }

    /// Chains another name to the end of this name.
    ///
    /// Depending on whether `other` is an absolute or relative domain name,
    /// the resulting name will behave like an absolute or relative name.
    ///
    /// The method will fail if the combined length of the two names is
    /// greater than the size limit of 255. Note that in this case you will
    /// loose both `self` and `other`, so it might be worthwhile to check
    /// first.
    pub fn chain<N: ToLabelIter>(
        self,
        other: N,
    ) -> Result<Chain<Self, N>, LongChainError>
    where
        Octs: AsRef<[u8]>,
    {
        Chain::new(self, other)
    }

    /// Creates an absolute name by chaining the root label to it.
    pub fn chain_root(self) -> Chain<Self, Dname<&'static [u8]>>
    where
        Octs: AsRef<[u8]>,
    {
        self.chain(Dname::root()).unwrap()
    }
}

/// # Properties
///
impl<Octs: AsRef<[u8]> + ?Sized> RelativeDname<Octs> {
    /// Returns the length of the name.
    pub fn len(&self) -> usize {
        self.0.as_ref().len()
    }

    /// Returns whether the name is empty.
    pub fn is_empty(&self) -> bool {
        self.0.as_ref().is_empty()
    }
}

/// # Working with Labels
///
impl<Octs: AsRef<[u8]> + ?Sized> RelativeDname<Octs> {
    /// Returns an iterator over the labels of the domain name.
    pub fn iter(&self) -> DnameIter {
        DnameIter::new(self.0.as_ref())
    }

    /// Returns the number of labels in the name.
    pub fn label_count(&self) -> usize {
        self.iter().count()
    }

    /// Returns a reference to the first label if the name isn’t empty.
    pub fn first(&self) -> Option<&Label> {
        self.iter().next()
    }

    /// Returns a reference to the last label if the name isn’t empty.
    pub fn last(&self) -> Option<&Label> {
        self.iter().next_back()
    }

    /// Returns the number of dots in the string representation of the name.
    ///
    /// Specifically, returns a value equal to the number of labels minus one,
    /// except for an empty name where it returns a zero, also.
    pub fn ndots(&self) -> usize {
        if self.0.as_ref().is_empty() {
            0
        } else {
            self.label_count() - 1
        }
    }

    /// Determines whether `base` is a prefix of `self`.
    pub fn starts_with<N: ToLabelIter>(&self, base: &N) -> bool {
        <Self as ToLabelIter>::starts_with(self, base)
    }

    /// Determines whether `base` is a suffix of `self`.
    pub fn ends_with<N: ToLabelIter>(&self, base: &N) -> bool {
        <Self as ToLabelIter>::ends_with(self, base)
    }

    /// Returns whether an index points to the first octet of a label.
    pub fn is_label_start(&self, mut index: usize) -> bool {
        if index == 0 {
            return true;
        }
        let mut tmp = self.as_slice();
        while !tmp.is_empty() {
            let (label, tail) = Label::split_from(tmp).unwrap();
            let len = label.len() + 1;
            match index.cmp(&len) {
                Ordering::Less => return false,
                Ordering::Equal => return true,
                _ => {}
            }
            index -= len;
            tmp = tail;
        }
        false
    }

    /// Like `is_label_start` but panics if it isn’t.
    fn check_index(&self, index: usize) {
        if !self.is_label_start(index) {
            panic!("index not at start of a label");
        }
    }

    fn check_bounds(&self, bounds: &impl RangeBounds<usize>) {
        match bounds.start_bound().cloned() {
            Bound::Included(idx) => self.check_index(idx),
            Bound::Excluded(_) => {
                panic!("excluded lower bounds not supported");
            }
            Bound::Unbounded => {}
        }
        match bounds.end_bound().cloned() {
            Bound::Included(idx) => self
                .check_index(idx.checked_add(1).expect("end bound too big")),
            Bound::Excluded(idx) => self.check_index(idx),
            Bound::Unbounded => {}
        }
    }

    /// Returns a part of the name indicated by start and end positions.
    ///
    /// The returned name will start at position `begin` and end right before
    /// position `end`. Both positions are given as indexes into the
    /// underlying octets sequence and must point to the begining of a label.
    ///
    /// The method returns a reference to an unsized relative domain name and
    /// is thus best suited for temporary referencing. If you want to keep the
    /// part of the name around, [`range`] is likely a better choice.
    ///
    /// # Panics
    ///
    /// The method panics if either position is not the beginning of a label
    /// or is out of bounds.
    ///
    /// [`range`]: #method.range
    pub fn slice(
        &self,
        range: impl RangeBounds<usize>,
    ) -> &RelativeDname<[u8]> {
        self.check_bounds(&range);
        unsafe {
            RelativeDname::from_slice_unchecked(self.0.as_ref().range(range))
        }
    }

    /// Returns a part of the name indicated by start and end positions.
    ///
    /// The returned name will start at position `begin` and end right before
    /// position `end`. Both positions are given as indexes into the
    /// underlying octets sequence and must point to the begining of a label.
    ///
    /// # Panics
    ///
    /// The method panics if either position is not the beginning of a label
    /// or is out of bounds.
    pub fn range(
        &self,
        range: impl RangeBounds<usize>,
    ) -> RelativeDname<<Octs as Octets>::Range<'_>>
    where
        Octs: Octets,
    {
        self.check_bounds(&range);
        unsafe { RelativeDname::from_octets_unchecked(self.0.range(range)) }
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> RelativeDname<Octs> {
    /// Splits the name into two at the given position.
    ///
    /// Returns a pair of the left and right part of the split name.
    ///
    /// # Panics
    ///
    /// The method panics if the position is not the beginning of a label
    /// or is beyond the end of the name.
    pub fn split(
        &self,
        mid: usize,
    ) -> (
        RelativeDname<Octs::Range<'_>>,
        RelativeDname<Octs::Range<'_>>,
    )
    where
        Octs: Octets,
    {
        self.check_index(mid);
        unsafe {
            (
                RelativeDname::from_octets_unchecked(self.0.range(..mid)),
                RelativeDname::from_octets_unchecked(self.0.range(mid..)),
            )
        }
    }

    /// Truncates the name to the given length.
    ///
    /// # Panics
    ///
    /// The method panics if the position is not the beginning of a label
    /// or is beyond the end of the name.
    pub fn truncate(&mut self, len: usize)
    where
        Octs: Truncate,
    {
        self.check_index(len);
        self.0.truncate(len);
    }

    /// Splits off the first label.
    ///
    /// If there is at least one label in the name, returns the first label
    /// as a relative domain name with exactly one label and makes `self`
    /// contain the domain name starting after that first label. If the name
    /// is empty, returns `None`.
    pub fn split_first(
        &self,
    ) -> Option<(&Label, RelativeDname<Octs::Range<'_>>)>
    where
        Octs: Octets,
    {
        if self.is_empty() {
            return None;
        }
        let label = self.iter().next()?;
        Some((label, self.split(label.len() + 1).1))
    }

    /// Returns the parent name.
    ///
    /// Returns `None` if the name was empty.
    pub fn parent(&self) -> Option<RelativeDname<Octs::Range<'_>>>
    where
        Octs: Octets,
    {
        self.split_first().map(|(_, parent)| parent)
    }

    /// Strips the suffix `base` from the domain name.
    ///
    /// This will fail if `base` isn’t actually a suffix, i.e., if
    /// [`ends_with`] doesn’t return `true`.
    ///
    /// [`ends_with`]: #method.ends_with
    pub fn strip_suffix<N: ToRelativeDname>(
        &mut self,
        base: &N,
    ) -> Result<(), StripSuffixError>
    where
        Octs: Truncate,
    {
        if self.ends_with(base) {
            let idx = self.0.as_ref().len() - usize::from(base.compose_len());
            self.0.truncate(idx);
            Ok(())
        } else {
            Err(StripSuffixError)
        }
    }
}

//--- AsRef

impl<Octs> AsRef<Octs> for RelativeDname<Octs> {
    fn as_ref(&self) -> &Octs {
        &self.0
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> AsRef<[u8]> for RelativeDname<Octs> {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

//--- OctetsFrom

impl<Octs, SrcOcts> OctetsFrom<RelativeDname<SrcOcts>> for RelativeDname<Octs>
where
    Octs: OctetsFrom<SrcOcts>,
{
    type Error = Octs::Error;

    fn try_octets_from(
        source: RelativeDname<SrcOcts>,
    ) -> Result<Self, Self::Error> {
        Octs::try_octets_from(source.0)
            .map(|octets| unsafe { Self::from_octets_unchecked(octets) })
    }
}

//--- FromStr

impl<Octs> FromStr for RelativeDname<Octs>
where
    Octs: FromBuilder,
    <Octs as FromBuilder>::Builder: EmptyBuilder
        + FreezeBuilder<Octets = Octs>
        + AsRef<[u8]>
        + AsMut<[u8]>,
{
    type Err = RelativeFromStrError;

    /// Parses a string into an absolute domain name.
    ///
    /// The name needs to be formatted in representation format, i.e., as a
    /// sequence of labels separated by dots. If Internationalized Domain
    /// Name (IDN) labels are to be used, these need to be given in punycode
    /// encoded form.
    ///
    /// This implementation will error if the name ends in a dot since that
    /// indicates an absolute name.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::from_chars(s.chars())
    }
}

//--- ToLabelIter and ToRelativeDname

impl<Octs> ToLabelIter for RelativeDname<Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
{
    type LabelIter<'a> = DnameIter<'a> where Octs: 'a;

    fn iter_labels(&self) -> Self::LabelIter<'_> {
        self.iter()
    }

    fn compose_len(&self) -> u16 {
        u16::try_from(self.0.as_ref().len()).expect("long domain name")
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> ToRelativeDname for RelativeDname<Octs> {
    fn as_flat_slice(&self) -> Option<&[u8]> {
        Some(self.0.as_ref())
    }

    fn is_empty(&self) -> bool {
        self.0.as_ref().is_empty()
    }
}

//--- IntoIterator

impl<'a, Octs> IntoIterator for &'a RelativeDname<Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
{
    type Item = &'a Label;
    type IntoIter = DnameIter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

//--- PartialEq and Eq

impl<Octs, N> PartialEq<N> for RelativeDname<Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
    N: ToRelativeDname + ?Sized,
{
    fn eq(&self, other: &N) -> bool {
        self.name_eq(other)
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> Eq for RelativeDname<Octs> {}

//--- PartialOrd and Ord

impl<Octs, N> PartialOrd<N> for RelativeDname<Octs>
where
    Octs: AsRef<[u8]> + ?Sized,
    N: ToRelativeDname + ?Sized,
{
    fn partial_cmp(&self, other: &N) -> Option<cmp::Ordering> {
        Some(self.name_cmp(other))
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> Ord for RelativeDname<Octs> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.name_cmp(other)
    }
}

//--- Hash

impl<Octs: AsRef<[u8]> + ?Sized> hash::Hash for RelativeDname<Octs> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        for item in self.iter() {
            item.hash(state)
        }
    }
}

//--- Display and Debug

impl<Octs: AsRef<[u8]> + ?Sized> fmt::Display for RelativeDname<Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut iter = self.iter();
        match iter.next() {
            Some(label) => label.fmt(f)?,
            None => return Ok(()),
        }
        for label in iter {
            f.write_str(".")?;
            label.fmt(f)?;
        }
        Ok(())
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> fmt::Debug for RelativeDname<Octs> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "RelativeDname({})", self)
    }
}

//--- Serialize and Deserialize

#[cfg(feature = "serde")]
impl<Octs> serde::Serialize for RelativeDname<Octs>
where
    Octs: AsRef<[u8]> + SerializeOctets + ?Sized,
{
    fn serialize<S: serde::Serializer>(
        &self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        if serializer.is_human_readable() {
            serializer.serialize_newtype_struct(
                "RelativeDname",
                &format_args!("{}", self),
            )
        } else {
            serializer.serialize_newtype_struct(
                "RelativeDname",
                &self.0.as_serialized_octets(),
            )
        }
    }
}

#[cfg(feature = "serde")]
impl<'de, Octs> serde::Deserialize<'de> for RelativeDname<Octs>
where
    Octs: FromBuilder + DeserializeOctets<'de>,
    <Octs as FromBuilder>::Builder: FreezeBuilder<Octets = Octs>
        + EmptyBuilder
        + AsRef<[u8]>
        + AsMut<[u8]>,
{
    fn deserialize<D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        use core::marker::PhantomData;

        struct InnerVisitor<'de, T: DeserializeOctets<'de>>(T::Visitor);

        impl<'de, Octs> serde::de::Visitor<'de> for InnerVisitor<'de, Octs>
        where
            Octs: FromBuilder + DeserializeOctets<'de>,
            <Octs as FromBuilder>::Builder: FreezeBuilder<Octets = Octs>
                + EmptyBuilder
                + AsRef<[u8]>
                + AsMut<[u8]>,
        {
            type Value = RelativeDname<Octs>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a relative domain name")
            }

            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> Result<Self::Value, E> {
                let mut builder = DnameBuilder::<Octs::Builder>::new();
                builder.append_chars(v.chars()).map_err(E::custom)?;
                Ok(builder.finish())
            }

            fn visit_borrowed_bytes<E: serde::de::Error>(
                self,
                value: &'de [u8],
            ) -> Result<Self::Value, E> {
                self.0.visit_borrowed_bytes(value).and_then(|octets| {
                    RelativeDname::from_octets(octets).map_err(E::custom)
                })
            }

            #[cfg(feature = "std")]
            fn visit_byte_buf<E: serde::de::Error>(
                self,
                value: std::vec::Vec<u8>,
            ) -> Result<Self::Value, E> {
                self.0.visit_byte_buf(value).and_then(|octets| {
                    RelativeDname::from_octets(octets).map_err(E::custom)
                })
            }
        }

        struct NewtypeVisitor<T>(PhantomData<T>);

        impl<'de, Octs> serde::de::Visitor<'de> for NewtypeVisitor<Octs>
        where
            Octs: FromBuilder + DeserializeOctets<'de>,
            <Octs as FromBuilder>::Builder: FreezeBuilder<Octets = Octs>
                + EmptyBuilder
                + AsRef<[u8]>
                + AsMut<[u8]>,
        {
            type Value = RelativeDname<Octs>;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a relative domain name")
            }

            fn visit_newtype_struct<D: serde::Deserializer<'de>>(
                self,
                deserializer: D,
            ) -> Result<Self::Value, D::Error> {
                if deserializer.is_human_readable() {
                    deserializer
                        .deserialize_str(InnerVisitor(Octs::visitor()))
                } else {
                    Octs::deserialize_with_visitor(
                        deserializer,
                        InnerVisitor(Octs::visitor()),
                    )
                }
            }
        }

        deserializer.deserialize_newtype_struct(
            "RelativeDname",
            NewtypeVisitor(PhantomData),
        )
    }
}

//------------ DnameIter -----------------------------------------------------

/// An iterator over the labels in an uncompressed name.
#[derive(Clone, Debug)]
pub struct DnameIter<'a> {
    slice: &'a [u8],
}

impl<'a> DnameIter<'a> {
    pub(super) fn new(slice: &'a [u8]) -> Self {
        DnameIter { slice }
    }
}

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

    fn next(&mut self) -> Option<Self::Item> {
        let (label, tail) = match Label::split_from(self.slice) {
            Ok(res) => res,
            Err(_) => return None,
        };
        self.slice = tail;
        Some(label)
    }
}

impl<'a> DoubleEndedIterator for DnameIter<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        if self.slice.is_empty() {
            return None;
        }
        let mut tmp = self.slice;
        loop {
            let (label, tail) = Label::split_from(tmp).unwrap();
            if tail.is_empty() {
                let end = self.slice.len() - (label.len() + 1);
                self.slice = &self.slice[..end];
                return Some(label);
            } else {
                tmp = tail
            }
        }
    }
}

//============ Error Types ===================================================

//------------ RelativeDnameError --------------------------------------------

/// An error happened while creating a domain name from octets.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RelativeDnameError {
    /// A bad label was encountered.
    BadLabel(LabelTypeError),

    /// A compressed name was encountered.
    CompressedName,

    /// The data ended before the end of a label.
    ShortInput,

    /// The domain name was longer than 255 octets.
    LongName,

    /// The root label was encountered.
    AbsoluteName,
}

//--- From

impl From<LabelTypeError> for RelativeDnameError {
    fn from(err: LabelTypeError) -> Self {
        RelativeDnameError::BadLabel(err)
    }
}

impl From<SplitLabelError> for RelativeDnameError {
    fn from(err: SplitLabelError) -> Self {
        match err {
            SplitLabelError::Pointer(_) => RelativeDnameError::CompressedName,
            SplitLabelError::BadType(t) => RelativeDnameError::BadLabel(t),
            SplitLabelError::ShortInput => RelativeDnameError::ShortInput,
        }
    }
}

//--- Display and Error

impl fmt::Display for RelativeDnameError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            RelativeDnameError::BadLabel(err) => err.fmt(f),
            RelativeDnameError::CompressedName => {
                f.write_str("compressed domain name")
            }
            RelativeDnameError::ShortInput => ParseError::ShortInput.fmt(f),
            RelativeDnameError::LongName => f.write_str("long domain name"),
            RelativeDnameError::AbsoluteName => {
                f.write_str("absolute domain name")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for RelativeDnameError {}

//------------ RelativeFromStrError ------------------------------------------

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RelativeFromStrError {
    /// The name could not be parsed.
    FromStr(FromStrError),

    /// The parsed name was ended in a dot.
    AbsoluteName,
}

//--- From

impl From<FromStrError> for RelativeFromStrError {
    fn from(src: FromStrError) -> Self {
        Self::FromStr(src)
    }
}

//--- Display and Error

impl fmt::Display for RelativeFromStrError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RelativeFromStrError::FromStr(err) => err.fmt(f),
            RelativeFromStrError::AbsoluteName => {
                f.write_str("absolute domain name")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for RelativeFromStrError {}

//------------ StripSuffixError ----------------------------------------------

/// An attempt was made to strip a suffix that wasn’t actually a suffix.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StripSuffixError;

//--- Display and Error

impl fmt::Display for StripSuffixError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("suffix not found")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for StripSuffixError {}

//============ Testing =======================================================

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

    #[cfg(feature = "std")]
    macro_rules! assert_panic {
        ( $cond:expr ) => {{
            let result = std::panic::catch_unwind(|| $cond);
            assert!(result.is_err());
        }};
    }

    #[test]
    #[cfg(feature = "std")]
    fn impls() {
        fn assert_to_relative_dname<T: ToRelativeDname + ?Sized>(_: &T) {}

        assert_to_relative_dname(
            RelativeDname::from_slice(b"\x03www".as_ref()).unwrap(),
        );
        assert_to_relative_dname(
            &RelativeDname::from_octets(b"\x03www").unwrap(),
        );
        assert_to_relative_dname(
            &RelativeDname::from_octets(b"\x03www".as_ref()).unwrap(),
        );
        assert_to_relative_dname(
            &RelativeDname::from_octets(Vec::from(b"\x03www".as_ref()))
                .unwrap(),
        );
    }

    #[cfg(feature = "bytes")]
    #[test]
    fn impl_bytes() {
        fn assert_to_relative_dname<T: ToRelativeDname + ?Sized>(_: &T) {}

        assert_to_relative_dname(
            &RelativeDname::from_octets(Bytes::from(b"\x03www".as_ref()))
                .unwrap(),
        );
    }

    #[test]
    fn empty() {
        assert_eq!(RelativeDname::empty_slice().as_slice(), b"");
        assert_eq!(RelativeDname::empty_ref().as_slice(), b"");

        #[cfg(feature = "std")]
        {
            assert_eq!(RelativeDname::empty_vec().as_slice(), b"");
        }
    }

    #[test]
    fn wildcard() {
        assert_eq!(RelativeDname::wildcard_slice().as_slice(), b"\x01*");
        assert_eq!(RelativeDname::wildcard_ref().as_slice(), b"\x01*");

        #[cfg(feature = "std")]
        {
            assert_eq!(RelativeDname::wildcard_vec().as_slice(), b"\x01*");
        }
    }

    #[cfg(feature = "bytes")]
    #[test]
    fn literals_bytes() {
        assert_eq!(RelativeDname::empty_bytes().as_slice(), b"");
        assert_eq!(RelativeDname::wildcard_bytes().as_slice(), b"\x01*");
    }

    #[test]
    #[cfg(feature = "std")]
    fn from_slice() {
        // good names
        assert_eq!(RelativeDname::from_slice(b"").unwrap().as_slice(), b"");
        assert_eq!(
            RelativeDname::from_slice(b"\x03www").unwrap().as_slice(),
            b"\x03www"
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example")
                .unwrap()
                .as_slice(),
            b"\x03www\x07example"
        );

        // absolute names
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com\0"),
            Err(RelativeDnameError::AbsoluteName)
        );
        assert_eq!(
            RelativeDname::from_slice(b"\0"),
            Err(RelativeDnameError::AbsoluteName)
        );

        // bytes shorter than what label length says.
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07exa"),
            Err(RelativeDnameError::ShortInput)
        );

        // label 63 long ok, 64 bad.
        let mut slice = [0u8; 64];
        slice[0] = 63;
        assert!(RelativeDname::from_slice(&slice[..]).is_ok());
        let mut slice = [0u8; 65];
        slice[0] = 64;
        assert!(RelativeDname::from_slice(&slice[..]).is_err());

        // name 254 long ok, 255 bad.
        let mut buf = Vec::new();
        for _ in 0..25 {
            buf.extend_from_slice(b"\x09123456789");
        }
        assert_eq!(buf.len(), 250);
        let mut tmp = buf.clone();
        tmp.extend_from_slice(b"\x03123");
        assert_eq!(RelativeDname::from_slice(&tmp).map(|_| ()), Ok(()));
        buf.extend_from_slice(b"\x041234");
        assert!(RelativeDname::from_slice(&buf).is_err());

        // bad label heads: compressed, other types.
        assert_eq!(
            RelativeDname::from_slice(b"\xa2asdasds"),
            Err(LabelTypeError::Undefined.into())
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x62asdasds"),
            Err(LabelTypeError::Extended(0x62).into())
        );
        assert_eq!(
            RelativeDname::from_slice(b"\xccasdasds"),
            Err(RelativeDnameError::CompressedName)
        );
    }

    #[test]
    #[cfg(feature = "std")]
    fn from_str() {
        // empty name
        assert_eq!(RelativeDname::vec_from_str("").unwrap().as_slice(), b"");

        // relative name
        assert_eq!(
            RelativeDname::vec_from_str("www.example")
                .unwrap()
                .as_slice(),
            b"\x03www\x07example"
        );

        // absolute name
        assert!(RelativeDname::vec_from_str("www.example.com.").is_err());
    }

    #[test]
    #[cfg(feature = "std")]
    fn into_absolute() {
        assert_eq!(
            RelativeDname::from_octets(Vec::from(
                b"\x03www\x07example\x03com".as_ref()
            ))
            .unwrap()
            .into_absolute()
            .unwrap()
            .as_slice(),
            b"\x03www\x07example\x03com\0"
        );

        // Check that a 254 octets long relative name converts fine.
        let mut buf = Vec::new();
        for _ in 0..25 {
            buf.extend_from_slice(b"\x09123456789");
        }
        assert_eq!(buf.len(), 250);
        let mut tmp = buf.clone();
        tmp.extend_from_slice(b"\x03123");
        RelativeDname::from_octets(tmp)
            .unwrap()
            .into_absolute()
            .unwrap();
    }

    #[test]
    #[cfg(feature = "std")]
    fn make_canonical() {
        let mut name = Dname::vec_from_str("wWw.exAmpLE.coM.").unwrap();
        name.make_canonical();
        assert_eq!(
            name,
            Dname::from_octets(b"\x03www\x07example\x03com\0").unwrap()
        );
    }

    // chain is tested with the Chain type.

    #[test]
    fn chain_root() {
        assert_eq!(
            Dname::from_octets(b"\x03www\x07example\x03com\0").unwrap(),
            RelativeDname::from_octets(b"\x03www\x07example\x03com")
                .unwrap()
                .chain_root()
        );
    }

    #[test]
    fn iter() {
        use crate::base::name::dname::test::cmp_iter;

        cmp_iter(RelativeDname::empty_ref().iter(), &[]);
        cmp_iter(RelativeDname::wildcard_ref().iter(), &[b"*"]);
        cmp_iter(
            RelativeDname::from_slice(b"\x03www\x07example\x03com")
                .unwrap()
                .iter(),
            &[b"www", b"example", b"com"],
        );
    }

    #[test]
    fn iter_back() {
        use crate::base::name::dname::test::cmp_iter_back;

        cmp_iter_back(RelativeDname::empty_ref().iter(), &[]);
        cmp_iter_back(RelativeDname::wildcard_ref().iter(), &[b"*"]);
        cmp_iter_back(
            RelativeDname::from_slice(b"\x03www\x07example\x03com")
                .unwrap()
                .iter(),
            &[b"com", b"example", b"www"],
        );
    }

    #[test]
    fn label_count() {
        assert_eq!(RelativeDname::empty_ref().label_count(), 0);
        assert_eq!(RelativeDname::wildcard_slice().label_count(), 1);
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com")
                .unwrap()
                .label_count(),
            3
        );
    }

    #[test]
    fn first() {
        assert_eq!(RelativeDname::empty_slice().first(), None);
        assert_eq!(
            RelativeDname::from_slice(b"\x03www")
                .unwrap()
                .first()
                .unwrap()
                .as_slice(),
            b"www"
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example")
                .unwrap()
                .first()
                .unwrap()
                .as_slice(),
            b"www"
        );
    }

    #[test]
    fn last() {
        assert_eq!(RelativeDname::empty_slice().last(), None);
        assert_eq!(
            RelativeDname::from_slice(b"\x03www")
                .unwrap()
                .last()
                .unwrap()
                .as_slice(),
            b"www"
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example")
                .unwrap()
                .last()
                .unwrap()
                .as_slice(),
            b"example"
        );
    }

    #[test]
    fn ndots() {
        assert_eq!(RelativeDname::empty_slice().ndots(), 0);
        assert_eq!(RelativeDname::from_slice(b"\x03www").unwrap().ndots(), 0);
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example")
                .unwrap()
                .ndots(),
            1
        );
    }

    #[test]
    fn starts_with() {
        let matrix = [
            (
                RelativeDname::empty_slice(),
                [true, false, false, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www").unwrap(),
                [true, true, false, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www\x07example").unwrap(),
                [true, true, true, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www\x07example\x03com")
                    .unwrap(),
                [true, true, true, true, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x07example\x03com").unwrap(),
                [true, false, false, false, true, false],
            ),
            (
                RelativeDname::from_slice(b"\x03com").unwrap(),
                [true, false, false, false, false, true],
            ),
        ];
        for i in 0..6 {
            for j in 0..6 {
                assert_eq!(
                    matrix[i].0.starts_with(&matrix[j].0),
                    matrix[i].1[j],
                    "i={}, j={}",
                    i,
                    j
                )
            }
        }
    }

    #[test]
    fn ends_with() {
        let matrix = [
            (
                RelativeDname::empty_slice(),
                [true, false, false, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www").unwrap(),
                [true, true, false, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www\x07example").unwrap(),
                [true, false, true, false, false, false],
            ),
            (
                RelativeDname::from_slice(b"\x03www\x07example\x03com")
                    .unwrap(),
                [true, false, false, true, true, true],
            ),
            (
                RelativeDname::from_slice(b"\x07example\x03com").unwrap(),
                [true, false, false, false, true, true],
            ),
            (
                RelativeDname::from_slice(b"\x03com").unwrap(),
                [true, false, false, false, false, true],
            ),
        ];
        for i in 0..matrix.len() {
            for j in 0..matrix.len() {
                assert_eq!(
                    matrix[i].0.ends_with(&matrix[j].0),
                    matrix[i].1[j],
                    "i={}, j={}",
                    i,
                    j
                )
            }
        }
    }

    #[test]
    fn is_label_start() {
        let wec =
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap();

        assert!(wec.is_label_start(0)); // \x03
        assert!(!wec.is_label_start(1)); // w
        assert!(!wec.is_label_start(2)); // w
        assert!(!wec.is_label_start(3)); // w
        assert!(wec.is_label_start(4)); // \x07
        assert!(!wec.is_label_start(5)); // e
        assert!(!wec.is_label_start(6)); // x
        assert!(!wec.is_label_start(7)); // a
        assert!(!wec.is_label_start(8)); // m
        assert!(!wec.is_label_start(9)); // p
        assert!(!wec.is_label_start(10)); // l
        assert!(!wec.is_label_start(11)); // e
        assert!(wec.is_label_start(12)); // \x03
        assert!(!wec.is_label_start(13)); // c
        assert!(!wec.is_label_start(14)); // o
        assert!(!wec.is_label_start(15)); // m
        assert!(wec.is_label_start(16)); // empty label
        assert!(!wec.is_label_start(17)); //
    }

    #[test]
    #[cfg(feature = "std")]
    fn slice() {
        let wec =
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap();
        assert_eq!(wec.slice(0..4).as_slice(), b"\x03www");
        assert_eq!(wec.slice(0..12).as_slice(), b"\x03www\x07example");
        assert_eq!(wec.slice(4..12).as_slice(), b"\x07example");
        assert_eq!(wec.slice(4..16).as_slice(), b"\x07example\x03com");

        assert_panic!(wec.slice(0..3));
        assert_panic!(wec.slice(1..4));
        assert_panic!(wec.slice(0..11));
        assert_panic!(wec.slice(1..12));
        assert_panic!(wec.slice(0..17));
        assert_panic!(wec.slice(4..17));
        assert_panic!(wec.slice(0..18));
    }

    #[test]
    #[cfg(feature = "std")]
    fn range() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();
        assert_eq!(wec.range(0..4).as_slice(), b"\x03www");
        assert_eq!(wec.range(0..12).as_slice(), b"\x03www\x07example");
        assert_eq!(wec.range(4..12).as_slice(), b"\x07example");
        assert_eq!(wec.range(4..16).as_slice(), b"\x07example\x03com");

        assert_panic!(wec.range(0..3));
        assert_panic!(wec.range(1..4));
        assert_panic!(wec.range(0..11));
        assert_panic!(wec.range(1..12));
        assert_panic!(wec.range(0..17));
        assert_panic!(wec.range(4..17));
        assert_panic!(wec.range(0..18));
    }

    #[test]
    #[cfg(feature = "std")]
    fn split() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();

        let (left, right) = wec.split(0);
        assert_eq!(left.as_slice(), b"");
        assert_eq!(right.as_slice(), b"\x03www\x07example\x03com");

        let (left, right) = wec.split(4);
        assert_eq!(left.as_slice(), b"\x03www");
        assert_eq!(right.as_slice(), b"\x07example\x03com");

        let (left, right) = wec.split(12);
        assert_eq!(left.as_slice(), b"\x03www\x07example");
        assert_eq!(right.as_slice(), b"\x03com");

        let (left, right) = wec.split(16);
        assert_eq!(left.as_slice(), b"\x03www\x07example\x03com");
        assert_eq!(right.as_slice(), b"");

        assert_panic!(wec.split(1));
        assert_panic!(wec.split(14));
        assert_panic!(wec.split(17));
        assert_panic!(wec.split(18));
    }

    #[test]
    #[cfg(feature = "std")]
    fn truncate() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();

        let mut tmp = wec.clone();
        tmp.truncate(0);
        assert_eq!(tmp.as_slice(), b"");

        let mut tmp = wec.clone();
        tmp.truncate(4);
        assert_eq!(tmp.as_slice(), b"\x03www");

        let mut tmp = wec.clone();
        tmp.truncate(12);
        assert_eq!(tmp.as_slice(), b"\x03www\x07example");

        let mut tmp = wec.clone();
        tmp.truncate(16);
        assert_eq!(tmp.as_slice(), b"\x03www\x07example\x03com");

        assert_panic!(wec.clone().truncate(1));
        assert_panic!(wec.clone().truncate(14));
        assert_panic!(wec.clone().truncate(17));
        assert_panic!(wec.clone().truncate(18));
    }

    #[test]
    fn split_first() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();

        let (label, wec) = wec.split_first().unwrap();
        assert_eq!(label.as_slice(), b"www");
        assert_eq!(wec.as_slice(), b"\x07example\x03com");

        let (label, wec) = wec.split_first().unwrap();
        assert_eq!(label.as_slice(), b"example");
        assert_eq!(wec.as_slice(), b"\x03com");

        let (label, wec) = wec.split_first().unwrap();
        assert_eq!(label.as_slice(), b"com");
        assert_eq!(wec.as_slice(), b"");
        assert!(wec.split_first().is_none());
    }

    #[test]
    fn parent() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();

        let wec = wec.parent().unwrap();
        assert_eq!(wec.as_slice(), b"\x07example\x03com");

        let wec = wec.parent().unwrap();
        assert_eq!(wec.as_slice(), b"\x03com");

        let wec = wec.parent().unwrap();
        assert_eq!(wec.as_slice(), b"");

        assert!(wec.parent().is_none());
    }

    #[test]
    fn strip_suffix() {
        let wec =
            RelativeDname::from_octets(b"\x03www\x07example\x03com".as_ref())
                .unwrap();
        let ec = RelativeDname::from_octets(b"\x07example\x03com".as_ref())
            .unwrap();
        let c = RelativeDname::from_octets(b"\x03com".as_ref()).unwrap();
        let wen =
            RelativeDname::from_octets(b"\x03www\x07example\x03net".as_ref())
                .unwrap();
        let en = RelativeDname::from_octets(b"\x07example\x03net".as_ref())
            .unwrap();
        let n = RelativeDname::from_slice(b"\x03net".as_ref()).unwrap();

        let mut tmp = wec.clone();
        assert_eq!(tmp.strip_suffix(&wec), Ok(()));
        assert_eq!(tmp.as_slice(), b"");

        let mut tmp = wec.clone();
        assert_eq!(tmp.strip_suffix(&ec), Ok(()));
        assert_eq!(tmp.as_slice(), b"\x03www");

        let mut tmp = wec.clone();
        assert_eq!(tmp.strip_suffix(&c), Ok(()));
        assert_eq!(tmp.as_slice(), b"\x03www\x07example");

        let mut tmp = wec.clone();
        assert_eq!(tmp.strip_suffix(&RelativeDname::empty_ref()), Ok(()));
        assert_eq!(tmp.as_slice(), b"\x03www\x07example\x03com");

        assert_eq!(wec.clone().strip_suffix(&wen), Err(StripSuffixError));
        assert_eq!(wec.clone().strip_suffix(&en), Err(StripSuffixError));
        assert_eq!(wec.clone().strip_suffix(&n), Err(StripSuffixError));
    }

    // No test for Compose since the implementation is so simple.

    #[test]
    fn eq() {
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap()
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            RelativeDname::from_slice(b"\x03wWw\x07eXAMple\x03Com").unwrap()
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            &RelativeDname::from_octets(b"\x03www")
                .unwrap()
                .chain(
                    RelativeDname::from_octets(b"\x07example\x03com")
                        .unwrap()
                )
                .unwrap()
        );
        assert_eq!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            &RelativeDname::from_octets(b"\x03wWw")
                .unwrap()
                .chain(
                    RelativeDname::from_octets(b"\x07eXAMple\x03coM")
                        .unwrap()
                )
                .unwrap()
        );

        assert_ne!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            RelativeDname::from_slice(b"\x03ww4\x07example\x03com").unwrap()
        );
        assert_ne!(
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap(),
            &RelativeDname::from_octets(b"\x03www")
                .unwrap()
                .chain(
                    RelativeDname::from_octets(b"\x073xample\x03com")
                        .unwrap()
                )
                .unwrap()
        );
    }

    #[test]
    fn cmp() {
        use core::cmp::Ordering;

        // The following is taken from section 6.1 of RFC 4034.
        let names = [
            RelativeDname::from_slice(b"\x07example").unwrap(),
            RelativeDname::from_slice(b"\x01a\x07example").unwrap(),
            RelativeDname::from_slice(b"\x08yljkjljk\x01a\x07example")
                .unwrap(),
            RelativeDname::from_slice(b"\x01Z\x01a\x07example").unwrap(),
            RelativeDname::from_slice(b"\x04zABC\x01a\x07example").unwrap(),
            RelativeDname::from_slice(b"\x01z\x07example").unwrap(),
            RelativeDname::from_slice(b"\x01\x01\x01z\x07example").unwrap(),
            RelativeDname::from_slice(b"\x01*\x01z\x07example").unwrap(),
            RelativeDname::from_slice(b"\x01\xc8\x01z\x07example").unwrap(),
        ];
        for i in 0..names.len() {
            for j in 0..names.len() {
                let ord = i.cmp(&j);
                assert_eq!(names[i].partial_cmp(names[j]), Some(ord));
                assert_eq!(names[i].cmp(names[j]), ord);
            }
        }

        let n1 =
            RelativeDname::from_slice(b"\x03www\x07example\x03com").unwrap();
        let n2 =
            RelativeDname::from_slice(b"\x03wWw\x07eXAMple\x03Com").unwrap();
        assert_eq!(n1.partial_cmp(n2), Some(Ordering::Equal));
        assert_eq!(n1.cmp(n2), Ordering::Equal);
    }

    #[test]
    #[cfg(feature = "std")]
    fn hash() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut s1 = DefaultHasher::new();
        let mut s2 = DefaultHasher::new();
        RelativeDname::from_slice(b"\x03www\x07example\x03com")
            .unwrap()
            .hash(&mut s1);
        RelativeDname::from_slice(b"\x03wWw\x07eXAMple\x03Com")
            .unwrap()
            .hash(&mut s2);
        assert_eq!(s1.finish(), s2.finish());
    }

    // Display and Debug skipped for now.

    #[cfg(all(feature = "serde", feature = "std"))]
    #[test]
    fn ser_de() {
        use serde_test::{assert_tokens, Configure, Token};

        let name = RelativeDname::from_octets(Vec::from(
            b"\x03www\x07example\x03com".as_ref(),
        ))
        .unwrap();
        assert_tokens(
            &name.clone().compact(),
            &[
                Token::NewtypeStruct {
                    name: "RelativeDname",
                },
                Token::ByteBuf(b"\x03www\x07example\x03com"),
            ],
        );
        assert_tokens(
            &name.readable(),
            &[
                Token::NewtypeStruct {
                    name: "RelativeDname",
                },
                Token::Str("www.example.com"),
            ],
        );
    }
}