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
//! Parsed domain names.
//!
//! This is a private module. Its public types are re-exported by the parent
//! module.

use super::super::cmp::CanonicalOrd;
use super::super::wire::{FormError, ParseError};
use super::absolute::Name;
use super::label::{Label, LabelTypeError};
use super::relative::RelativeName;
use super::traits::{FlattenInto, ToLabelIter, ToName};
use core::{cmp, fmt, hash};
use octseq::builder::{
    BuilderAppendError, EmptyBuilder, FreezeBuilder, FromBuilder,
    OctetsBuilder,
};
use octseq::octets::Octets;
use octseq::parse::Parser;

//------------ ParsedName ----------------------------------------------------

/// A domain name parsed from a DNS message.
///
/// In an attempt to keep messages small, DNS uses a procedure called ‘name
/// compression.’ It tries to minimize the space used for repeatedly
/// appearing domain names by simply refering to the first occurence of the
/// name. This works not only for complete names but also for suffixes. In
/// this case, the first unique labels of the name are included and then a
/// pointer is included for the remainder of the name.
///
/// A consequence of this is that when parsing a domain name, its labels can
/// be scattered all over the message and we would need to allocate some
/// space to re-assemble the original name. However, in many cases we don’t
/// need the complete name. Many operations can be performed by just
/// iterating over the labels which we can do in place.
///
/// [`ParsedName`] deals with such names. It takes a copy of a [`Parser`]
/// representing a reference to the underlying DNS message and, if nedded,
/// traverses over the name starting at the current position of the parser.
/// When being created, the type quickly walks over the name to check that it
/// is, indeed, a valid name. While this does take a bit of time, it spares
/// you having to deal with possible parse errors later on.
///
/// [`ParsedName`] implementes the [`ToName`] trait, so you can use it
/// everywhere where a generic absolute domain name is accepted. In
/// particular, you can compare it to other names or chain it to the end of a
/// relative name. If necessary, [`ToName::to_name`] can be used to produce
/// a flat, self-contained [`Name`].
#[derive(Clone, Copy)]
pub struct ParsedName<Octs> {
    /// The octets the name is embedded in.
    ///
    /// This needs to be the full message as compression pointers in the name
    /// are indexes into this sequence.
    octets: Octs,

    /// The start position of the name within `octets`.
    pos: usize,

    /// The length of the uncompressed name in octets.
    ///
    /// We need this for implementing [`ToLabelIter`].
    name_len: u16,

    /// Whether the name is compressed.
    ///
    /// This allows various neat optimizations for the case where it isn’t.
    compressed: bool,
}

impl<Octs> ParsedName<Octs> {
    /// Returns whether the name is compressed.
    pub fn is_compressed(&self) -> bool {
        self.compressed
    }

    /// Returns whether the name is the root label only.
    pub fn is_root(&self) -> bool {
        self.name_len == 1
    }

    /// Returns a correctly positioned parser.
    fn parser(&self) -> Parser<Octs>
    where
        Octs: AsRef<[u8]>,
    {
        let mut res = Parser::from_ref(&self.octets);
        res.advance(self.pos).expect("illegal pos in ParsedName");
        res
    }

    /// Returns an equivalent name for a reference to the contained octets.
    pub fn ref_octets(&self) -> ParsedName<&Octs> {
        ParsedName {
            octets: &self.octets,
            pos: self.pos,
            name_len: self.name_len,
            compressed: self.compressed,
        }
    }
}

impl<'a, Octs: Octets + ?Sized> ParsedName<&'a Octs> {
    #[must_use]
    pub fn deref_octets(&self) -> ParsedName<Octs::Range<'a>> {
        ParsedName {
            octets: self.octets.range(..),
            pos: self.pos,
            name_len: self.name_len,
            compressed: self.compressed,
        }
    }
}

/// # Working with Labels
///
impl<Octs: AsRef<[u8]>> ParsedName<Octs> {
    /// Returns an iterator over the labels of the name.
    pub fn iter(&self) -> ParsedNameIter {
        ParsedNameIter::new(self.octets.as_ref(), self.pos, self.name_len)
    }

    /// Returns an iterator over the suffixes of the name.
    ///
    /// The returned iterator starts with the full name and then for each
    /// additional step returns a name with the left-most label stripped off
    /// until it reaches the root label.
    pub fn iter_suffixes(&self) -> ParsedSuffixIter<Octs> {
        ParsedSuffixIter::new(self)
    }

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

    /// Returns a reference to the first label.
    pub fn first(&self) -> &Label {
        self.iter().next().unwrap()
    }

    /// Returns a reference to the last label.
    ///
    /// Because the last label in an absolute name is always the root label,
    /// this method can return a static reference. It is also a wee bit silly,
    /// but here for completeness.
    pub fn last(&self) -> &'static Label {
        Label::root()
    }

    /// 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)
    }

    /// Splits off the first label.
    ///
    /// If this name is longer than just the root label, returns the first
    /// label as a relative name and removes it from the name itself. If the
    /// name is only the root label, returns `None` and does nothing.
    pub fn split_first(&mut self) -> Option<RelativeName<Octs::Range<'_>>>
    where
        Octs: Octets,
    {
        if self.name_len == 1 {
            return None;
        }
        let mut name_len = self.name_len;
        let range = {
            let mut parser = self.parser();
            let len = loop {
                match LabelType::peek(&parser).unwrap() {
                    LabelType::Normal(0) => {
                        unreachable!()
                    }
                    LabelType::Normal(label_len) => break label_len + 1,
                    LabelType::Compressed(pos) => {
                        parser.seek(pos).unwrap();
                    }
                }
            };
            name_len -= len;
            parser.pos()..parser.pos() + usize::from(len)
        };
        self.pos = range.end;
        self.name_len = name_len;
        Some(unsafe {
            RelativeName::from_octets_unchecked(self.octets.range(range))
        })
    }

    /// Reduces the name to the parent of the current name.
    ///
    /// If the name consists of the root label only, returns `false` and does
    /// nothing. Otherwise, drops the first label and returns `true`.
    pub fn parent(&mut self) -> bool {
        if self.name_len == 1 {
            return false;
        }
        let (pos, len) = {
            let mut parser = self.parser();
            let len = loop {
                match LabelType::peek(&parser).unwrap() {
                    LabelType::Normal(0) => {
                        unreachable!()
                    }
                    LabelType::Normal(label_len) => break label_len + 1,
                    LabelType::Compressed(pos) => {
                        parser.seek(pos).unwrap();
                    }
                }
            };
            (parser.pos() + usize::from(len), len)
        };
        self.name_len -= len;
        self.pos = pos;
        true
    }
}

impl<Octs> ParsedName<Octs> {
    pub fn parse<'a, Src: Octets<Range<'a> = Octs> + ?Sized>(
        parser: &mut Parser<'a, Src>,
    ) -> Result<Self, ParseError> {
        ParsedName::parse_ref(parser).map(|res| res.deref_octets())
    }
}

impl<'a, Octs: AsRef<[u8]> + ?Sized> ParsedName<&'a Octs> {
    pub fn parse_ref(
        parser: &mut Parser<'a, Octs>,
    ) -> Result<Self, ParseError> {
        let mut name_len = 0;
        let mut pos = parser.pos();

        // Phase One: No compression pointers have been found yet.
        //
        // Parse labels. If we encounter the root label, return an
        // uncompressed name. Otherwise continue to phase two.
        let mut ptr = loop {
            match LabelType::parse(parser)? {
                LabelType::Normal(0) => {
                    // Root label.
                    name_len += 1;
                    return Ok(ParsedName {
                        octets: parser.octets_ref(),
                        pos,
                        name_len,
                        compressed: false,
                    });
                }
                LabelType::Normal(label_len) => {
                    parser.advance(usize::from(label_len))?;
                    name_len += label_len + 1;
                    if name_len >= 255 {
                        return Err(ParsedDnameError::LongName.into());
                    }
                }
                LabelType::Compressed(ptr) => {
                    break ptr;
                }
            }
        };

        // Phase Two: Compression has occured.
        //
        // Now we need to add up label lengths until we encounter the root
        // label or the name becomes too long.
        //
        // We are going to work on a temporary parser so we can jump around.
        // The actual parser has already reached the end of the name, so we
        // can just shadow it. (Because parsers are copy, dereferencing them
        // clones them.)
        let mut parser = *parser;
        let mut compressed = true;
        loop {
            // Check that the compression pointer points backwards. Because
            // it is 16 bit long and the current position is behind the label
            // header, it needs to less than the current position minus 2 --
            // less so can’t point to itself.
            if ptr >= parser.pos() - 2 {
                return Err(ParsedDnameError::ExcessiveCompression.into());
            }

            // If this is the first label, the returned name may as well start
            // here.
            if name_len == 0 {
                pos = ptr;
                compressed = false;
            }

            // Reposition and read next label.
            parser.seek(ptr)?;

            loop {
                match LabelType::parse(&mut parser)? {
                    LabelType::Normal(0) => {
                        // Root label.
                        name_len += 1;
                        return Ok(ParsedName {
                            octets: parser.octets_ref(),
                            pos,
                            name_len,
                            compressed,
                        });
                    }
                    LabelType::Normal(label_len) => {
                        parser.advance(usize::from(label_len))?;
                        name_len += label_len + 1;
                        if name_len >= 255 {
                            return Err(ParsedDnameError::LongName.into());
                        }
                    }
                    LabelType::Compressed(new_ptr) => {
                        ptr = new_ptr;
                        compressed = true;
                        break;
                    }
                }
            }
        }
    }
}

impl ParsedName<()> {
    /// Skip over a domain name.
    ///
    /// This will only check the uncompressed part of the name. If the name
    /// is compressed but the compression pointer is invalid or the name
    /// pointed to is invalid or too long, the function will still succeed.
    ///
    /// If you need to check that the name you are skipping over is valid, you
    /// will have to use `parse` and drop the result.
    pub fn skip<Src: AsRef<[u8]> + ?Sized>(
        parser: &mut Parser<Src>,
    ) -> Result<(), ParseError> {
        let mut len = 0;
        loop {
            match LabelType::parse(parser) {
                Ok(LabelType::Normal(0)) => {
                    len += 1;
                    if len > 255 {
                        return Err(ParsedDnameError::LongName.into());
                    }
                    return Ok(());
                }
                Ok(LabelType::Normal(label_len)) => {
                    parser.advance(label_len.into())?;
                    len += label_len + 1;
                    if len > 255 {
                        return Err(ParsedDnameError::LongName.into());
                    }
                }
                Ok(LabelType::Compressed(_)) => return Ok(()),
                Err(err) => return Err(err),
            }
        }
    }
}

//--- From

impl<Octs: AsRef<[u8]>> From<Name<Octs>> for ParsedName<Octs> {
    fn from(name: Name<Octs>) -> ParsedName<Octs> {
        let name_len = name.compose_len();
        ParsedName {
            octets: name.into_octets(),
            pos: 0,
            name_len,
            compressed: false,
        }
    }
}

//--- FlattenInto

impl<Octs, Target> FlattenInto<Name<Target>> for ParsedName<Octs>
where
    Octs: Octets,
    Target: FromBuilder,
    <Target as FromBuilder>::Builder: EmptyBuilder,
{
    type AppendError = BuilderAppendError<Target>;

    fn try_flatten_into(self) -> Result<Name<Target>, Self::AppendError> {
        let mut builder =
            Target::Builder::with_capacity(self.compose_len().into());
        if let Some(slice) = self.as_flat_slice() {
            builder.append_slice(slice)?;
        } else {
            self.iter_labels()
                .try_for_each(|label| label.compose(&mut builder))?;
        }
        Ok(unsafe { Name::from_octets_unchecked(builder.freeze()) })
    }
}

//--- PartialEq and Eq

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

impl<Octs: AsRef<[u8]>> Eq for ParsedName<Octs> {}

//--- PartialOrd, Ord, and CanonicalOrd

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

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

impl<Octs, N> CanonicalOrd<N> for ParsedName<Octs>
where
    Octs: AsRef<[u8]>,
    N: ToName + ?Sized,
{
    fn canonical_cmp(&self, other: &N) -> cmp::Ordering {
        self.name_cmp(other)
    }
}

//--- Hash

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

//--- ToLabelIter and ToName

impl<Octs: AsRef<[u8]>> ToLabelIter for ParsedName<Octs> {
    type LabelIter<'s> = ParsedNameIter<'s> where Octs: 's;

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

    fn compose_len(&self) -> u16 {
        self.name_len
    }
}

impl<Octs: AsRef<[u8]>> ToName for ParsedName<Octs> {
    fn as_flat_slice(&self) -> Option<&[u8]> {
        if self.compressed {
            None
        } else {
            Some(
                &self.octets.as_ref()
                    [self.pos..self.pos + usize::from(self.name_len)],
            )
        }
    }
}

//--- IntoIterator

impl<'a, Octs> IntoIterator for &'a ParsedName<Octs>
where
    Octs: AsRef<[u8]>,
{
    type Item = &'a Label;
    type IntoIter = ParsedNameIter<'a>;

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

//--- Display and Debug

impl<Octs: AsRef<[u8]>> fmt::Display for ParsedName<Octs> {
    /// Formats the domain name.
    ///
    /// This will produce the domain name in common display format without
    /// the trailing dot.
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut iter = self.iter();
        write!(f, "{}", iter.next().unwrap())?;
        for label in iter {
            if !label.is_root() {
                write!(f, ".{}", label)?
            }
        }
        Ok(())
    }
}

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

//--- Serialize

#[cfg(feature = "serde")]
impl<Octs: AsRef<[u8]>> serde::Serialize for ParsedName<Octs> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.collect_str(self)
    }
}

//------------ ParsedNameIter -----------------------------------------------

/// An iterator over the labels in a parsed domain name.
#[derive(Clone)]
pub struct ParsedNameIter<'a> {
    slice: &'a [u8],
    pos: usize,
    len: u16,
}

impl<'a> ParsedNameIter<'a> {
    /// Creates a new iterator from the parser and the name length.
    ///
    /// The parser must be positioned at the beginning of the name.
    pub(crate) fn new(slice: &'a [u8], pos: usize, len: u16) -> Self {
        ParsedNameIter { slice, pos, len }
    }

    /// Returns the next label.
    ///
    /// This just assumes that there is a label at the current beginning
    /// of the parser. This may lead to funny results if there isn’t,
    /// including panics if the label head is illegal or points beyond the
    /// end of the message.
    fn get_label(&mut self) -> &'a Label {
        let end = loop {
            let ltype = self.slice[self.pos];
            self.pos += 1;
            match ltype {
                0..=0x3F => break self.pos + (ltype as usize),
                0xC0..=0xFF => {
                    self.pos = (self.slice[self.pos] as usize)
                        | (((ltype as usize) & 0x3F) << 8);
                }
                _ => panic!("bad label"),
            }
        };
        let res = unsafe {
            Label::from_slice_unchecked(&self.slice[self.pos..end])
        };
        self.pos = end;
        self.len -= res.compose_len();
        res
    }
}

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

    fn next(&mut self) -> Option<&'a Label> {
        if self.len == 0 {
            return None;
        }
        Some(self.get_label())
    }
}

impl<'a> DoubleEndedIterator for ParsedNameIter<'a> {
    fn next_back(&mut self) -> Option<&'a Label> {
        if self.len == 0 {
            return None;
        }
        let mut tmp = self.clone();
        let label = loop {
            let label = tmp.get_label();
            if tmp.len == 0 {
                break label;
            }
        };
        self.len -= label.compose_len();
        Some(label)
    }
}

//------------ ParsedSuffixIter ----------------------------------------------

/// An iterator over ever shorter suffixes of a parsed domain name.
#[derive(Clone)]
pub struct ParsedSuffixIter<'a, Octs: ?Sized> {
    name: Option<ParsedName<&'a Octs>>,
}

impl<'a, Octs> ParsedSuffixIter<'a, Octs> {
    /// Creates a new iterator cloning `name`.
    fn new(name: &'a ParsedName<Octs>) -> Self {
        ParsedSuffixIter {
            name: Some(name.ref_octets()),
        }
    }
}

impl<'a, Octs: Octets + ?Sized> Iterator for ParsedSuffixIter<'a, Octs> {
    type Item = ParsedName<Octs::Range<'a>>;

    fn next(&mut self) -> Option<Self::Item> {
        let name = match self.name {
            Some(ref mut name) => name,
            None => return None,
        };
        let res = name.deref_octets();
        if !name.parent() {
            self.name = None
        }
        Some(res)
    }
}

//------------ LabelType -----------------------------------------------------

/// The type of a label.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum LabelType {
    /// A normal label with its size in octets.
    Normal(u16),

    /// A compressed label with the position of where to continue.
    Compressed(usize),
}

impl LabelType {
    /// Attempts to take a label type from the beginning of `parser`.
    pub fn parse<Octs: AsRef<[u8]> + ?Sized>(
        parser: &mut Parser<Octs>,
    ) -> Result<Self, ParseError> {
        let ltype = parser.parse_u8()?;
        match ltype {
            0..=0x3F => Ok(LabelType::Normal(ltype.into())),
            0xC0..=0xFF => {
                let res = usize::from(parser.parse_u8()?);
                let res = res | ((usize::from(ltype) & 0x3F) << 8);
                Ok(LabelType::Compressed(res))
            }
            _ => Err(ParseError::Form(FormError::new("invalid label type"))),
        }
    }

    /// Returns the label type at the beginning of `parser` without advancing.
    pub fn peek<Ref: AsRef<[u8]> + ?Sized>(
        parser: &Parser<Ref>,
    ) -> Result<Self, ParseError> {
        let ltype = parser.peek(1)?[0];
        match ltype {
            0..=0x3F => Ok(LabelType::Normal(ltype.into())),
            0xC0..=0xFF => {
                let res = usize::from(parser.peek(2)?[1]);
                let res = res | ((usize::from(ltype) & 0x3F) << 8);
                Ok(LabelType::Compressed(res))
            }
            _ => Err(ParseError::Form(FormError::new("invalid label type"))),
        }
    }
}

//------------ ParsedDnameError ----------------------------------------------

/// Parsing a domain name failed.
///
/// This type isn’t used as a public error type but is only converted into
/// [`FormError`]s etc. Thus it doesn’t need to be public.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ParsedDnameError {
    /// A bad label was encountered.
    BadLabel(LabelTypeError),

    /// The name is longer than the 255 octets allowed.
    LongName,

    /// Too many compression pointers.
    ExcessiveCompression,
}

impl fmt::Display for ParsedDnameError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        FormError::from(*self).fmt(f)
    }
}

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

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

impl From<ParsedDnameError> for FormError {
    fn from(err: ParsedDnameError) -> FormError {
        match err {
            ParsedDnameError::BadLabel(_) => {
                FormError::new("invalid label type")
            }
            ParsedDnameError::LongName => FormError::new("long domain name"),
            ParsedDnameError::ExcessiveCompression => {
                FormError::new("too many compression pointers")
            }
        }
    }
}

impl From<ParsedDnameError> for ParseError {
    fn from(err: ParsedDnameError) -> ParseError {
        ParseError::Form(err.into())
    }
}

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

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

    macro_rules! name {
        (root) => {
            name!(b"123\0", 3, 1, false)
        };
        (flat) => {
            name!(b"\x03www\x07example\x03com\0\xc0\0", 0, 17, false)
        };
        (copy) => {
            name!(b"\x03www\x07example\x03com\0\xc0\0", 17, 17, false)
        };
        (once) => {
            name!(b"\x03com\0\x03www\x07example\xC0\0", 5, 17, true)
        };
        (twice) => {
            name!(b"\x03com\0\x07example\xc0\0\x03www\xc0\x05", 15, 17, true)
        };

        ($bytes:expr, $start:expr, $len:expr, $compressed:expr) => {{
            let mut parser = Parser::from_ref($bytes.as_ref());
            parser.advance($start).unwrap();
            ParsedName {
                octets: $bytes.as_ref(),
                pos: $start,
                name_len: $len,
                compressed: $compressed,
            }
        }};
    }

    static WECR: &[u8] = b"\x03www\x07example\x03com\0";

    #[test]
    fn len() {
        assert_eq!(name!(root).compose_len(), 1);
        assert_eq!(name!(flat).compose_len(), 17);
        assert_eq!(name!(once).compose_len(), 17);
        assert_eq!(name!(twice).compose_len(), 17);
    }

    #[test]
    fn is_compressed() {
        assert!(!name!(root).is_compressed());
        assert!(!name!(flat).is_compressed());
        assert!(name!(once).is_compressed());
        assert!(name!(twice).is_compressed());
    }

    #[test]
    fn is_root() {
        assert!(name!(root).is_root());
        assert!(!name!(flat).is_root());
        assert!(!name!(once).is_root());
        assert!(!name!(twice).is_root());
    }

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

        let labels: &[&[u8]] = &[b"www", b"example", b"com", b""];
        cmp_iter(name!(root).iter(), &[b""]);
        cmp_iter(name!(flat).iter(), labels);
        cmp_iter(name!(once).iter(), labels);
        cmp_iter(name!(twice).iter(), labels);
    }

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

        let labels: &[&[u8]] = &[b"", b"com", b"example", b"www"];
        cmp_iter_back(name!(root).iter(), &[b""]);
        cmp_iter_back(name!(flat).iter(), labels);
        cmp_iter_back(name!(once).iter(), labels);
        cmp_iter_back(name!(twice).iter(), labels);
    }

    fn cmp_iter_suffixes<'a, I>(iter: I, labels: &[&[u8]])
    where
        I: Iterator<Item = ParsedName<&'a [u8]>>,
    {
        for (name, labels) in iter.zip(labels) {
            let mut iter = name.iter();
            let labels = Name::from_slice(labels).unwrap();
            let mut labels_iter = labels.iter();
            loop {
                match (iter.next(), labels_iter.next()) {
                    (Some(left), Some(right)) => assert_eq!(left, right),
                    (None, None) => break,
                    (_, None) => panic!("extra items in iterator"),
                    (None, _) => panic!("missing items in iterator"),
                }
            }
        }
    }

    #[test]
    fn iter_suffixes() {
        let suffixes: &[&[u8]] = &[
            b"\x03www\x07example\x03com\0",
            b"\x07example\x03com\0",
            b"\x03com\0",
            b"\0",
        ];
        cmp_iter_suffixes(name!(root).iter_suffixes(), &[b"\0"]);
        cmp_iter_suffixes(name!(flat).iter_suffixes(), suffixes);
        cmp_iter_suffixes(name!(once).iter_suffixes(), suffixes);
        cmp_iter_suffixes(name!(twice).iter_suffixes(), suffixes);
    }

    #[test]
    fn label_count() {
        assert_eq!(name!(root).label_count(), 1);
        assert_eq!(name!(flat).label_count(), 4);
        assert_eq!(name!(once).label_count(), 4);
        assert_eq!(name!(twice).label_count(), 4);
    }

    #[test]
    fn first() {
        assert_eq!(name!(root).first().as_slice(), b"");
        assert_eq!(name!(flat).first().as_slice(), b"www");
        assert_eq!(name!(once).first().as_slice(), b"www");
        assert_eq!(name!(twice).first().as_slice(), b"www");
    }

    #[test]
    fn starts_with() {
        let root = name!(root);
        let flat_wec = name!(flat);
        let once_wec = name!(once);
        let twice_wec = name!(twice);

        let test = Name::root_ref();
        assert!(root.starts_with(&test));
        assert!(!flat_wec.starts_with(&test));
        assert!(!once_wec.starts_with(&test));
        assert!(!twice_wec.starts_with(&test));

        let test = RelativeName::empty_ref();
        assert!(root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test = RelativeName::from_slice(b"\x03www").unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test = RelativeName::from_slice(b"\x03www\x07example").unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test =
            RelativeName::from_slice(b"\x03www\x07example\x03com").unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test = Name::from_slice(b"\x03www\x07example\x03com\0").unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test = RelativeName::from_slice(b"\x07example\x03com").unwrap();
        assert!(!root.starts_with(&test));
        assert!(!flat_wec.starts_with(&test));
        assert!(!once_wec.starts_with(&test));
        assert!(!twice_wec.starts_with(&test));

        let test = RelativeName::from_octets(b"\x03www".as_ref())
            .unwrap()
            .chain(
                RelativeName::from_octets(b"\x07example".as_ref()).unwrap(),
            )
            .unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));

        let test = test
            .chain(RelativeName::from_octets(b"\x03com".as_ref()).unwrap())
            .unwrap();
        assert!(!root.starts_with(&test));
        assert!(flat_wec.starts_with(&test));
        assert!(once_wec.starts_with(&test));
        assert!(twice_wec.starts_with(&test));
    }

    #[test]
    fn ends_with() {
        let root = name!(root);
        let flat_wec = name!(flat);
        let once_wec = name!(once);
        let twice_wec = name!(twice);
        let wecr = Name::from_octets(b"\x03www\x07example\x03com\0".as_ref())
            .unwrap();

        for name in wecr.iter_suffixes() {
            if name.is_root() {
                assert!(root.ends_with(&name))
            } else {
                assert!(!root.ends_with(&name))
            }
            assert!(flat_wec.ends_with(&name));
            assert!(once_wec.ends_with(&name));
            assert!(twice_wec.ends_with(&name));
        }
    }

    #[test]
    #[cfg(feature = "std")]
    fn split_first() {
        fn split_first_wec(mut name: ParsedName<&[u8]>) {
            assert_eq!(
                name.to_vec().as_slice(),
                b"\x03www\x07example\x03com\0"
            );
            assert_eq!(
                name.split_first().unwrap().as_slice(),
                b"\x03www".as_ref()
            );
            assert_eq!(name.to_vec().as_slice(), b"\x07example\x03com\0");
            assert_eq!(
                name.split_first().unwrap().as_slice(),
                b"\x07example".as_ref()
            );
            assert_eq!(name.to_vec().as_slice(), b"\x03com\0");
            assert_eq!(
                name.split_first().unwrap().as_slice(),
                b"\x03com".as_ref()
            );
            assert_eq!(name.to_vec().as_slice(), b"\0");
            assert_eq!(name.split_first(), None);
            assert_eq!(name.split_first(), None);
        }

        split_first_wec(name!(flat));
        split_first_wec(name!(once));
        split_first_wec(name!(twice));
    }

    #[test]
    #[cfg(feature = "std")]
    fn parent() {
        fn parent_wec(mut name: ParsedName<&[u8]>) {
            assert_eq!(
                name.to_vec().as_slice(),
                b"\x03www\x07example\x03com\0"
            );
            assert!(name.parent());
            assert_eq!(name.to_vec().as_slice(), b"\x07example\x03com\0");
            assert!(name.parent());
            assert_eq!(name.to_vec().as_slice(), b"\x03com\0");
            assert!(name.parent());
            assert_eq!(name.to_vec().as_slice(), b"\0");
            assert!(!name.parent());
            assert!(!name.parent());
        }

        parent_wec(name!(flat));
        parent_wec(name!(once));
        parent_wec(name!(twice));
    }

    #[test]
    #[cfg(feature = "std")]
    fn parse_and_skip() {
        use std::vec::Vec;

        fn name_eq(parsed: ParsedName<&[u8]>, name: ParsedName<&[u8]>) {
            assert_eq!(parsed.octets, name.octets);
            assert_eq!(parsed.pos, name.pos);
            assert_eq!(parsed.name_len, name.name_len);
            assert_eq!(parsed.compressed, name.compressed);
        }

        fn parse(
            mut parser: Parser<&[u8]>,
            equals: ParsedName<&[u8]>,
            compose_len: usize,
        ) {
            let end = parser.pos() + compose_len;
            name_eq(ParsedName::parse(&mut parser).unwrap(), equals);
            assert_eq!(parser.pos(), end);
        }

        fn skip(name: ParsedName<&[u8]>, len: usize) {
            let mut parser = name.parser();
            let pos = parser.pos();
            assert_eq!(ParsedName::skip(&mut parser), Ok(()));
            assert_eq!(parser.pos(), pos + len);
        }

        fn p(slice: &[u8], pos: usize) -> Parser<[u8]> {
            let mut res = Parser::from_ref(slice);
            res.advance(pos).unwrap();
            res
        }

        // Correctly formatted names.
        parse(name!(root).parser(), name!(root), 1);
        parse(name!(flat).parser(), name!(flat), 17);
        parse(name!(copy).parser(), name!(flat), 2);
        parse(name!(once).parser(), name!(once), 14);
        parse(name!(twice).parser(), name!(twice), 6);
        skip(name!(root), 1);
        skip(name!(flat), 17);
        skip(name!(copy), 2);
        skip(name!(once), 14);
        skip(name!(twice), 6);

        // Short buffer in the middle of a label.
        let mut parser = p(b"\x03www\x07exam", 0);
        assert_eq!(
            ParsedName::parse(&mut parser.clone()),
            Err(ParseError::ShortInput)
        );
        assert_eq!(
            ParsedName::skip(&mut parser),
            Err(ParseError::ShortInput)
        );

        // Short buffer at end of label.
        let mut parser = p(b"\x03www\x07example", 0);
        assert_eq!(
            ParsedName::parse(&mut parser.clone()),
            Err(ParseError::ShortInput)
        );
        assert_eq!(
            ParsedName::skip(&mut parser),
            Err(ParseError::ShortInput)
        );

        // Compression pointer beyond the end of buffer.
        let mut parser = p(b"\x03www\xc0\xee12", 0);
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);

        // Compression pointer to itself
        assert!(ParsedName::parse(&mut p(b"\x03www\xc0\x0412", 4)).is_err());

        // Compression pointer forward
        assert!(ParsedName::parse(&mut p(b"\x03www\xc0\x0612", 4)).is_err());

        // Bad label header.
        let mut parser = p(b"\x03www\x07example\xbffoo", 0);
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert!(ParsedName::skip(&mut parser).is_err());

        // Long name: 255 bytes is fine.
        let mut buf = Vec::from(&b"\x03123\0"[..]);
        for _ in 0..25 {
            buf.extend_from_slice(b"\x09123456789");
        }
        buf.extend_from_slice(b"\xc0\x0012");
        let mut parser = Parser::from_ref(buf.as_slice());
        parser.advance(5).unwrap();
        let name = ParsedName::parse(&mut parser.clone()).unwrap();
        assert_eq!(name.compose_len(), 255);
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);

        // Long name: 256 bytes are bad.
        let mut buf = Vec::from(&b"\x041234\x00"[..]);
        for _ in 0..25 {
            buf.extend_from_slice(b"\x09123456789");
        }
        buf.extend_from_slice(b"\xc0\x0012");
        let mut parser = Parser::from_ref(buf.as_slice());
        parser.advance(6).unwrap();
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);

        // Long name through recursion
        let mut parser = p(b"\x03www\xc0\x0012", 0);
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);

        // Single-step infinite recursion
        let mut parser = p(b"\xc0\x0012", 0);
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);

        // Two-step infinite recursion
        let mut parser = p(b"\xc0\x02\xc0\x0012", 2);
        assert!(ParsedName::parse(&mut parser.clone()).is_err());
        assert_eq!(ParsedName::skip(&mut parser), Ok(()));
        assert_eq!(parser.remaining(), 2);
    }

    #[test]
    #[cfg(feature = "std")]
    fn compose() {
        use octseq::builder::infallible;
        use std::vec::Vec;

        fn step(name: ParsedName<&[u8]>, result: &[u8]) {
            let mut buf = Vec::new();
            infallible(name.compose(&mut buf));
            assert_eq!(buf.as_slice(), result);
        }

        step(name!(root), b"\x00");
        step(name!(flat), WECR);
        step(name!(once), WECR);
        step(name!(twice), WECR);
    }

    // XXX TODO compose_canonical

    #[test]
    fn as_flat_slice() {
        assert_eq!(name!(root).as_flat_slice(), Some(b"\x00".as_ref()));
        assert_eq!(name!(flat).as_flat_slice(), Some(WECR));
        assert_eq!(name!(once).as_flat_slice(), None);
        assert_eq!(name!(twice).as_flat_slice(), None);
    }

    #[test]
    fn eq() {
        fn step<N: ToName + fmt::Debug>(name: N) {
            assert_eq!(name!(flat), &name);
            assert_eq!(name!(once), &name);
            assert_eq!(name!(twice), &name);
        }

        fn ne_step<N: ToName + fmt::Debug>(name: N) {
            assert_ne!(name!(flat), &name);
            assert_ne!(name!(once), &name);
            assert_ne!(name!(twice), &name);
        }

        step(name!(flat));
        step(name!(once));
        step(name!(twice));

        step(Name::from_slice(b"\x03www\x07example\x03com\x00").unwrap());
        step(Name::from_slice(b"\x03wWw\x07EXAMPLE\x03com\x00").unwrap());
        step(
            RelativeName::from_octets(b"\x03www\x07example\x03com")
                .unwrap()
                .chain_root(),
        );
        step(
            RelativeName::from_octets(b"\x03www\x07example")
                .unwrap()
                .chain(Name::from_octets(b"\x03com\x00").unwrap())
                .unwrap(),
        );

        ne_step(Name::from_slice(b"\x03ww4\x07EXAMPLE\x03com\x00").unwrap());
    }

    // XXX TODO Test for cmp and hash.
}