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
use core::convert::TryFrom;
use core::fmt::{self, Display, Formatter, Write};

use byteorder::{ByteOrder, NetworkEndian};

use crate::r#const::{CLASS, OPCODE, RCODE, TYPE};
use crate::view::{
    rdata::{
        Caa, CaaTag, CaaValue, CompressibleName, InAaaa, InAddress, Malformed, Mx, Soa, Txt,
        Unknown,
    },
    CharacterString, Class, Extension, Header, Label, Message, Name, Question, Record, Type,
};

pub trait Format {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result;
}

impl fmt::Write for Wrapper<'_, '_> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        (self.f)(self.i, &mut self.p, s)
    }
}

pub type Writer = dyn Fn(&mut dyn fmt::Write, &mut Position, &str) -> fmt::Result;

fn plain(w: &mut dyn fmt::Write, _: &mut Position, s: &str) -> fmt::Result {
    w.write_str(s)
}

pub struct Wrapper<'i, 'f> {
    i: &'i mut dyn fmt::Write,
    p: Position,
    f: &'f Writer,
}

impl<'i, 'f> Wrapper<'i, 'f> {
    pub fn plain(i: &'i mut dyn fmt::Write) -> Self {
        Self::with_writer(i, &plain)
    }
    pub fn with_writer(i: &'i mut dyn fmt::Write, f: &'f Writer) -> Self {
        Self {
            i,
            p: Position::default(),
            f,
        }
    }
}

use self::HeaderPosition::*;
use self::MainPosition::*;
use self::QuestionPosition::*;
use self::RecordPosition::*;
use self::SectionPosition::*;

#[derive(Debug, Clone, Default)]
pub struct Position {
    pub main: Option<MainPosition>,
    pub header: Option<HeaderPosition>,
    pub section: Option<SectionPosition>,
    pub question: Option<QuestionPosition>,
    pub record: Option<RecordPosition>,
}

struct ScopedPosition<'w, 'i, 'f> {
    w: &'w mut Wrapper<'i, 'f>,
    old_position: Position,
}

impl<'w, 'i, 'f> From<&'w mut Wrapper<'i, 'f>> for ScopedPosition<'w, 'i, 'f> {
    fn from(w: &'w mut Wrapper<'i, 'f>) -> Self {
        let old_position = w.p.clone();

        Self { w, old_position }
    }
}

impl Drop for ScopedPosition<'_, '_, '_> {
    fn drop(&mut self) {
        self.w.p = self.old_position.clone();
    }
}

impl ScopedPosition<'_, '_, '_> {
    pub fn main(&mut self, m: impl Into<Option<MainPosition>>) -> &mut Self {
        self.w.p.main = m.into();

        self
    }
    pub fn header(&mut self, h: impl Into<Option<HeaderPosition>>) -> &mut Self {
        self.w.p.header = h.into();

        self
    }
    pub fn section(&mut self, s: impl Into<Option<SectionPosition>>) -> &mut Self {
        self.w.p.section = s.into();

        self
    }
    pub fn question(&mut self, q: impl Into<Option<QuestionPosition>>) -> &mut Self {
        self.w.p.question = q.into();

        self
    }
    pub fn record(&mut self, r: impl Into<Option<RecordPosition>>) -> &mut Self {
        self.w.p.record = r.into();

        self
    }
}

#[derive(Debug, Clone)]
pub enum MainPosition {
    Header,
    EdnsHeader,
    Qd,
    An,
    Ns,
    Ar,
}

#[derive(Debug, Clone)]
pub enum HeaderPosition {
    Rcode,
    Id,
    Opcode,
    Qdcount,
    Ancount,
    Nscount,
    Arcount,
    Flag,
}

#[derive(Debug, Clone)]
pub enum SectionPosition {
    Heading,
    QuestionLine,
    RecordLine,
    EdnsPlaceholder,
}

#[derive(Debug, Clone)]
pub enum QuestionPosition {
    Qname,
    Qclass,
    Qtype,
}

#[derive(Debug, Clone)]
pub enum RecordPosition {
    Name,
    Ttl,
    Class,
    Type,
    Rdata,
}

pub struct Plain<'i>(pub &'i dyn Format);

impl Display for Plain<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let mut w = Wrapper::plain(f);

        Format::fmt(self.0, &mut w)
    }
}

pub struct Pretty<'i, 'f>(pub &'i dyn Format, pub &'f Writer);

impl Display for Pretty<'_, '_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        let mut w = Wrapper::with_writer(f, self.1);

        Format::fmt(self.0, &mut w)
    }
}

impl Format for Message<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut p = ScopedPosition::from(w);
        p.main(Header);

        write!(p.header(None).w, ";; ")?;

        if let Some(x) = RCODE.name(self.rcode()) {
            write!(p.header(Rcode).w, "{}", x)?;
        } else {
            // FIXME canonical format?
            write!(p.header(Rcode).w, "<{}>", self.rcode())?;
        }

        write!(p.header(None).w, " ")?;
        self.header().fmt(p.w)?;
        writeln!(p.w)?;

        let opt = self.opt();

        if let Some(extension) = opt {
            write!(p.main(EdnsHeader).w, ";; ")?;
            extension.fmt(p.w)?;
            writeln!(p.main(None).w)?;
        }

        writeln!(p.main(Qd).w)?;
        write!(p.section(Heading).w, ";; question section")?;
        writeln!(p.section(None).w)?;

        for question in self.qd() {
            question.fmt(p.section(QuestionLine).w)?;
            writeln!(p.section(None).w)?;
        }

        writeln!(p.main(An).w)?;
        write!(p.section(Heading).w, ";; answer section")?;
        writeln!(p.section(None).w)?;

        for record in self.an() {
            record.fmt(p.section(RecordLine).w)?;
            writeln!(p.section(None).w)?;
        }

        writeln!(p.main(Ns).w)?;
        write!(p.section(Heading).w, ";; authority section")?;
        writeln!(p.section(None).w)?;

        for record in self.ns() {
            record.fmt(p.section(RecordLine).w)?;
            writeln!(p.section(None).w)?;
        }

        writeln!(p.main(Ar).w)?;
        write!(p.section(Heading).w, ";; additional section")?;
        writeln!(p.section(None).w)?;

        for record in self.ar() {
            if opt.map_or(false, |x| x.inner.offset == record.offset) {
                write!(p.section(EdnsPlaceholder).w, "; EDNS OPT RR was here")?;
            } else {
                record.fmt(p.section(RecordLine).w)?;
            }
            writeln!(p.section(None).w)?;
        }

        Ok(())
    }
}

impl Format for Header<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut p = ScopedPosition::from(w);
        p.main(Header);

        write!(p.header(Id).w, "#{}", self.id())?;
        write!(p.header(None).w, " ")?;

        if let Some(x) = OPCODE.name(self.opcode().into()) {
            write!(p.header(Opcode).w, "{}", x)?;
        } else {
            // FIXME canonical format?
            write!(p.header(Opcode).w, "<{}>", self.opcode())?;
        }

        write!(p.header(None).w, " ")?;
        write!(p.header(Qdcount).w, "{}", self.qdcount())?;
        write!(p.header(None).w, " ")?;
        write!(p.header(Ancount).w, "{}", self.ancount())?;
        write!(p.header(None).w, " ")?;
        write!(p.header(Nscount).w, "{}", self.nscount())?;
        write!(p.header(None).w, " ")?;
        write!(p.header(Arcount).w, "{}", self.arcount())?;
        write!(p.header(None).w, " flags")?;

        if self.qr() {
            write!(p.header(None).w, " ")?;
            write!(p.header(Flag).w, "qr")?;
        }
        if self.aa() {
            write!(p.header(None).w, " ")?;
            write!(p.header(Flag).w, "aa")?;
        }
        if self.tc() {
            write!(p.header(None).w, " ")?;
            write!(p.header(Flag).w, "tc")?;
        }
        if self.rd() {
            write!(p.header(None).w, " ")?;
            write!(p.header(Flag).w, "rd")?;
        }
        if self.ra() {
            write!(p.header(None).w, " ")?;
            write!(p.header(Flag).w, "ra")?;
        }

        Ok(())
    }
}

impl Format for Extension<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        write!(w, "EDNS({}) UDP {} flags", self.version(), self.udp())?;

        if self.r#do() {
            write!(w, " do")?;
        }

        Ok(())
    }
}

impl Format for Question<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut p = ScopedPosition::from(w);

        // RFC 3597 § 5
        self.qname().fmt(p.question(Qname).w)?;
        write!(p.question(None).w, " ")?;
        self.qclass().fmt(p.question(Qclass).w)?;
        write!(p.question(None).w, " ")?;
        self.qtype().fmt(p.question(Qtype).w)?;

        Ok(())
    }
}

impl Format for Record<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut p = ScopedPosition::from(w);

        self.name().fmt(p.record(Name).w)?;
        write!(p.record(None).w, " ")?;
        write!(p.record(Ttl).w, "{}", self.ttl())?;
        write!(p.record(None).w, " ")?;
        self.class().fmt(p.record(Class).w)?;
        write!(p.record(None).w, " ")?;
        self.r#type().fmt(p.record(Type).w)?;
        write!(p.record(None).w, " ")?;
        let rdata = self.rdata();
        let rdata: &dyn Format = rdata.as_ref();
        rdata.fmt(p.record(Rdata).w)?;

        Ok(())
    }
}

impl Format for Name<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut first = true;

        for label in self.labels() {
            if first || !label.null() {
                label.fmt(w)?;
                write!(w, ".")?;
            }

            first = false;
        }

        Ok(())
    }
}

impl Format for Label<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        if let Some(value) = self.literal() {
            for &octet in value {
                display_octet(w, octet, |x| match x {
                    b' ' | b';' => OctetStyle::Decimal,
                    b'-' | b'_' => OctetStyle::Identity,
                    x if x.is_ascii_alphanumeric() => OctetStyle::Identity,
                    x if x.is_ascii_graphic() => OctetStyle::PrefixBackslash,
                    _ => OctetStyle::Decimal,
                })?;
            }
        } else {
            unimplemented!();
        }

        Ok(())
    }
}

impl Format for Type<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        if let Some(name) = TYPE.name(self.value()) {
            write!(w, "{}", name)
        } else {
            // RFC 3597 § 5
            write!(w, "TYPE{}", self.value())
        }
    }
}

impl Format for Class<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        if let Some(name) = CLASS.name(self.value()) {
            write!(w, "{}", name)
        } else {
            // RFC 3597 § 5
            write!(w, "CLASS{}", self.value())
        }
    }
}

impl Format for CharacterString<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        write!(w, r#"""#)?;

        for &octet in self.value() {
            display_octet(w, octet, |x| match x {
                b'\\' | b'"' => OctetStyle::Decimal,
                b' ' => OctetStyle::Identity,
                x if x.is_ascii_graphic() => OctetStyle::Identity,
                _ => OctetStyle::Decimal,
            })?;
        }

        write!(w, r#"""#)?;

        Ok(())
    }
}

impl Format for Soa<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        self.mname().fmt(w)?;
        write!(w, " ")?;
        self.rname().fmt(w)?;
        write!(
            w,
            " {} {} {} {} {}",
            self.serial(),
            self.refresh(),
            self.retry(),
            self.expire(),
            self.minimum(),
        )?;

        Ok(())
    }
}

impl Format for Mx<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        write!(w, "{} ", self.preference())?;
        self.exchange().fmt(w)?;

        Ok(())
    }
}

impl Format for Txt<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        for string in self.data() {
            string.fmt(w)?;
            write!(w, " ")?;
        }

        Ok(())
    }
}

impl Format for Caa<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        write!(w, "{} ", self.flags())?;
        self.tag().fmt(w)?;
        write!(w, " ")?;
        self.value().fmt(w)?;

        Ok(())
    }
}

impl Format for CaaTag<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let start = self.offset;
        let stop = start + self.len;

        for i in start..stop {
            display_octet(w, self.source[i], |x| {
                if x.is_ascii_alphanumeric() {
                    OctetStyle::Identity
                } else {
                    OctetStyle::Decimal
                }
            })?;
        }

        Ok(())
    }
}

impl Format for CaaValue<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let start = self.offset;
        let stop = start + self.len;

        write!(w, r#"""#)?;

        for i in start..stop {
            display_octet(w, self.source[i], |x| match x {
                b'\\' | b'"' => OctetStyle::Decimal,
                x if x.is_ascii_graphic() => OctetStyle::Identity,
                _ => OctetStyle::Decimal,
            })?;
        }

        write!(w, r#"""#)?;

        Ok(())
    }
}

impl Format for CompressibleName<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        self.name.fmt(w)
    }
}

impl Format for InAddress<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        write!(
            w,
            "{}.{}.{}.{}",
            self.source[self.offset + 0],
            self.source[self.offset + 1],
            self.source[self.offset + 2],
            self.source[self.offset + 3],
        )
    }
}

impl Format for InAaaa<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        let mut x = [0u16; 8];
        NetworkEndian::read_u16_into(&self.source[self.offset..][..16], &mut x);

        // The one at bit 8 (and hence the use of u16) ensures that we count
        // trailing zeros correctly if all ones have been shifted out.
        let zero = 0x100
            | u16::from(x[0] != 0) << 0
            | u16::from(x[1] != 0) << 1
            | u16::from(x[2] != 0) << 2
            | u16::from(x[3] != 0) << 3
            | u16::from(x[4] != 0) << 4
            | u16::from(x[5] != 0) << 5
            | u16::from(x[6] != 0) << 6
            | u16::from(x[7] != 0) << 7;

        // RFC 5952
        let (start, len) = (0..8)
            .map(|i| (zero >> i).trailing_zeros())
            .enumerate()
            .filter(|(_, n)| *n > 1) // § 4.2.2
            .rev() // § 4.2.3 (leftmost)
            .max_by_key(|(_, n)| *n) // § 4.2.3 (longest)
            .unwrap_or((0, 0));

        let len = usize::try_from(len).expect("len is always ≤ 8");

        for i in 0..start {
            write!(w, "{}{:x}", if i > 0 { ":" } else { "" }, x[i])?;
        }
        if len > 0 {
            write!(w, "::")?;
        }
        for i in (start + len)..8 {
            write!(w, "{:x}{}", x[i], if i < 7 { ":" } else { "" })?;
        }

        Ok(())
    }
}

impl Format for Malformed<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        self.inner.fmt(w)
    }
}

impl Format for Unknown<'_> {
    fn fmt(&self, w: &mut Wrapper) -> fmt::Result {
        // RFC 3597 § 5
        write!(w, "\\# {}", self.len)?;

        let start = self.offset;
        let stop = start + self.len;

        for i in start..stop {
            write!(w, " {:02X}", self.source[i])?;
        }

        Ok(())
    }
}

pub enum OctetStyle {
    Identity,
    PrefixBackslash,
    Decimal,
}

pub fn display_octet(
    sink: &mut Wrapper,
    octet: u8,
    style: impl FnOnce(u8) -> OctetStyle,
) -> fmt::Result {
    // octet as char only makes sense below 80h
    if octet >= 0x80 {
        return write!(sink, "\\{:03}", octet);
    }

    match style(octet) {
        OctetStyle::Identity => write!(sink, "{}", octet as char),
        OctetStyle::PrefixBackslash => write!(sink, "\\{}", octet as char),
        OctetStyle::Decimal => write!(sink, "\\{:03}", octet),
    }
}

#[cfg(test)]
mod test {
    use core::fmt::Write;

    use arrayvec::ArrayString;
    use assert_matches::assert_matches;

    use crate::{view::View, zone::Plain};

    declare_any_error!(AnyError);

    type S12 = ArrayString<[u8; 4096]>;

    macro_rules! assert {
        ($type:ident $source:literal yields $output:literal) => (
            assert_matches!(assert!(@write $type $source), (ref x, Ok(_)) if x == $output);
        );

        ($type:ident $source:literal fails) => (
            assert_matches!(assert!(@write $type $source), (_, Err(_)))
        );

        (@write $type:ident $source:literal) => ({
            let mut sink = S12::default();
            let result = super::$type::view($source, 0..$source.len())
                .map(|(view, _)| write!(&mut sink, "{}", Plain(&view)));

            (sink, result)
        });
    }

    #[test]
    fn record() -> Result<(), AnyError> {
        let mut sink = S12::default();
        let source = b"\0\x00\x02\x00\x01\x00\x00\x00\x00\x00\x00";
        let (record, _) = super::Record::view(source, 0..source.len())?;
        write!(&mut sink, "{}", Plain(&record))?;

        assert_eq!(&*sink, r#". 0 IN NS \# 0"#);

        Ok(())
    }

    #[test]
    fn soa() {
        assert!(Soa b"\x05daria\x03daz\x03cat\0\x05delan\x07azabani\x03com\0\x78\x57\xF7\xD8\x00\x00\x02\x58\x00\x00\x00\x3C\x00\x1B\xAF\x80\x00\x00\x00\x3C" yields "daria.daz.cat. delan.azabani.com. 2019031000 600 60 1814400 60");
    }

    #[test]
    fn mx() {
        assert!(Mx b"\x00\x0D\x05daria\x03daz\x03cat\0" yields "13 daria.daz.cat.");
    }

    #[test]
    fn txt() {
        assert!(Txt b"\x05hello\x01 \x05world" yields r#""hello" " " "world" "#);
    }

    #[test]
    fn caa() {
        assert!(Caa b"\x80\x05issueletsencrypt.org" yields r#"128 issue "letsencrypt.org""#);
    }

    #[test]
    fn in_address() {
        assert!(InAddress b"\xC0\x00\x02\x00" yields "192.0.2.0");
        assert!(InAddress b"\xC0\x00\x02" fails);
    }

    #[test]
    fn in_aaaa() {
        // RFC 5952 § 4 > RFC 4291 § 2.2
        // § 4.1 leading zeros MUST be suppressed
        assert!(InAaaa b"\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01" yields "1:1:1:1:1:1:1:1");
        // § 4.2.1 double colon MUST consume all adjacent zeros
        assert!(InAaaa b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01" yields "::1");
        assert!(InAaaa b"\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\x01" yields "1::1");
        assert!(InAaaa b"\0\x01\0\0\0\0\0\0\0\0\0\0\0\0\0\0" yields "1::");
        // § 4.2.2 double colon MUST cover two or more words
        assert!(InAaaa b"\0\0\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01" yields "0:1:1:1:1:1:1:1");
        assert!(InAaaa b"\0\x01\0\0\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01" yields "1:0:1:1:1:1:1:1");
        assert!(InAaaa b"\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01\0\x01\0\0" yields "1:1:1:1:1:1:1:0");
        // § 4.2.3 double colon MUST cover leftmost longest run
        assert!(InAaaa b"\0\0\0\0\0\0\0\x01\0\x01\0\0\0\0\0\0" yields "::1:1:0:0:0");
        assert!(InAaaa b"\0\0\0\0\0\0\0\x01\0\0\0\0\0\0\0\x01" yields "::1:0:0:0:1");
        assert!(InAaaa b"\0\x01\0\0\0\0\0\0\0\x01\0\0\0\0\0\0" yields "1::1:0:0:0");
        assert!(InAaaa b"\0\x01\0\0\0\0\0\x01\0\x01\0\0\0\0\0\x01" yields "1::1:1:0:0:1");
        // § 4.3 hexadecimal digits MUST be in lowercase form
        assert!(InAaaa b"\0\xAA\0\xBB\0\xCC\0\xDD\0\xEE\0\xFF\0\0\0\0" yields "aa:bb:cc:dd:ee:ff::");
        // § 5 mixed notation for IPv4-in-lowest-32 is RECOMMENDED (well-known) or OPTIONAL (otherwise)
        assert!(InAaaa b"\0\0\0\0\0\0\0\0\0\0\xFF\xFF\x7F\0\0\x01" yields "::ffff:7f00:1");

        // nonymous test suite
        assert!(InAaaa b"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\x01" yields "::1"); // 7l
        assert!(InAaaa b"\x20\x01\x0D\xB8\xAA\xAA\0\0\0\0\0\0\0\0\0\0" yields "2001:db8:aaaa::"); // 5r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\xAA\xAA\0\0\0\0\0\0\0\0" yields "2001:db8:0:aaaa::"); // 1 4r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\xAA\xAA\0\0\0\0\0\0" yields "2001:db8:0:0:aaaa::"); // 2 3r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\xAA\xAA\xAA\xAA\0\0\0\0" yields "2001:db8::aaaa:aaaa:0:0"); // 2 2r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\0\0\xAA\xAA\0\0\0\0" yields "2001:db8::aaaa:0:0"); // 3 2r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\0\0\0\0\xAA\xAA\0\0" yields "2001:db8::aaaa:0"); // 4 1r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\0\0\0\0\0\0\xAA\xAA" yields "2001:db8::aaaa"); // 5
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\0\0\0\0\0\0\0\0" yields "2001:db8::"); // 6r
        assert!(InAaaa b"\x20\x01\x0D\xB8\0\0\0\0\0\0\0\0\0\0\0" fails);
    }

    #[test]
    fn unknown() {
        assert!(Unknown b"" yields "\\# 0");
        assert!(Unknown b"\xFF" yields "\\# 1 FF");
    }
}

#[cfg(all(test, feature = "bench"))]
mod bench {
    extern crate test;

    use alloc::string::String;
    use core::fmt::Write;
    use test::bench::black_box as b;
    use test::Bencher;

    use crate::{
        view::{Message, View},
        zone::Plain,
    };

    declare_any_error!(AnyError);

    #[bench]
    fn response(bencher: &mut Bencher) -> Result<(), AnyError> {
        let source = include_bytes!("../examples/response.dns");
        let (message, _) = Message::view(source, 0..source.len())?;

        bencher.iter(|| -> Result<usize, AnyError> {
            let mut out = String::new();
            write!(out, "{}", Plain(b(&message)))?;

            Ok(out.len())
        });

        Ok(())
    }
}