internet 0.1.0

Network 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
//! ICMPv6 message types and codecs.
//!
//! As defined in [RFC 4443].
//! See the [IANA ICMPv6 Parameters] registry for the complete list.
//!
//! ## Messages
//!
//! * [DestinationUnreachable]
//! * [PacketTooBig]
//! * [TimeExceeded]
//! * [ParameterProblem]
//! * [EchoRequest] / [EchoReply]
//!
//! ## Supporting types
//!
//! * [Type] — the message type.
//! * [Code] — the message code.
//! * [Checksum] — the Internet Checksum.
//!
//! [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
//! [IANA ICMPv6 Parameters]: https://www.iana.org/assignments/icmpv6-parameters

use crate::{Buf, BufError, BufMut, BufResult, Codec, Cursor};

/// An ICMPv6 message.
///
/// Currently covers only the messages defined in [RFC 4443].
/// See the [IANA ICMPv6 Parameters] registry for the complete list.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
/// [IANA ICMPv6 Parameters]: https://www.iana.org/assignments/icmpv6-parameters
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Message {
    /// Destination Unreachable.
    DestinationUnreachable(DestinationUnreachable),
    /// Packet Too Big.
    PacketTooBig(PacketTooBig),
    /// Time Exceed.
    TimeExceeded(TimeExceeded),
    /// Parameter Problem.
    ParameterProblem(ParameterProblem),
    /// Echo.
    EchoRequest(EchoRequest),
    /// Echo Reply.
    EchoReply(EchoReply),
}

impl Codec for Message {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        match self {
            Message::DestinationUnreachable(message) => message.encode(writer, ()),
            Message::PacketTooBig(message) => message.encode(writer, ()),
            Message::TimeExceeded(message) => message.encode(writer, ()),
            Message::ParameterProblem(message) => message.encode(writer, ()),
            Message::EchoRequest(message) => message.encode(writer, ()),
            Message::EchoReply(message) => message.encode(writer, ()),
        }
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let r#type = Type::decode(&mut Cursor::new(&[(reader.peek_u8()?)]), ())?;
        Ok(match r#type {
            Type::DestinationUnreachable => {
                Self::DestinationUnreachable(DestinationUnreachable::decode(reader, ())?)
            }
            Type::PacketTooBig => Self::PacketTooBig(PacketTooBig::decode(reader, ())?),
            Type::TimeExceeded => Self::TimeExceeded(TimeExceeded::decode(reader, ())?),
            Type::ParameterProblem => Self::ParameterProblem(ParameterProblem::decode(reader, ())?),
            Type::EchoRequest => Self::EchoRequest(EchoRequest::decode(reader, ())?),
            Type::EchoReply => Self::EchoReply(EchoReply::decode(reader, ())?),
        })
    }
}

/// An ICMPv6 message type.
///
/// Determines the format of the remaining data, as defined in [RFC 4443, Section 2.1].
/// See the [IANA ICMPv6 Parameters] registry for the complete list.
///
/// [RFC 4443, Section 2.1]: https://datatracker.ietf.org/doc/html/rfc4443#section-2.1
/// [IANA ICMPv6 Parameters]: https://www.iana.org/assignments/icmpv6-parameters
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum Type {
    /// Destination Unreachable.
    DestinationUnreachable = 1,
    /// Packet Too Big.
    PacketTooBig = 2,
    /// Time Exceeded.
    TimeExceeded = 3,
    /// Parameter Problem.
    ParameterProblem = 4,
    /// Echo Request.
    EchoRequest = 128,
    /// Echo Reply.
    EchoReply = 129,
}

impl Codec for Type {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == (Self::DestinationUnreachable as u8) => Ok(Self::DestinationUnreachable),
            x if x == (Self::PacketTooBig as u8) => Ok(Self::PacketTooBig),
            x if x == (Self::TimeExceeded as u8) => Ok(Self::TimeExceeded),
            x if x == (Self::ParameterProblem as u8) => Ok(Self::ParameterProblem),
            x if x == (Self::EchoRequest as u8) => Ok(Self::EchoRequest),
            x if x == (Self::EchoReply as u8) => Ok(Self::EchoReply),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A zero code value.
///
/// Used when the code field is unused.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum NoCode {
    /// Zero
    Zero = 0,
}

impl Codec for NoCode {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            x if x == Self::Zero as u8 => Ok(Self::Zero),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// An ICMPv6 checksum.
///
/// Used to detect data corruption, as defined in [RFC 4443] Section 2.3.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Checksum(pub u16);

impl Checksum {
    /// Calculates the Internet Checksum.
    ///
    /// # Examples
    ///
    /// ```
    /// use internet::icmpv6::Checksum;
    ///
    /// // The checksum field must be zeroed before calculation.
    /// let mut packet = vec![0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01];
    ///
    /// let checksum = Checksum::calculate(&packet);
    /// packet[2..4].copy_from_slice(&checksum.0.to_be_bytes());
    /// ```
    pub fn calculate(data: &[u8]) -> Self {
        let mut sum: u32 = 0;
        let mut i = 0;

        while i + 1 < data.len() {
            sum += u16::from_be_bytes([data[i], data[i + 1]]) as u32;
            i += 2;
        }

        if i < data.len() {
            sum += (data[i] as u32) << 8;
        }

        while sum >> 16 != 0 {
            sum = (sum & 0xFFFF) + (sum >> 16);
        }

        Self(!(sum as u16))
    }
}

impl Codec for Checksum {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        Ok(Self(u16::decode(reader, ())?))
    }
}

/// A Destination Unreachable message.
///
/// Sent when the destination cannot be reached, as defined in [RFC 4443] Section 3.1.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DestinationUnreachable {
    /// The code.
    pub code: DestinationUnreachableCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The original data.
    pub data: Vec<u8>,
}

impl DestinationUnreachable {
    /// The type.
    pub const TYPE: Type = Type::DestinationUnreachable;
    /// Reserved. Must be zero.
    pub const UNUSED: [u8; 4] = [0u8; 4];
}

impl Codec for DestinationUnreachable {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        Self::UNUSED.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Type::DestinationUnreachable => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = DestinationUnreachableCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        match reader.read_array::<4>()? {
            Self::UNUSED => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            data,
        })
    }
}

/// A code for [`DestinationUnreachable`].
///
/// The reason the destination is unreachable.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum DestinationUnreachableCode {
    /// No route to destination.
    NoRouteToDestination = 0,
    /// Communication administratively prohibited.
    CommunicationAdministrativelyProhibited = 1,
    /// Beyond scope of source address.
    BeyondScopeOfSourceAddress = 2,
    /// Address unreachable.
    AddressUnreachable = 3,
    /// Port unreachable.
    PortUnreachable = 4,
    /// Source address failed ingress/egress policy.
    SourceAddressFailedIngressEgressPolicy = 5,
    /// Reject route to destination.
    RejectRouteToDestination = 6,
}

impl Codec for DestinationUnreachableCode {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            0 => Ok(Self::NoRouteToDestination),
            1 => Ok(Self::CommunicationAdministrativelyProhibited),
            2 => Ok(Self::BeyondScopeOfSourceAddress),
            3 => Ok(Self::AddressUnreachable),
            4 => Ok(Self::PortUnreachable),
            5 => Ok(Self::SourceAddressFailedIngressEgressPolicy),
            6 => Ok(Self::RejectRouteToDestination),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Packet Too Big message.
///
/// Sent when a packet exceeds the link MTU, as defined in [RFC 4443] Section 3.2.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PacketTooBig {
    /// The code.
    pub code: PacketTooBigCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The MTU.
    pub mtu: u32,
    /// The original data.
    pub data: Vec<u8>,
}

impl PacketTooBig {
    /// The type.
    pub const TYPE: Type = Type::PacketTooBig;
}

impl Codec for PacketTooBig {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        self.mtu.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Type::PacketTooBig => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = PacketTooBigCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        let mtu = u32::decode(reader, ())?;
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            mtu,
            data,
        })
    }
}

/// A code for [`PacketTooBig`].
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
pub type PacketTooBigCode = NoCode;

/// A Time Exceeded message.
///
/// Sent when the hop limit or fragment reassembly time has been exceeded,
/// as defined in [RFC 4443] Section 3.3.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct TimeExceeded {
    /// The code.
    pub code: TimeExceededCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The original data.
    pub data: Vec<u8>,
}

impl TimeExceeded {
    /// The type.
    pub const TYPE: Type = Type::TimeExceeded;
    /// Reserved. Must be zero.
    pub const UNUSED: [u8; 4] = [0u8; 4];
}

impl Codec for TimeExceeded {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        Self::UNUSED.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Type::TimeExceeded => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = TimeExceededCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        match reader.read_array::<4>()? {
            Self::UNUSED => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            data,
        })
    }
}

/// A code for [`TimeExceeded`].
///
/// The reason the time was exceeded.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum TimeExceededCode {
    /// Hop limit exceeded in transit.
    HopLimitExceededInTransit = 0,
    /// Fragment reassembly time exceeded.
    FragmentReassemblyTimeExceeded = 1,
}

impl Codec for TimeExceededCode {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            0 => Ok(Self::HopLimitExceededInTransit),
            1 => Ok(Self::FragmentReassemblyTimeExceeded),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A Parameter Problem message.
///
/// Sent when a parameter in the IPv6 header or extension headers is invalid,
/// as defined in [RFC 4443] Section 3.4.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ParameterProblem {
    /// The code.
    pub code: ParameterProblemCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The byte offset of the error.
    pub pointer: u32,
    /// The original data.
    pub data: Vec<u8>,
}

impl ParameterProblem {
    /// The type.
    pub const TYPE: Type = Type::ParameterProblem;
}

impl Codec for ParameterProblem {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        self.pointer.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Type::ParameterProblem => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = ParameterProblemCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        let pointer = u32::decode(reader, ())?;
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            pointer,
            data,
        })
    }
}

/// A code for [`ParameterProblem`].
///
/// The type of parameter error.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum ParameterProblemCode {
    /// Erroneous header field encountered.
    ErroneousHeaderField = 0,
    /// Unrecognized Next Header type encountered.
    UnrecognizedNextHeaderType = 1,
    /// Unrecognized IPv6 option encountered.
    UnrecognizedIpv6Option = 2,
}

impl Codec for ParameterProblemCode {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        (*self as u8).encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match u8::decode(reader, ())? {
            0 => Ok(Self::ErroneousHeaderField),
            1 => Ok(Self::UnrecognizedNextHeaderType),
            2 => Ok(Self::UnrecognizedIpv6Option),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// An Echo Request message.
///
/// Used to test reachability, as defined in [RFC 4443] Section 4.1.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EchoRequest {
    /// The code.
    pub code: EchoRequestCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The identifier.
    pub identifier: u16,
    /// The sequence number.
    pub sequence_number: u16,
    /// The data.
    pub data: Vec<u8>,
}

impl EchoRequest {
    /// The type.
    pub const TYPE: Type = Type::EchoRequest;
}

impl Codec for EchoRequest {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        self.identifier.encode(writer, ())?;
        self.sequence_number.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Self::TYPE => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = EchoRequestCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        let identifier = u16::decode(reader, ())?;
        let sequence_number = u16::decode(reader, ())?;
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            identifier,
            sequence_number,
            data,
        })
    }
}

/// A code for [`EchoRequest`].
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
pub type EchoRequestCode = NoCode;

/// An Echo Reply message.
///
/// Sent in response to an [`EchoRequest`], as defined in [RFC 4443] Section 4.2.
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EchoReply {
    /// The code.
    pub code: EchoReplyCode,
    /// The checksum.
    pub checksum: Checksum,
    /// The identifier.
    pub identifier: u16,
    /// The sequence number.
    pub sequence_number: u16,
    /// The data.
    pub data: Vec<u8>,
}

impl EchoReply {
    /// The type.
    pub const TYPE: Type = Type::EchoReply;
}

impl Codec for EchoReply {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.code.encode(writer, ())?;
        self.checksum.encode(writer, ())?;
        self.identifier.encode(writer, ())?;
        self.sequence_number.encode(writer, ())?;
        self.data.encode(writer, ())?;
        Ok(())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        match Type::decode(reader, ())? {
            Self::TYPE => (),
            _ => return Err(BufError::UnexpectedValue),
        }
        let code = EchoReplyCode::decode(reader, ())?;
        let checksum = Checksum::decode(reader, ())?;
        let identifier = u16::decode(reader, ())?;
        let sequence_number = u16::decode(reader, ())?;
        let data = Vec::decode(reader, ())?;
        Ok(Self {
            code,
            checksum,
            identifier,
            sequence_number,
            data,
        })
    }
}

/// A code for [`EchoReply`].
///
/// [RFC 4443]: https://datatracker.ietf.org/doc/html/rfc4443
pub type EchoReplyCode = NoCode;

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

    use crate::{
        Codec, Cursor,
        ietf::icmpv6::{
            Checksum, DestinationUnreachable, DestinationUnreachableCode, EchoReply, EchoReplyCode,
            EchoRequest, EchoRequestCode, NoCode, PacketTooBig, PacketTooBigCode, ParameterProblem,
            ParameterProblemCode, TimeExceeded, TimeExceededCode, Type,
        },
    };

    fn codec_roundtrip<T: Codec<C> + Debug + Eq, C: Copy>(
        etalon_struct: T,
        etalon_bytes: &[u8],
        context: C,
    ) {
        let mut encoded_bytes = vec![];
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            etalon_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);

        let decoded_struct = {
            let reader = &mut Cursor::new(&mut encoded_bytes);
            T::decode(reader, context).unwrap()
        };
        assert_eq!(etalon_struct, decoded_struct);

        encoded_bytes.fill(0x00);
        {
            let writer = &mut Cursor::new(&mut encoded_bytes);
            decoded_struct.encode(writer, context).unwrap();
        }
        assert_eq!(etalon_bytes, &encoded_bytes);
    }

    #[test]
    fn checksum() {
        let packet = &[0x80, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02];
        let checksum = Checksum::calculate(packet);

        let mut with_checksum = vec![0x80, 0x00];
        with_checksum.extend_from_slice(&checksum.0.to_be_bytes());
        with_checksum.extend_from_slice(&[0x00, 0x01, 0x00, 0x02]);

        let verify = Checksum::calculate(&with_checksum);
        assert!(verify.0 == 0x0000 || verify.0 == 0xFFFF);
    }

    #[test]
    fn type_roundtrip() {
        let cases = [
            (Type::DestinationUnreachable, &[0x01][..]),
            (Type::PacketTooBig, &[0x02][..]),
            (Type::TimeExceeded, &[0x03][..]),
            (Type::ParameterProblem, &[0x04][..]),
            (Type::EchoRequest, &[0x80][..]),
            (Type::EchoReply, &[0x81][..]),
        ];
        for (t, bytes) in &cases {
            codec_roundtrip(*t, bytes, ());
        }
    }

    #[test]
    fn no_code() {
        codec_roundtrip(NoCode::Zero, &[0x00], ());
    }

    #[test]
    fn destination_unreachable() {
        let etalon_bytes = &[
            0x01, // Type
            0x00, // Code: NoRouteToDestination
            0x00, 0x00, // Checksum
            0x00, 0x00, 0x00, 0x00, // UNUSED
            0xde, 0xad, 0xbe, 0xef, // Data
        ];
        let etalon_struct = DestinationUnreachable {
            code: DestinationUnreachableCode::NoRouteToDestination,
            checksum: Checksum(0x0000),
            data: vec![0xde, 0xad, 0xbe, 0xef],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn packet_too_big() {
        let etalon_bytes = &[
            0x02, // Type
            0x00, // Code
            0x00, 0x00, // Checksum
            0x00, 0x00, 0x05, 0x00, // MTU: 1280
            0xca, 0xfe, 0xba, 0xbe, // Data
        ];
        let etalon_struct = PacketTooBig {
            code: PacketTooBigCode::Zero,
            checksum: Checksum(0x0000),
            mtu: 1280,
            data: vec![0xca, 0xfe, 0xba, 0xbe],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn time_exceeded() {
        let etalon_bytes = &[
            0x03, // Type
            0x00, // Code: HopLimitExceededInTransit
            0x00, 0x00, // Checksum
            0x00, 0x00, 0x00, 0x00, // UNUSED
            0x11, 0x22, 0x33, 0x44, // Data
        ];
        let etalon_struct = TimeExceeded {
            code: TimeExceededCode::HopLimitExceededInTransit,
            checksum: Checksum(0x0000),
            data: vec![0x11, 0x22, 0x33, 0x44],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn parameter_problem() {
        let etalon_bytes = &[
            0x04, // Type
            0x00, // Code: ErroneousHeaderField
            0x00, 0x00, // Checksum
            0x00, 0x00, 0x00, 0x05, // Pointer: 5
            0x55, 0x66, 0x77, 0x88, // Data
        ];
        let etalon_struct = ParameterProblem {
            code: ParameterProblemCode::ErroneousHeaderField,
            checksum: Checksum(0x0000),
            pointer: 5,
            data: vec![0x55, 0x66, 0x77, 0x88],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn echo_request() {
        let etalon_bytes = &[
            0x80, // Type: Echo Request
            0x00, // Code: 0
            0x00, 0x00, // Checksum: 0
            0x00, 0x01, // Identifier: 1
            0x00, 0x02, // Sequence Number: 2
            0x41, 0x42, 0x43, // Data: "ABC"
        ];
        let etalon_struct = EchoRequest {
            code: EchoRequestCode::Zero,
            checksum: Checksum(0x0000),
            identifier: 1,
            sequence_number: 2,
            data: vec![0x41, 0x42, 0x43],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn echo_reply() {
        let etalon_bytes = &[
            0x81, // Type: Echo Reply
            0x00, // Code: 0
            0x00, 0x00, // Checksum: 0
            0x00, 0x01, // Identifier: 1
            0x00, 0x02, // Sequence Number: 2
            0x41, 0x42, 0x43, // Data: "ABC"
        ];
        let etalon_struct = EchoReply {
            code: EchoReplyCode::Zero,
            checksum: Checksum(0x0000),
            identifier: 1,
            sequence_number: 2,
            data: vec![0x41, 0x42, 0x43],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }
}