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
//! A domain name that can be both relative or absolute.
//!
//! This is a private module. Its public types are re-exported by the parent.

use super::super::scan::Scanner;
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::relative::{DnameIter, RelativeDname};
use super::traits::ToLabelIter;
#[cfg(feature = "bytes")]
use bytes::Bytes;
use core::{fmt, hash, str};
use octseq::builder::{
    EmptyBuilder, FreezeBuilder, FromBuilder, IntoBuilder,
};
#[cfg(feature = "serde")]
use octseq::serde::{DeserializeOctets, SerializeOctets};
#[cfg(feature = "std")]
use std::vec::Vec;

//------------ UncertainDname ------------------------------------------------

/// A domain name that may be absolute or relative.
///
/// This type is helpful when reading a domain name from some source where it
/// may end up being absolute or not.
#[derive(Clone)]
pub enum UncertainDname<Octets> {
    Absolute(Dname<Octets>),
    Relative(RelativeDname<Octets>),
}

impl<Octets> UncertainDname<Octets> {
    /// Creates a new uncertain domain name from an absolute domain name.
    pub fn absolute(name: Dname<Octets>) -> Self {
        UncertainDname::Absolute(name)
    }

    /// Creates a new uncertain domain name from a relative domain name.
    pub fn relative(name: RelativeDname<Octets>) -> Self {
        UncertainDname::Relative(name)
    }

    /// Creates a new uncertain domain name containing the root label only.
    #[must_use]
    pub fn root() -> Self
    where
        Octets: From<&'static [u8]>,
    {
        UncertainDname::Absolute(Dname::root())
    }

    /// Creates a new uncertain yet empty domain name.
    #[must_use]
    pub fn empty() -> Self
    where
        Octets: From<&'static [u8]>,
    {
        UncertainDname::Relative(RelativeDname::empty())
    }

    /// Creates a new domain name from its wire format representation.
    ///
    /// The returned name will correctly be identified as an absolute or
    /// relative name.
    pub fn from_octets(octets: Octets) -> Result<Self, UncertainDnameError>
    where
        Octets: AsRef<[u8]>,
    {
        if Self::is_slice_absolute(octets.as_ref())? {
            Ok(UncertainDname::Absolute(unsafe {
                Dname::from_octets_unchecked(octets)
            }))
        } else {
            Ok(UncertainDname::Relative(unsafe {
                RelativeDname::from_octets_unchecked(octets)
            }))
        }
    }

    /// Checks an octet slice for a name and returns whether it is absolute.
    fn is_slice_absolute(
        mut slice: &[u8],
    ) -> Result<bool, UncertainDnameError> {
        if slice.len() > Dname::MAX_LEN {
            return Err(UncertainDnameError::LongName);
        }
        loop {
            let (label, tail) = Label::split_from(slice)?;
            if label.is_root() {
                if tail.is_empty() {
                    return Ok(true);
                } else {
                    return Err(UncertainDnameError::TrailingData);
                }
            }
            if tail.is_empty() {
                return Ok(false);
            }
            slice = tail;
        }
    }

    /// Creates a domain name from a sequence of characters.
    ///
    /// The sequence must result in a domain name in zone file
    /// representation. That is, its labels should be separated by dots,
    /// while 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.
    ///
    /// If the last character is a dot, the name will be absolute, otherwise
    /// it will be relative.
    ///
    /// If you have a string, you can also use the `FromStr` trait, which
    /// really does the same thing.
    pub fn from_chars<C>(chars: C) -> Result<Self, FromStrError>
    where
        Octets: FromBuilder,
        <Octets as FromBuilder>::Builder: FreezeBuilder<Octets = Octets>
            + EmptyBuilder
            + AsRef<[u8]>
            + AsMut<[u8]>,
        C: IntoIterator<Item = char>,
    {
        let mut builder =
            DnameBuilder::<<Octets as FromBuilder>::Builder>::new();
        builder.append_chars(chars)?;
        if builder.in_label() || builder.is_empty() {
            Ok(builder.finish().into())
        } else {
            Ok(builder.into_dname()?.into())
        }
    }

    pub fn scan<S: Scanner<Dname = Dname<Octets>>>(
        scanner: &mut S,
    ) -> Result<Self, S::Error> {
        scanner.scan_dname().map(UncertainDname::Absolute)
    }
}

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

    /// Creates an absolute name that is the root label atop a slice reference.
    #[must_use]
    pub fn root_ref() -> Self {
        Self::root()
    }
}

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

    /// Creates an absolute name from the root label atop a `Vec<u8>`.
    #[must_use]
    pub fn root_vec() -> Self {
        Self::root()
    }
}

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

    /// Creates an absolute name from the root label atop a bytes value.
    pub fn root_bytes() -> Self {
        Self::root()
    }
}

impl<Octets> UncertainDname<Octets> {
    /// Returns whether the name is absolute.
    pub fn is_absolute(&self) -> bool {
        match *self {
            UncertainDname::Absolute(_) => true,
            UncertainDname::Relative(_) => false,
        }
    }

    /// Returns whether the name is relative.
    pub fn is_relative(&self) -> bool {
        !self.is_absolute()
    }

    /// Returns a reference to an absolute name, if this name is absolute.
    pub fn as_absolute(&self) -> Option<&Dname<Octets>> {
        match *self {
            UncertainDname::Absolute(ref name) => Some(name),
            _ => None,
        }
    }

    /// Returns a reference to a relative name, if the name is relative.
    pub fn as_relative(&self) -> Option<&RelativeDname<Octets>> {
        match *self {
            UncertainDname::Relative(ref name) => Some(name),
            _ => None,
        }
    }

    /// Converts the name into an absolute name.
    ///
    /// If the name is relative, appends the root label to it using
    /// [`RelativeDname::into_absolute`].
    ///
    /// [`RelativeDname::into_absolute`]:
    ///     struct.RelativeDname.html#method.into_absolute
    pub fn into_absolute(self) -> Result<Dname<Octets>, PushError>
    where
        Octets: AsRef<[u8]> + IntoBuilder,
        <Octets as IntoBuilder>::Builder:
            FreezeBuilder<Octets = Octets> + AsRef<[u8]> + AsMut<[u8]>,
    {
        match self {
            UncertainDname::Absolute(name) => Ok(name),
            UncertainDname::Relative(name) => name.into_absolute(),
        }
    }

    /// Converts the name into an absolute name if it is absolute.
    ///
    /// Otherwise, returns itself as the error.
    pub fn try_into_absolute(self) -> Result<Dname<Octets>, Self> {
        if let UncertainDname::Absolute(name) = self {
            Ok(name)
        } else {
            Err(self)
        }
    }

    /// Converts the name into a relative name if it is relative.
    ///
    /// Otherwise just returns itself as the error.
    pub fn try_into_relative(self) -> Result<RelativeDname<Octets>, Self> {
        if let UncertainDname::Relative(name) = self {
            Ok(name)
        } else {
            Err(self)
        }
    }

    /// Returns a reference to the underlying octets sequence.
    pub fn as_octets(&self) -> &Octets {
        match *self {
            UncertainDname::Absolute(ref name) => name.as_octets(),
            UncertainDname::Relative(ref name) => name.as_octets(),
        }
    }

    /// Returns an octets slice with the raw content of the name.
    pub fn as_slice(&self) -> &[u8]
    where
        Octets: AsRef<[u8]>,
    {
        match *self {
            UncertainDname::Absolute(ref name) => name.as_slice(),
            UncertainDname::Relative(ref name) => name.as_slice(),
        }
    }

    /// Makes an uncertain name absolute by chaining on a suffix if needed.
    ///
    /// The method converts the uncertain name into a chain that will
    /// be absolute. If the name is already absolute, the chain will be the
    /// name itself. If it is relative, if will be the concatenation of the
    /// name and `suffix`.
    pub fn chain<S: ToLabelIter>(
        self,
        suffix: S,
    ) -> Result<Chain<Self, S>, LongChainError>
    where
        Octets: AsRef<[u8]>,
    {
        Chain::new_uncertain(self, suffix)
    }
}

//--- From

impl<Octets> From<Dname<Octets>> for UncertainDname<Octets> {
    fn from(src: Dname<Octets>) -> Self {
        UncertainDname::Absolute(src)
    }
}

impl<Octets> From<RelativeDname<Octets>> for UncertainDname<Octets> {
    fn from(src: RelativeDname<Octets>) -> Self {
        UncertainDname::Relative(src)
    }
}

//--- FromStr

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

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

//--- AsRef

impl<Octs> AsRef<Octs> for UncertainDname<Octs> {
    fn as_ref(&self) -> &Octs {
        match *self {
            UncertainDname::Absolute(ref name) => name.as_ref(),
            UncertainDname::Relative(ref name) => name.as_ref(),
        }
    }
}

impl<Octs: AsRef<[u8]>> AsRef<[u8]> for UncertainDname<Octs> {
    fn as_ref(&self) -> &[u8] {
        match *self {
            UncertainDname::Absolute(ref name) => name.as_ref(),
            UncertainDname::Relative(ref name) => name.as_ref(),
        }
    }
}

//--- PartialEq, and Eq

impl<Octets, Other> PartialEq<UncertainDname<Other>>
    for UncertainDname<Octets>
where
    Octets: AsRef<[u8]>,
    Other: AsRef<[u8]>,
{
    fn eq(&self, other: &UncertainDname<Other>) -> bool {
        use UncertainDname::*;

        match (self, other) {
            (Absolute(l), Absolute(r)) => l.eq(r),
            (Relative(l), Relative(r)) => l.eq(r),
            _ => false,
        }
    }
}

impl<Octets: AsRef<[u8]>> Eq for UncertainDname<Octets> {}

//--- Hash

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

//--- ToLabelIter

impl<Octs: AsRef<[u8]>> ToLabelIter for UncertainDname<Octs> {
    type LabelIter<'a> = DnameIter<'a> where Octs: 'a;

    fn iter_labels(&self) -> Self::LabelIter<'_> {
        match *self {
            UncertainDname::Absolute(ref name) => name.iter_labels(),
            UncertainDname::Relative(ref name) => name.iter_labels(),
        }
    }

    fn compose_len(&self) -> u16 {
        match *self {
            UncertainDname::Absolute(ref name) => name.compose_len(),
            UncertainDname::Relative(ref name) => name.compose_len(),
        }
    }
}

//--- IntoIterator

impl<'a, Octets: AsRef<[u8]>> IntoIterator for &'a UncertainDname<Octets> {
    type Item = &'a Label;
    type IntoIter = DnameIter<'a>;

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

//--- Display and Debug

impl<Octets: AsRef<[u8]>> fmt::Display for UncertainDname<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UncertainDname::Absolute(ref name) => {
                write!(f, "{}.", name)
            }
            UncertainDname::Relative(ref name) => name.fmt(f),
        }
    }
}

impl<Octets: AsRef<[u8]>> fmt::Debug for UncertainDname<Octets> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            UncertainDname::Absolute(ref name) => {
                write!(f, "UncertainDname::Absolute({})", name)
            }
            UncertainDname::Relative(ref name) => {
                write!(f, "UncertainDname::Relative({})", name)
            }
        }
    }
}

//--- Serialize and Deserialize

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

#[cfg(feature = "serde")]
impl<'de, Octets> serde::Deserialize<'de> for UncertainDname<Octets>
where
    Octets: FromBuilder + DeserializeOctets<'de>,
    <Octets as FromBuilder>::Builder: EmptyBuilder
        + FreezeBuilder<Octets = Octets>
        + 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, Octets> serde::de::Visitor<'de> for InnerVisitor<'de, Octets>
        where
            Octets: FromBuilder + DeserializeOctets<'de>,
            <Octets as FromBuilder>::Builder: EmptyBuilder
                + FreezeBuilder<Octets = Octets>
                + AsRef<[u8]>
                + AsMut<[u8]>,
        {
            type Value = UncertainDname<Octets>;

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

            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> Result<Self::Value, E> {
                use core::str::FromStr;

                UncertainDname::from_str(v).map_err(E::custom)
            }

            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| {
                    UncertainDname::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| {
                    UncertainDname::from_octets(octets).map_err(E::custom)
                })
            }
        }

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

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

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a 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(Octets::visitor()))
                } else {
                    Octets::deserialize_with_visitor(
                        deserializer,
                        InnerVisitor(Octets::visitor()),
                    )
                }
            }
        }

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

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

//------------ UncertainDnameError -------------------------------------------

/// A domain name wasn’t encoded correctly.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum UncertainDnameError {
    /// The encoding contained an unknown or disallowed label type.
    BadLabel(LabelTypeError),

    /// The encoding contained a compression pointer.
    CompressedName,

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

    /// There was more data after the root label was encountered.
    TrailingData,

    /// The input ended in the middle of a label.
    ShortInput,
}

//--- From

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

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

//--- Display and Error

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

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

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

#[cfg(test)]
#[cfg(feature = "std")]
mod test {
    use super::*;
    use std::str::FromStr;
    use std::string::String;

    #[test]
    fn from_str() {
        type U = UncertainDname<Vec<u8>>;

        fn name(s: &str) -> U {
            U::from_str(s).unwrap()
        }

        assert_eq!(
            name("www.example.com").as_relative().unwrap().as_slice(),
            b"\x03www\x07example\x03com"
        );
        assert_eq!(
            name("www.example.com.").as_absolute().unwrap().as_slice(),
            b"\x03www\x07example\x03com\0"
        );

        assert_eq!(
            name(r"www\.example.com").as_slice(),
            b"\x0bwww.example\x03com"
        );
        assert_eq!(
            name(r"w\119w.example.com").as_slice(),
            b"\x03www\x07example\x03com"
        );
        assert_eq!(
            name(r"w\000w.example.com").as_slice(),
            b"\x03w\0w\x07example\x03com"
        );

        assert_eq!(U::from_str(r"w\01"), Err(FromStrError::UnexpectedEnd));
        assert_eq!(U::from_str(r"w\"), Err(FromStrError::UnexpectedEnd));
        assert_eq!(
            U::from_str(r"www..example.com"),
            Err(FromStrError::EmptyLabel)
        );
        assert_eq!(
            U::from_str(r"www.example.com.."),
            Err(FromStrError::EmptyLabel)
        );
        assert_eq!(
            U::from_str(r".www.example.com"),
            Err(FromStrError::EmptyLabel)
        );
        assert_eq!(
            U::from_str(r"www.\[322].example.com"),
            Err(FromStrError::BinaryLabel)
        );
        assert_eq!(
            U::from_str(r"www.\2example.com"),
            Err(FromStrError::IllegalEscape)
        );
        assert_eq!(
            U::from_str(r"www.\29example.com"),
            Err(FromStrError::IllegalEscape)
        );
        assert_eq!(
            U::from_str(r"www.\299example.com"),
            Err(FromStrError::IllegalEscape)
        );
        assert_eq!(
            U::from_str(r"www.\892example.com"),
            Err(FromStrError::IllegalEscape)
        );
        assert_eq!(
            U::from_str("www.e\0ample.com"),
            Err(FromStrError::IllegalCharacter('\0'))
        );
        assert_eq!(
            U::from_str("www.eüample.com"),
            Err(FromStrError::IllegalCharacter('ü'))
        );

        // LongLabel
        let mut s = String::from("www.");
        for _ in 0..Label::MAX_LEN {
            s.push('x');
        }
        s.push_str(".com");
        assert!(U::from_str(&s).is_ok());
        let mut s = String::from("www.");
        for _ in 0..64 {
            s.push('x');
        }
        s.push_str(".com");
        assert_eq!(U::from_str(&s), Err(FromStrError::LongLabel));

        // Long Name
        let mut s = String::new();
        for _ in 0..50 {
            s.push_str("four.");
        }
        let mut s1 = s.clone();
        s1.push_str("com.");
        assert_eq!(name(&s1).as_slice().len(), 255);
        let mut s1 = s.clone();
        s1.push_str("com");
        assert_eq!(name(&s1).as_slice().len(), 254);
        let mut s1 = s.clone();
        s1.push_str("coma.");
        assert_eq!(U::from_str(&s1), Err(FromStrError::LongName));
        let mut s1 = s.clone();
        s1.push_str("coma");
        assert_eq!(U::from_str(&s1), Err(FromStrError::LongName));
    }

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

        let abs_name =
            UncertainDname::<Vec<u8>>::from_str("www.example.com.").unwrap();
        assert!(abs_name.is_absolute());

        assert_tokens(
            &abs_name.clone().compact(),
            &[
                Token::NewtypeStruct {
                    name: "UncertainDname",
                },
                Token::ByteBuf(b"\x03www\x07example\x03com\0"),
            ],
        );
        assert_tokens(
            &abs_name.readable(),
            &[
                Token::NewtypeStruct {
                    name: "UncertainDname",
                },
                Token::Str("www.example.com."),
            ],
        );

        let rel_name =
            UncertainDname::<Vec<u8>>::from_str("www.example.com").unwrap();
        assert!(rel_name.is_relative());

        assert_tokens(
            &rel_name.clone().compact(),
            &[
                Token::NewtypeStruct {
                    name: "UncertainDname",
                },
                Token::ByteBuf(b"\x03www\x07example\x03com"),
            ],
        );
        assert_tokens(
            &rel_name.readable(),
            &[
                Token::NewtypeStruct {
                    name: "UncertainDname",
                },
                Token::Str("www.example.com"),
            ],
        );
    }
}