domain 0.12.0

A DNS library for Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
//! Absolute domain names.

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

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

use super::{
    CanonicalName, Label, LabelBuf, LabelIter, LabelParseError,
    NameCompressor,
};

//----------- Name -----------------------------------------------------------

/// An absolute domain name.
#[derive(AsBytes, BuildBytes, UnsizedCopy)]
#[repr(transparent)]
pub struct Name([u8]);

//--- Constants

impl Name {
    /// The maximum size of a domain name.
    pub const MAX_SIZE: usize = 255;

    /// The root name.
    pub const ROOT: &'static Self = {
        // SAFETY: A root label is the shortest valid name.
        unsafe { Self::from_bytes_unchecked(&[0u8]) }
    };
}

//--- Construction

impl Name {
    /// Assume a byte sequence is a valid [`Name`].
    ///
    /// # Safety
    ///
    /// The byte sequence must represent a valid uncompressed domain name in
    /// the conventional wire format (a sequence of labels terminating with a
    /// root label, totalling 255 bytes or less).
    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
        // SAFETY: 'Name' is 'repr(transparent)' to '[u8]', so casting a
        // '[u8]' into a 'Name' is sound.
        core::mem::transmute(bytes)
    }

    /// Assume a mutable byte sequence is a valid [`Name`].
    ///
    /// # Safety
    ///
    /// The byte sequence must represent a valid uncompressed domain name in
    /// the conventional wire format (a sequence of labels terminating with a
    /// root label, totalling 255 bytes or less).
    pub unsafe fn from_bytes_unchecked_mut(bytes: &mut [u8]) -> &mut Self {
        // SAFETY: 'Name' is 'repr(transparent)' to '[u8]', so casting a
        // '[u8]' into a 'Name' is sound.
        core::mem::transmute(bytes)
    }
}

//--- Inspection

impl Name {
    /// The size of this name in the wire format.
    #[allow(clippy::len_without_is_empty)]
    pub const fn len(&self) -> usize {
        self.0.len()
    }

    /// Whether this is the root label.
    pub const fn is_root(&self) -> bool {
        self.0.len() == 1
    }

    /// A byte representation of the [`Name`].
    pub const fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// The labels in the [`Name`].
    pub const fn labels(&self) -> LabelIter<'_> {
        // SAFETY: A 'Name' always contains valid encoded labels.
        unsafe { LabelIter::new_unchecked(self.as_bytes()) }
    }
}

//--- Canonical operations

impl CanonicalName for Name {
    fn cmp_composed(&self, other: &Self) -> Ordering {
        self.as_bytes().cmp(other.as_bytes())
    }

    fn cmp_lowercase_composed(&self, other: &Self) -> Ordering {
        self.as_bytes()
            .iter()
            .map(u8::to_ascii_lowercase)
            .cmp(other.as_bytes().iter().map(u8::to_ascii_lowercase))
    }
}

//--- Parsing from bytes

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

impl<'a> SplitBytes<'a> for &'a Name {
    fn split_bytes(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), ParseError> {
        let mut offset = 0usize;
        while offset < 255 {
            match *bytes.get(offset..).ok_or(ParseError)? {
                [0, ..] => {
                    // Found the root, stop.
                    let (name, rest) = bytes.split_at(offset + 1);

                    // SAFETY: 'name' follows the wire format and is 255 bytes
                    // or shorter.
                    let name = unsafe { Name::from_bytes_unchecked(name) };
                    return Ok((name, rest));
                }

                [l @ 1..=63, ref rest @ ..] if rest.len() >= l as usize => {
                    // This looks like a regular label.
                    offset += 1 + l as usize;
                }

                _ => return Err(ParseError),
            }
        }

        Err(ParseError)
    }
}

//--- Building in DNS messages

impl BuildInMessage for Name {
    fn build_in_message(
        &self,
        contents: &mut [u8],
        start: usize,
        compressor: &mut NameCompressor,
    ) -> Result<usize, TruncationError> {
        if let Some((rest, addr)) =
            compressor.compress_name(&contents[..start], self)
        {
            // The name was compressed, and 'rest' is the uncompressed part.
            let end = start + rest.len() + 2;
            let bytes =
                contents.get_mut(start..end).ok_or(TruncationError)?;
            bytes[..rest.len()].copy_from_slice(rest);

            // Add the top bits and the 12-byte offset for the message header.
            let addr = (addr + 0xC00C).to_be_bytes();
            bytes[rest.len()..].copy_from_slice(&addr);
            Ok(end)
        } else {
            // The name could not be compressed.
            let end = start + self.len();
            contents
                .get_mut(start..end)
                .ok_or(TruncationError)?
                .copy_from_slice(self.as_bytes());
            Ok(end)
        }
    }
}

//--- Cloning

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

//--- Equality

impl PartialEq for Name {
    fn eq(&self, other: &Self) -> bool {
        // Instead of iterating labels, blindly iterate bytes. The locations
        // of labels don't matter since we're testing everything for equality.

        // NOTE: Label lengths (which are less than 64) aren't affected by
        // 'to_ascii_lowercase', so this method can be applied uniformly.
        // This gives the compiler opportunities to vectorize the code.
        let lhs = self.as_bytes().iter().map(u8::to_ascii_lowercase);
        let rhs = other.as_bytes().iter().map(u8::to_ascii_lowercase);

        lhs.eq(rhs)
    }
}

impl Eq for Name {}

//--- Comparison

impl PartialOrd for Name {
    fn partial_cmp(&self, that: &Self) -> Option<Ordering> {
        Some(self.cmp(that))
    }
}

impl Ord for Name {
    fn cmp(&self, that: &Self) -> Ordering {
        // We wish to compare the labels in these names in reverse order.
        // Unfortunately, labels in absolute names cannot be traversed
        // backwards efficiently. We need to try harder.
        //
        // Consider two names that are not equal. This means that one name is
        // a strict suffix of the other, or that the two had different labels
        // at some position. Following this mismatched label is a suffix of
        // labels that both names do agree on.
        //
        // We traverse the bytes in the names in reverse order and find the
        // length of their shared suffix. The actual shared suffix, in units
        // of labels, may be shorter than this (because the last bytes of the
        // mismatched labels could be the same).
        //
        // Then, we traverse the labels of both names in forward order, until
        // we hit the shared suffix territory. We try to match up the names
        // in order to discover the real shared suffix. Once the suffix is
        // found, the immediately preceding label (if there is one) contains
        // the inequality, and can be compared as usual.

        let suffix_len = core::iter::zip(
            self.as_bytes().iter().rev().map(u8::to_ascii_lowercase),
            that.as_bytes().iter().rev().map(u8::to_ascii_lowercase),
        )
        .position(|(a, b)| a != b);

        let Some(suffix_len) = suffix_len else {
            // 'iter::zip()' simply ignores unequal iterators, stopping when
            // either iterator finishes. Even though the two names had no
            // mismatching bytes, one could be longer than the other.
            return self.len().cmp(&that.len());
        };

        // Prepare for forward traversal.
        let (mut lhs, mut rhs) = (self.labels(), that.labels());
        // SAFETY: There is at least one unequal byte, and it cannot be the
        //   root label, so both names have at least one additional label.
        let mut prev = unsafe {
            (lhs.next().unwrap_unchecked(), rhs.next().unwrap_unchecked())
        };

        // Traverse both names in lockstep, trying to match their lengths.
        loop {
            let (llen, rlen) = (lhs.remaining().len(), rhs.remaining().len());
            if llen == rlen && llen <= suffix_len {
                // We're in shared suffix territory, and 'lhs' and 'rhs' have
                // the same length. Thus, they must be identical, and we have
                // found the shared suffix.
                break prev.0.cmp(prev.1);
            } else if llen > rlen {
                // Try to match the lengths by shortening 'lhs'.

                // SAFETY: 'llen > rlen >= 1', thus 'lhs' contains at least
                //   one additional label before the root.
                prev.0 = unsafe { lhs.next().unwrap_unchecked() };
            } else {
                // Try to match the lengths by shortening 'rhs'.

                // SAFETY: Either:
                // - '1 <= llen < rlen', thus 'rhs' contains at least one
                //   additional label before the root.
                // - 'llen == rlen > suffix_len >= 1', thus 'rhs' contains at
                //   least one additional label before the root.
                prev.1 = unsafe { rhs.next().unwrap_unchecked() };
            }
        }
    }
}

//--- Hashing

impl Hash for Name {
    fn hash<H: Hasher>(&self, state: &mut H) {
        for byte in self.as_bytes() {
            // NOTE: Label lengths (which are less than 64) aren't affected by
            // 'to_ascii_lowercase', so this method can be applied uniformly.
            state.write_u8(byte.to_ascii_lowercase())
        }
    }
}

//--- Formatting

impl fmt::Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        self.labels().try_for_each(|label| {
            if !first {
                f.write_str(".")?;
            } else {
                first = false;
            }

            label.fmt(f)
        })
    }
}

impl fmt::Debug for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Name({})", self)
    }
}

//--- Serialize

#[cfg(feature = "serde")]
impl serde::Serialize for Name {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        use std::string::ToString;

        if serializer.is_human_readable() {
            serializer.serialize_newtype_struct("Name", &self.to_string())
        } else {
            serializer.serialize_newtype_struct("Name", self.as_bytes())
        }
    }
}

//----------- NameBuf --------------------------------------------------------

/// A 256-byte buffer containing a [`Name`].
#[derive(Clone)]
#[repr(C)] // make layout compatible with '[u8; 256]'
pub struct NameBuf {
    /// The size of the encoded name.
    size: u8,

    /// The buffer containing the [`Name`].
    buffer: [u8; 255],
}

//--- Construction

impl NameBuf {
    /// Construct an empty, invalid buffer.
    const fn empty() -> Self {
        Self {
            size: 0,
            buffer: [0; 255],
        }
    }

    /// Copy a [`Name`] into a buffer.
    pub fn copy_from(name: &Name) -> Self {
        let mut buffer = [0u8; 255];
        buffer[..name.len()].copy_from_slice(name.as_bytes());
        Self {
            size: name.len() as u8,
            buffer,
        }
    }
}

impl UnsizedCopyFrom for NameBuf {
    type Source = Name;

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

//--- Parsing from DNS messages

impl<'a> SplitMessageBytes<'a> for NameBuf {
    fn split_message_bytes(
        contents: &'a [u8],
        start: usize,
    ) -> Result<(Self, usize), ParseError> {
        // NOTE: The input may be controlled by an attacker. Compression
        // pointers can be arranged to cause loops or to access every byte in
        // the message in random order. Instead of performing complex loop
        // detection, which would probably perform allocations, we simply
        // disallow a name to point to data _after_ it. Standard name
        // compressors will never generate such pointers.

        let mut buffer = Self::empty();

        // Perform the first iteration early, to catch the end of the name.
        let bytes = contents.get(start..).ok_or(ParseError)?;
        let (mut pointer, rest) = parse_segment(bytes, &mut buffer)?;
        let orig_end = contents.len() - rest.len();

        // Traverse compression pointers.
        let mut old_start = start;
        while let Some(start) = pointer.map(usize::from) {
            let start = start.checked_sub(12).ok_or(ParseError)?;

            // Ensure the referenced position comes earlier.
            if start >= old_start {
                return Err(ParseError);
            }

            // Keep going, from the referenced position.
            let bytes = contents.get(start..).ok_or(ParseError)?;
            (pointer, _) = parse_segment(bytes, &mut buffer)?;
            old_start = start;
            continue;
        }

        // Stop and return the original end.
        // NOTE: 'buffer' is now well-formed because we only stop when we
        // reach a root label (which has been appended into it).
        Ok((buffer, orig_end))
    }
}

impl<'a> ParseMessageBytes<'a> for NameBuf {
    fn parse_message_bytes(
        contents: &'a [u8],
        start: usize,
    ) -> Result<Self, ParseError> {
        // See 'split_from_message()' for details. The only differences are
        // in the range of the first iteration, and the check that the first
        // iteration exactly covers the input range.

        let mut buffer = Self::empty();

        // Perform the first iteration early, to catch the end of the name.
        let bytes = contents.get(start..).ok_or(ParseError)?;
        let (mut pointer, rest) = parse_segment(bytes, &mut buffer)?;

        if !rest.is_empty() {
            // The name didn't reach the end of the input range, fail.
            return Err(ParseError);
        }

        // Traverse compression pointers.
        let mut old_start = start;
        while let Some(start) = pointer.map(usize::from) {
            let start = start.checked_sub(12).ok_or(ParseError)?;

            // Ensure the referenced position comes earlier.
            if start >= old_start {
                return Err(ParseError);
            }

            // Keep going, from the referenced position.
            let bytes = contents.get(start..).ok_or(ParseError)?;
            (pointer, _) = parse_segment(bytes, &mut buffer)?;
            old_start = start;
            continue;
        }

        // NOTE: 'buffer' is now well-formed because we only stop when we
        // reach a root label (which has been appended into it).
        Ok(buffer)
    }
}

/// Parse an encoded and potentially-compressed domain name, without
/// following any compression pointer.
fn parse_segment<'a>(
    mut bytes: &'a [u8],
    buffer: &mut NameBuf,
) -> Result<(Option<u16>, &'a [u8]), ParseError> {
    loop {
        match *bytes {
            [0, ref rest @ ..] => {
                // Found the root, stop.
                buffer.append_bytes(&[0u8]);
                return Ok((None, rest));
            }

            [l, ..] if l < 64 => {
                // This looks like a regular label.

                if bytes.len() < 1 + l as usize {
                    // The input doesn't contain the whole label.
                    return Err(ParseError);
                } else if 255 - buffer.size < 2 + l {
                    // The output name would exceed 254 bytes (this isn't
                    // the root label, so it can't fill the 255th byte).
                    return Err(ParseError);
                }

                let (label, rest) = bytes.split_at(1 + l as usize);
                buffer.append_bytes(label);
                bytes = rest;
            }

            [hi, lo, ref rest @ ..] if hi >= 0xC0 => {
                let pointer = u16::from_be_bytes([hi, lo]);

                // NOTE: We don't verify the pointer here, that's left to
                // the caller (since they have to actually use it).
                return Ok((Some(pointer & 0x3FFF), rest));
            }

            _ => return Err(ParseError),
        }
    }
}

//--- Parsing from bytes

impl<'a> SplitBytes<'a> for NameBuf {
    fn split_bytes(bytes: &'a [u8]) -> Result<(Self, &'a [u8]), ParseError> {
        <&Name>::split_bytes(bytes)
            .map(|(name, rest)| (NameBuf::copy_from(name), rest))
    }
}

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

//--- Building into byte sequences

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

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

//--- Interaction

impl NameBuf {
    /// Append bytes to this buffer.
    ///
    /// This is an internal convenience function used while building buffers.
    fn append_bytes(&mut self, bytes: &[u8]) {
        self.buffer[self.size as usize..][..bytes.len()]
            .copy_from_slice(bytes);
        self.size += bytes.len() as u8;
    }

    /// Append a label to this buffer.
    ///
    /// This is an internal convenience function used while building buffers.
    fn append_label(&mut self, label: &Label) {
        self.append_bytes(label.as_bytes());
    }
}

//--- Access to the underlying 'Name'

impl Deref for NameBuf {
    type Target = Name;

    fn deref(&self) -> &Self::Target {
        let name = &self.buffer[..self.size as usize];
        // SAFETY: A 'NameBuf' always contains a valid 'Name'.
        unsafe { Name::from_bytes_unchecked(name) }
    }
}

impl DerefMut for NameBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        let name = &mut self.buffer[..self.size as usize];
        // SAFETY: A 'NameBuf' always contains a valid 'Name'.
        unsafe { Name::from_bytes_unchecked_mut(name) }
    }
}

impl Borrow<Name> for NameBuf {
    fn borrow(&self) -> &Name {
        self
    }
}

impl BorrowMut<Name> for NameBuf {
    fn borrow_mut(&mut self) -> &mut Name {
        self
    }
}

impl AsRef<Name> for NameBuf {
    fn as_ref(&self) -> &Name {
        self
    }
}

impl AsMut<Name> for NameBuf {
    fn as_mut(&mut self) -> &mut Name {
        self
    }
}

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

impl PartialEq for NameBuf {
    fn eq(&self, that: &Self) -> bool {
        **self == **that
    }
}

impl Eq for NameBuf {}

impl PartialOrd for NameBuf {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for NameBuf {
    fn cmp(&self, other: &Self) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl Hash for NameBuf {
    fn hash<H: Hasher>(&self, state: &mut H) {
        (**self).hash(state)
    }
}

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

impl fmt::Debug for NameBuf {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        (**self).fmt(f)
    }
}

//--- Parsing from strings

impl NameBuf {
    /// Parse a domain name from the zonefile format.
    pub fn parse_str(mut s: &[u8]) -> Result<(Self, &[u8]), NameParseError> {
        // The buffer we'll fill into.
        let mut this = Self::empty();

        // Parse label by label.
        loop {
            let (label, rest) = LabelBuf::parse_str(s)?;

            if 255 - this.size < 1 + label.as_bytes().len() as u8 {
                return Err(NameParseError::Overlong);
            }
            this.append_label(&label);

            match *rest {
                [b' ' | b'\n' | b'\r' | b'\t', ..] | [] => {
                    s = rest;
                    break;
                }
                [b'.', ref rest @ ..] => s = rest,
                _ => return Err(NameParseError::InvalidChar),
            }
        }
        this.append_label(Label::ROOT);

        Ok((this, s))
    }
}

impl FromStr for NameBuf {
    type Err = NameParseError;

    /// Parse a name from a string.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match Self::parse_str(s.as_bytes()) {
            Ok((this, &[])) => Ok(this),
            Ok(_) => Err(NameParseError::InvalidChar),
            Err(err) => Err(err),
        }
    }
}

//--- Serialize, Deserialize

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

#[cfg(feature = "serde")]
impl<'a> serde::Deserialize<'a> for NameBuf {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        if deserializer.is_human_readable() {
            struct V;

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

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

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

            struct NV;

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

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("an absolute domain name")
                }

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

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

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

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

                fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
                where
                    E: serde::de::Error,
                {
                    NameBuf::parse_bytes(v).map_err(|_| E::custom("misformatted domain name for the DNS wire format"))
                }
            }

            struct NV;

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

                fn expecting(
                    &self,
                    f: &mut fmt::Formatter<'_>,
                ) -> fmt::Result {
                    f.write_str("an absolute domain name")
                }

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

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

#[cfg(feature = "serde")]
impl<'a> serde::Deserialize<'a> for std::boxed::Box<Name> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'a>,
    {
        NameBuf::deserialize(deserializer)
            .map(|this| this.unsized_copy_into())
    }
}

//------------ NameParseError ------------------------------------------------

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

    /// The name contained an invalid character.
    ///
    /// Valid names contain any of the following characters:
    /// - ASCII alphanumeric characters
    /// - `-`, `_`, `*` (within labels)
    /// - `.` (between labels)
    /// - Correctly escaped characters
    InvalidChar,

    /// A label in the name could not be parsed.
    Label(LabelParseError),
}

impl From<LabelParseError> for NameParseError {
    fn from(value: LabelParseError) -> Self {
        Self::Label(value)
    }
}

// TODO(1.81.0): Use 'core::error::Error' instead.
#[cfg(feature = "std")]
impl std::error::Error for NameParseError {}

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