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
//! Character strings.
//!
//! The somewhat ill-named `<character-string>` is defined in [RFC 1035] as
//! binary information of up to 255 octets. As such, it doesn’t necessarily
//! contain (ASCII-) characters nor is it a string in a Rust-sense.
//!
//! An existing, immutable character string is represented by the type
//! [`CharStr`]. The type [`CharStrBuilder`] allows constructing a character
//! string from individual octets or octets slices.
//!
//! In wire-format, character strings are encoded as one octet giving the
//! length followed by the actual data in that many octets. The length octet
//! is not part of the content wrapped by [`CharStr`], it contains the data
//! only.
//!
//! A [`CharStr`] can be constructed from a string via the `FromStr`
//! trait. In this case, the string must consist only of printable ASCII
//! characters. Space and double quote are allowed and will be accepted with
//! their ASCII value. Other values need to be escaped via a backslash
//! followed by the three-digit decimal representation of the value. In
//! addition, a backslash followed by a non-digit printable ASCII character
//! is accepted, too, with the ASCII value of this character used.
//!
//! [RFC 1035]: https://tools.ietf.org/html/rfc1035

use super::cmp::CanonicalOrd;
use super::scan::{BadSymbol, Scanner, Symbol, SymbolCharsError};
use super::wire::{Compose, ParseError};
#[cfg(feature = "bytes")]
use bytes::BytesMut;
use core::{cmp, fmt, hash, str};
use octseq::builder::FreezeBuilder;
#[cfg(feature = "serde")]
use octseq::serde::{DeserializeOctets, SerializeOctets};
use octseq::{
    EmptyBuilder, FromBuilder, IntoBuilder, Octets, OctetsBuilder,
    OctetsFrom, Parser, ShortBuf, Truncate,
};
#[cfg(feature = "std")]
use std::vec::Vec;

//------------ CharStr -------------------------------------------------------

/// The content of a DNS character string.
///
/// A character string consists of up to 255 octets of binary data. This type
/// wraps an octets sequence. It is guaranteed to always be at most 255 octets
/// in length. It derefs into the underlying octets for working with the
/// content in a familiar way.
///
/// As per [RFC 1035], character strings compare ignoring ASCII case.
/// `CharStr`’s implementations of the `std::cmp` traits act accordingly.
///
/// [RFC 1035]: https://tools.ietf.org/html/rfc1035
#[derive(Clone)]
pub struct CharStr<Octs: ?Sized>(Octs);

impl CharStr<()> {
    /// Character strings have a maximum length of 255 octets.
    pub const MAX_LEN: usize = 255;
}

impl<Octs: ?Sized> CharStr<Octs> {
    /// Creates a new empty character string.
    #[must_use]
    pub fn empty() -> Self
    where
        Octs: From<&'static [u8]>,
    {
        CharStr(b"".as_ref().into())
    }

    /// Creates a new character string from an octets value.
    ///
    /// Returns succesfully if `octets` can indeed be used as a
    /// character string, i.e., it is not longer than 255 bytes.
    pub fn from_octets(octets: Octs) -> Result<Self, CharStrError>
    where
        Octs: AsRef<[u8]> + Sized,
    {
        CharStr::check_slice(octets.as_ref())?;
        Ok(unsafe { Self::from_octets_unchecked(octets) })
    }

    /// Creates a character string from octets without length check.
    ///
    /// # Safety
    ///
    /// The caller has to make sure that `octets` is at most 255 octets
    /// long. Otherwise, the behavior is undefined.
    pub unsafe fn from_octets_unchecked(octets: Octs) -> Self
    where
        Octs: Sized,
    {
        CharStr(octets)
    }
}

impl CharStr<[u8]> {
    /// Creates a character string from an octets slice.
    pub fn from_slice(slice: &[u8]) -> Result<&Self, CharStrError> {
        Self::check_slice(slice)?;
        Ok(unsafe { Self::from_slice_unchecked(slice) })
    }

    /// Creates a new empty character string on an octets slice.
    #[must_use]
    pub fn empty_slice() -> &'static Self {
        unsafe { Self::from_slice_unchecked(b"".as_ref()) }
    }

    /// Creates a character string from an octets slice without checking.
    ///
    /// # Safety
    ///
    /// The caller has to make sure that `octets` is at most 255 octets
    /// long. Otherwise, the behaviour is undefined.
    #[must_use]
    pub unsafe fn from_slice_unchecked(slice: &[u8]) -> &Self {
        &*(slice as *const [u8] as *const Self)
    }

    /// Creates a character string from a mutable slice without checking.
    ///
    /// # Safety
    ///
    /// The caller has to make sure that `octets` is at most 255 octets
    /// long. Otherwise, the behaviour is undefined.
    unsafe fn from_slice_mut_unchecked(slice: &mut [u8]) -> &mut Self {
        &mut *(slice as *mut [u8] as *mut Self)
    }

    /// Checks whether an octets slice contains a correct character string.
    fn check_slice(slice: &[u8]) -> Result<(), CharStrError> {
        if slice.len() > CharStr::MAX_LEN {
            Err(CharStrError)
        } else {
            Ok(())
        }
    }
}

impl<Octs: ?Sized> CharStr<Octs> {
    /// Creates a new empty builder for this character string type.
    #[must_use]
    pub fn builder() -> CharStrBuilder<Octs::Builder>
    where
        Octs: IntoBuilder,
        Octs::Builder: EmptyBuilder,
    {
        CharStrBuilder::new()
    }

    /// Converts the character string into a builder.
    pub fn into_builder(self) -> CharStrBuilder<Octs::Builder>
    where
        Octs: IntoBuilder + Sized,
        <Octs as IntoBuilder>::Builder: AsRef<[u8]>,
    {
        unsafe {
            CharStrBuilder::from_builder_unchecked(IntoBuilder::into_builder(
                self.0,
            ))
        }
    }

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

    /// Returns a character string atop a slice of the content.
    pub fn for_slice(&self) -> &CharStr<[u8]>
    where
        Octs: AsRef<[u8]>,
    {
        unsafe { CharStr::from_slice_unchecked(self.0.as_ref()) }
    }

    /// Returns a character string atop a mutable slice of the content.
    pub fn for_slice_mut(&mut self) -> &mut CharStr<[u8]>
    where
        Octs: AsMut<[u8]>,
    {
        unsafe { CharStr::from_slice_mut_unchecked(self.0.as_mut()) }
    }

    /// Returns a reference to a slice of the character string’s data.
    pub fn as_slice(&self) -> &[u8]
    where
        Octs: AsRef<[u8]>,
    {
        self.0.as_ref()
    }

    /// Returns a reference to a mutable slice of the character string’s data.
    pub fn as_slice_mut(&mut self) -> &mut [u8]
    where
        Octs: AsMut<[u8]>,
    {
        self.0.as_mut()
    }

    /// Parses a character string from the beginning of a parser.
    pub fn parse<'a, Src: Octets<Range<'a> = Octs> + ?Sized>(
        parser: &mut Parser<'a, Src>,
    ) -> Result<Self, ParseError>
    where
        Octs: Sized,
    {
        let len = parser.parse_u8()? as usize;
        parser
            .parse_octets(len)
            .map(|bytes| unsafe { Self::from_octets_unchecked(bytes) })
            .map_err(Into::into)
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> CharStr<Octs> {
    /// Returns the length of the character string.
    ///
    /// This is the length of the content only, i.e., without the extra
    /// length octet added for the wire format.
    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    /// Returns whether the character string is empty.
    pub fn is_empty(&self) -> bool {
        self.as_slice().is_empty()
    }

    /// Returns an iterator over the octets of the character string.
    pub fn iter(&self) -> Iter {
        Iter {
            octets: self.as_slice(),
        }
    }
}

impl CharStr<[u8]> {
    /// Skips over a character string at the beginning of a parser.
    pub fn skip<Src: Octets + ?Sized>(
        parser: &mut Parser<Src>,
    ) -> Result<(), ParseError> {
        let len = parser.parse_u8()?;
        parser.advance(len.into()).map_err(Into::into)
    }
}

impl<Octs: AsRef<[u8]> + ?Sized> CharStr<Octs> {
    /// Returns the length of the wire format representation.
    pub fn compose_len(&self) -> u16 {
        u16::try_from(self.0.as_ref().len() + 1).expect("long charstr")
    }

    /// Appends the wire format representation to an octets builder.
    pub fn compose<Target: OctetsBuilder + ?Sized>(
        &self,
        target: &mut Target,
    ) -> Result<(), Target::AppendError> {
        u8::try_from(self.0.as_ref().len())
            .expect("long charstr")
            .compose(target)?;
        target.append_slice(self.0.as_ref())
    }
}

impl<Octets> CharStr<Octets> {
    /// Scans the presentation format from a scanner.
    pub fn scan<S: Scanner<Octets = Octets>>(
        scanner: &mut S,
    ) -> Result<Self, S::Error> {
        scanner.scan_charstr()
    }
}

//--- OctetsFrom

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

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

//--- FromStr

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

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // Most likely, everything is ASCII so take `s`’s length as capacity.
        let mut builder =
            CharStrBuilder::<<Octets as FromBuilder>::Builder>::with_capacity(
                s.len(),
            );
        let mut chars = s.chars();
        while let Some(symbol) = Symbol::from_chars(&mut chars)? {
            if builder.len() == CharStr::MAX_LEN {
                return Err(FromStrError::LongString);
            }
            builder.append_slice(&[symbol.into_octet()?])?
        }
        Ok(builder.finish())
    }
}

//--- AsRef and AsMut
//
// No Borrow as character strings compare ignoring case.

impl<Octets: AsRef<U> + ?Sized, U: ?Sized> AsRef<U> for CharStr<Octets> {
    fn as_ref(&self) -> &U {
        self.0.as_ref()
    }
}

impl<Octets: AsMut<U> + ?Sized, U: ?Sized> AsMut<U> for CharStr<Octets> {
    fn as_mut(&mut self) -> &mut U {
        self.0.as_mut()
    }
}

//--- PartialEq and Eq

impl<T, U> PartialEq<U> for CharStr<T>
where
    T: AsRef<[u8]> + ?Sized,
    U: AsRef<[u8]> + ?Sized,
{
    fn eq(&self, other: &U) -> bool {
        self.as_slice().eq_ignore_ascii_case(other.as_ref())
    }
}

impl<T: AsRef<[u8]> + ?Sized> Eq for CharStr<T> {}

//--- PartialOrd, Ord, and CanonicalOrd

impl<T, U> PartialOrd<U> for CharStr<T>
where
    T: AsRef<[u8]> + ?Sized,
    U: AsRef<[u8]> + ?Sized,
{
    fn partial_cmp(&self, other: &U) -> Option<cmp::Ordering> {
        self.0
            .as_ref()
            .iter()
            .map(u8::to_ascii_lowercase)
            .partial_cmp(other.as_ref().iter().map(u8::to_ascii_lowercase))
    }
}

impl<T: AsRef<[u8]> + ?Sized> Ord for CharStr<T> {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.0
            .as_ref()
            .iter()
            .map(u8::to_ascii_lowercase)
            .cmp(other.0.as_ref().iter().map(u8::to_ascii_lowercase))
    }
}

impl<T, U> CanonicalOrd<CharStr<U>> for CharStr<T>
where
    T: AsRef<[u8]> + ?Sized,
    U: AsRef<[u8]> + ?Sized,
{
    fn canonical_cmp(&self, other: &CharStr<U>) -> cmp::Ordering {
        match self.0.as_ref().len().cmp(&other.0.as_ref().len()) {
            cmp::Ordering::Equal => {}
            other => return other,
        }
        self.as_slice().cmp(other.as_slice())
    }
}

//--- Hash

impl<T: AsRef<[u8]> + ?Sized> hash::Hash for CharStr<T> {
    fn hash<H: hash::Hasher>(&self, state: &mut H) {
        self.0
            .as_ref()
            .iter()
            .map(u8::to_ascii_lowercase)
            .for_each(|ch| ch.hash(state))
    }
}

//--- Display and Debug

impl<T: AsRef<[u8]> + ?Sized> fmt::Display for CharStr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for &ch in self.0.as_ref() {
            fmt::Display::fmt(&Symbol::from_octet(ch), f)?;
        }
        Ok(())
    }
}

impl<T: AsRef<[u8]> + ?Sized> fmt::LowerHex for CharStr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for ch in self.0.as_ref() {
            write!(f, "{:02x}", ch)?;
        }
        Ok(())
    }
}

impl<T: AsRef<[u8]> + ?Sized> fmt::UpperHex for CharStr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for ch in self.0.as_ref() {
            write!(f, "{:02X}", ch)?;
        }
        Ok(())
    }
}

impl<T: AsRef<[u8]> + ?Sized> fmt::Debug for CharStr<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_tuple("CharStr")
            .field(&format_args!("{}", self))
            .finish()
    }
}

//--- IntoIterator

impl<T: AsRef<[u8]>> IntoIterator for CharStr<T> {
    type Item = u8;
    type IntoIter = IntoIter<T>;

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

impl<'a, T: AsRef<[u8]> + ?Sized + 'a> IntoIterator for &'a CharStr<T> {
    type Item = u8;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self.0.as_ref())
    }
}

//--- Serialize and Deserialize

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

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

        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: OctetsBuilder
                + FreezeBuilder<Octets = Octets>
                + EmptyBuilder
                + AsRef<[u8]>,
        {
            type Value = CharStr<Octets>;

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

            fn visit_str<E: serde::de::Error>(
                self,
                v: &str,
            ) -> Result<Self::Value, E> {
                CharStr::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| {
                    CharStr::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| {
                    CharStr::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: OctetsBuilder
                + FreezeBuilder<Octets = Octets>
                + EmptyBuilder
                + AsRef<[u8]>,
        {
            type Value = CharStr<Octets>;

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

            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(
            "CharStr",
            NewtypeVisitor(PhantomData),
        )
    }
}

//------------ CharStrBuilder ------------------------------------------------

/// A builder for a character string.
///
/// This type wraps an [`OctetsBuilder`] and in turn implements the
/// [`OctetsBuilder`] trait, making sure that the content cannot grow beyond
/// the 255 octet limit of a character string.
#[derive(Clone)]
pub struct CharStrBuilder<Builder>(Builder);

impl<Builder: EmptyBuilder> CharStrBuilder<Builder> {
    /// Creates a new empty builder with default capacity.
    #[must_use]
    pub fn new() -> Self {
        CharStrBuilder(Builder::empty())
    }

    /// Creates a new empty builder with the given capacity.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Self {
        CharStrBuilder(Builder::with_capacity(capacity))
    }
}

impl<Builder: OctetsBuilder + AsRef<[u8]>> CharStrBuilder<Builder> {
    /// Creates a character string builder from an octet sequence unchecked.
    ///
    /// Since the buffer may already be longer than it is allowed to be, this
    /// is unsafe.
    unsafe fn from_builder_unchecked(builder: Builder) -> Self {
        CharStrBuilder(builder)
    }

    /// Creates a character string builder from an octet sequence.
    ///
    /// If the octet sequence is longer than 255 octets, an error is
    /// returned.
    pub fn from_builder(builder: Builder) -> Result<Self, CharStrError> {
        if builder.as_ref().len() > CharStr::MAX_LEN {
            Err(CharStrError)
        } else {
            Ok(unsafe { Self::from_builder_unchecked(builder) })
        }
    }
}

#[cfg(feature = "std")]
impl CharStrBuilder<Vec<u8>> {
    /// Creates a new empty characater string builder atop an octets vec.
    #[must_use]
    pub fn new_vec() -> Self {
        Self::new()
    }

    /// Creates a new empty builder atop an octets vec with a given capacity.
    #[must_use]
    pub fn vec_with_capacity(capacity: usize) -> Self {
        Self::with_capacity(capacity)
    }
}

#[cfg(feature = "bytes")]
impl CharStrBuilder<BytesMut> {
    /// Creates a new empty builder for a bytes value.
    pub fn new_bytes() -> Self {
        Self::new()
    }

    /// Creates a new empty builder for a bytes value with a given capacity.
    pub fn bytes_with_capacity(capacity: usize) -> Self {
        Self::with_capacity(capacity)
    }
}

impl<Builder> CharStrBuilder<Builder> {
    /// Returns an octet slice of the string assembled so far.
    pub fn as_slice(&self) -> &[u8]
    where
        Builder: AsRef<[u8]>,
    {
        self.0.as_ref()
    }

    /// Converts the builder into an imutable character string.
    pub fn finish(self) -> CharStr<Builder::Octets>
    where
        Builder: FreezeBuilder,
    {
        unsafe { CharStr::from_octets_unchecked(self.0.freeze()) }
    }
}

impl<Builder: AsRef<[u8]>> CharStrBuilder<Builder> {
    /// Returns the length of the assembled character string.
    ///
    /// This is the length of the content only, i.e., without the extra
    /// length octet added for the wire format.
    pub fn len(&self) -> usize {
        self.as_slice().len()
    }

    /// Returns whether the character string is empty.
    pub fn is_empty(&self) -> bool {
        self.as_slice().is_empty()
    }
}

//--- Default

impl<Builder: EmptyBuilder> Default for CharStrBuilder<Builder> {
    fn default() -> Self {
        Self::new()
    }
}

//--- OctetsBuilder and Truncate

impl<Builder> OctetsBuilder for CharStrBuilder<Builder>
where
    Builder: OctetsBuilder + AsRef<[u8]>,
{
    type AppendError = ShortBuf;

    fn append_slice(
        &mut self,
        slice: &[u8],
    ) -> Result<(), Self::AppendError> {
        if self.0.as_ref().len() + slice.len() > CharStr::MAX_LEN {
            return Err(ShortBuf);
        }
        self.0.append_slice(slice).map_err(Into::into)
    }
}

impl<Builder: Truncate> Truncate for CharStrBuilder<Builder> {
    fn truncate(&mut self, len: usize) {
        self.0.truncate(len)
    }
}

//--- AsRef and AsMut

impl<Builder: AsRef<[u8]>> AsRef<[u8]> for CharStrBuilder<Builder> {
    fn as_ref(&self) -> &[u8] {
        self.0.as_ref()
    }
}

impl<Builder: AsMut<[u8]>> AsMut<[u8]> for CharStrBuilder<Builder> {
    fn as_mut(&mut self) -> &mut [u8] {
        self.0.as_mut()
    }
}

//------------ IntoIter ------------------------------------------------------

/// The iterator type for `IntoIterator` for a character string itself.
pub struct IntoIter<T> {
    octets: T,
    len: usize,
    pos: usize,
}

impl<T: AsRef<[u8]>> IntoIter<T> {
    pub(crate) fn new(octets: T) -> Self {
        IntoIter {
            len: octets.as_ref().len(),
            octets,
            pos: 0,
        }
    }
}

impl<T: AsRef<[u8]>> Iterator for IntoIter<T> {
    type Item = u8;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos == self.len {
            None
        } else {
            let res = self.octets.as_ref()[self.pos];
            self.pos += 1;
            Some(res)
        }
    }
}

//------------ Iter ----------------------------------------------------------

/// The iterator type for `IntoIterator` for a reference to a character string.
pub struct Iter<'a> {
    octets: &'a [u8],
}

impl<'a> Iter<'a> {
    pub(crate) fn new(octets: &'a [u8]) -> Self {
        Iter { octets }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = u8;

    fn next(&mut self) -> Option<Self::Item> {
        let (res, octets) = self.octets.split_first()?;
        self.octets = octets;
        Some(*res)
    }
}

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

//------------ CharStrError --------------------------------------------------

/// A byte sequence does not represent a valid character string.
///
/// This can only mean that the sequence is longer than 255 bytes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct CharStrError;

impl fmt::Display for CharStrError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("long character string")
    }
}

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

//------------ FromStrError --------------------------------------------

/// An error happened when converting a Rust string to a DNS character string.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum FromStrError {
    /// A character string has more than 255 octets.
    LongString,

    SymbolChars(SymbolCharsError),

    /// An illegal character was encountered.
    ///
    /// Only printable ASCII characters are allowed.
    BadSymbol(BadSymbol),

    /// The octet builder’s buffer was too short for the data.
    ShortBuf,
}

//--- From

impl From<SymbolCharsError> for FromStrError {
    fn from(err: SymbolCharsError) -> FromStrError {
        FromStrError::SymbolChars(err)
    }
}

impl From<BadSymbol> for FromStrError {
    fn from(err: BadSymbol) -> FromStrError {
        FromStrError::BadSymbol(err)
    }
}

impl From<ShortBuf> for FromStrError {
    fn from(_: ShortBuf) -> FromStrError {
        FromStrError::ShortBuf
    }
}

//--- Display and Error

impl fmt::Display for FromStrError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            FromStrError::LongString => {
                f.write_str("character string with more than 255 octets")
            }
            FromStrError::SymbolChars(ref err) => err.fmt(f),
            FromStrError::BadSymbol(ref err) => err.fmt(f),
            FromStrError::ShortBuf => ShortBuf.fmt(f),
        }
    }
}

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

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

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

    type CharStrRef<'a> = CharStr<&'a [u8]>;

    #[test]
    fn from_slice() {
        assert_eq!(
            CharStr::from_slice(b"01234").unwrap().as_slice(),
            b"01234"
        );
        assert_eq!(CharStr::from_slice(b"").unwrap().as_slice(), b"");
        assert!(CharStr::from_slice(&vec![0; 255]).is_ok());
        assert!(CharStr::from_slice(&vec![0; 256]).is_err());
    }

    #[test]
    fn from_octets() {
        assert_eq!(
            CharStr::from_octets("01234").unwrap().as_slice(),
            b"01234"
        );
        assert_eq!(CharStr::from_octets("").unwrap().as_slice(), b"");
        assert!(CharStr::from_octets(vec![0; 255]).is_ok());
        assert!(CharStr::from_octets(vec![0; 256]).is_err());
    }

    #[test]
    fn from_str() {
        use std::str::{from_utf8, FromStr};

        type Cs = CharStr<Vec<u8>>;

        assert_eq!(Cs::from_str("foo").unwrap().as_slice(), b"foo");
        assert_eq!(Cs::from_str("f\\oo").unwrap().as_slice(), b"foo");
        assert_eq!(Cs::from_str("foo\\112").unwrap().as_slice(), b"foo\x70");
        assert_eq!(
            Cs::from_str("\"foo\\\"2\"").unwrap().as_slice(),
            b"\"foo\"2\""
        );
        assert_eq!(Cs::from_str("06 dii").unwrap().as_slice(), b"06 dii");
        assert!(Cs::from_str("0\\").is_err());
        assert!(Cs::from_str("0\\2").is_err());
        assert!(Cs::from_str("0\\2a").is_err());
        assert!(Cs::from_str("ö").is_err());
        assert!(Cs::from_str("\x06").is_err());
        assert!(Cs::from_str(from_utf8(&[b'a'; 256]).unwrap()).is_err());
    }

    #[test]
    fn parse() {
        let mut parser = Parser::from_static(b"12\x03foo\x02bartail");
        parser.advance(2).unwrap();
        let foo = CharStrRef::parse(&mut parser).unwrap();
        let bar = CharStrRef::parse(&mut parser).unwrap();
        assert_eq!(foo.as_slice(), b"foo");
        assert_eq!(bar.as_slice(), b"ba");
        assert_eq!(parser.peek_all(), b"rtail");

        assert!(
            CharStrRef::parse(&mut Parser::from_static(b"\x04foo")).is_err(),
        )
    }

    #[test]
    fn compose() {
        let mut target = Vec::new();
        let val = CharStr::from_slice(b"foo").unwrap();
        infallible(val.compose(&mut target));
        assert_eq!(target, b"\x03foo".as_ref());

        let mut target = Vec::new();
        let val = CharStr::from_slice(b"").unwrap();
        infallible(val.compose(&mut target));
        assert_eq!(target, &b"\x00"[..]);
    }

    fn are_eq(l: &[u8], r: &[u8]) -> bool {
        CharStr::from_slice(l).unwrap() == CharStr::from_slice(r).unwrap()
    }

    #[test]
    fn eq() {
        assert!(are_eq(b"abc", b"abc"));
        assert!(!are_eq(b"abc", b"def"));
        assert!(!are_eq(b"abc", b"ab"));
        assert!(!are_eq(b"abc", b"abcd"));
        assert!(are_eq(b"ABC", b"abc"));
        assert!(!are_eq(b"ABC", b"def"));
        assert!(!are_eq(b"ABC", b"ab"));
        assert!(!are_eq(b"ABC", b"abcd"));
        assert!(are_eq(b"", b""));
        assert!(!are_eq(b"", b"A"));
    }

    fn is_ord(l: &[u8], r: &[u8], order: cmp::Ordering) {
        assert_eq!(
            CharStr::from_slice(l)
                .unwrap()
                .cmp(CharStr::from_slice(r).unwrap()),
            order
        )
    }

    #[test]
    fn ord() {
        use std::cmp::Ordering::*;

        is_ord(b"abc", b"ABC", Equal);
        is_ord(b"abc", b"a", Greater);
        is_ord(b"abc", b"A", Greater);
        is_ord(b"a", b"BC", Less);
    }

    #[test]
    fn append_slice() {
        let mut o = CharStrBuilder::new_vec();
        o.append_slice(b"foo").unwrap();
        assert_eq!(o.finish().as_slice(), b"foo");

        let mut o = CharStrBuilder::from_builder(vec![0; 254]).unwrap();
        o.append_slice(b"f").unwrap();
        assert_eq!(o.len(), 255);
        assert!(o.append_slice(b"f").is_err());

        let mut o =
            CharStrBuilder::from_builder(vec![b'f', b'o', b'o']).unwrap();
        o.append_slice(b"bar").unwrap();
        assert_eq!(o.as_ref(), b"foobar");
        assert!(o.append_slice(&[0u8; 250][..]).is_err());
        o.append_slice(&[0u8; 249][..]).unwrap();
        assert_eq!(o.len(), 255);
    }

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

        assert_tokens(
            &CharStr::from_octets(vec![b'f', b'o', 0x12])
                .unwrap()
                .compact(),
            &[
                Token::NewtypeStruct { name: "CharStr" },
                Token::ByteBuf(b"fo\x12"),
            ],
        );

        assert_tokens(
            &CharStr::from_octets(vec![b'f', b'o', 0x12])
                .unwrap()
                .readable(),
            &[
                Token::NewtypeStruct { name: "CharStr" },
                Token::Str("fo\\018"),
            ],
        );
    }
}