internet 0.0.5

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
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
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
//! Packet headers encoding following [Section 17].
//!
//! > description
//!
//! This module provides the following primitives:
//!
//! - [`FixedBit`]
//! - [`LongHeaderPacketType`]
//! - [`ConnectionId`]
//! - [`PacketNumberLength`]
//! - [`PacketNumber`]
//! - [`Length`]
//! - [`RetryToken`]
//! - [`RetryIntegrityTag`]
//! - [`SpinBit`]
//! - [`KeyPhase`]
//!
//! And the following packet headers:
//!
//! - [`InitialPacket`]
//! - [`ZeroRttPacket`]
//! - [`HandshakePacket`]
//! - [`RetryPacket`]
//! - [`OneRttPacket`]
//!
//! [Section 17]: https://datatracker.ietf.org/doc/html/rfc9000#section-17

use crate::{
    Buf,
    BufError::{self},
    BufMut, BufResult, Codec, Cursor,
    quic::{HeaderForm, Version},
    quicv1::VariableLengthInteger,
};

/// A Fixed Bit of the Long Header Packet following [Section 17.2].
///
/// The bit is set to 1, unless the packet is a [Version Negotiation packet].
///
/// [Section 17.2]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.2
/// [Version Negotiation packet]: VersionNegotiationPacket
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum FixedBit {
    /// Indicating any packet.
    One = 1,
    /// Indicating [Version Negotiation Packet](`VersionNegotiationPacket`).
    VersionNegotiationPacket = 0,
}

impl Codec for FixedBit {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let current_byte = writer.peek_u8().unwrap_or(0x00);
        let bit_mask = (*self as u8) << 6;
        let updated_byte = (current_byte & !0x40) | bit_mask;
        writer.poke_u8(updated_byte)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let byte = reader.peek_u8()?;
        match (byte & 0x40) >> 6 {
            0 => Ok(Self::VersionNegotiationPacket),
            _ => Ok(Self::One),
        }
    }
}

/// A Long Header Type following [Section 17.2, Table 5].
///
/// Indicating type of the Long Header Packet.
///
/// [Section 17.2, Table 5]: https://datatracker.ietf.org/doc/html/rfc9000#table-5
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum LongHeaderPacketType {
    /// [Initial Packet](InitialPacket) type.
    Initial = 0x00,

    /// [0-RTT Packet](ZeroRttPacket) type.
    ZeroRtt = 0x01,

    /// [Handshake Packet](HandshakePacket) type.
    Handshake = 0x02,

    /// [Retry Packet](RetryPacket) type.
    Retry = 0x03,
}

impl Codec for LongHeaderPacketType {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let current_byte = writer.peek_u8().unwrap_or(0x00);
        let bit_mask = (*self as u8) << 4;
        let updated_byte = (current_byte & !0x30) | bit_mask;
        writer.poke_u8(updated_byte)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let value = (reader.peek_u8()? & 0x30) >> 4;
        match value {
            0 => Ok(Self::Initial),
            1 => Ok(Self::ZeroRtt),
            2 => Ok(Self::Handshake),
            _ => Ok(Self::Retry),
        }
    }
}

/// A connection ID, specified for QUIC version 1.
///
/// Helper structure to contain the `Connection ID Length` and `Connection ID` fields.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConnectionId {
    /// The length of the connection ID, must not exceed 20 in QUIC version 1.
    length: u8,
    /// The connection ID bytes.
    bytes: [u8; Self::MAXIMAL_LENGTH],
}

impl ConnectionId {
    ///
    pub const MAXIMAL_LENGTH: usize = 20;

    ///
    pub fn new(connection_id: &[u8]) -> Option<Self> {
        let length = connection_id.length();
        if length > Self::MAXIMAL_LENGTH as usize {
            return None;
        }
        let mut cid = [0u8; Self::MAXIMAL_LENGTH];
        cid[..length].copy_from_slice(connection_id);
        let length = length as u8;
        Some(Self { length, bytes: cid })
    }

    ///
    pub fn into_inner(self) -> (u8, [u8; Self::MAXIMAL_LENGTH]) {
        (self.length, self.bytes)
    }

    ///
    pub fn length(self) -> u8 {
        self.length
    }

    ///
    pub fn bytes(self) -> [u8; Self::MAXIMAL_LENGTH] {
        self.bytes
    }
}

impl Codec for ConnectionId {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let (cil, ci) = self.into_inner();
        cil.encode(writer, ())?;
        writer.write_slice(&ci[..cil as usize])
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let ci = &mut [0u8; Self::MAXIMAL_LENGTH];
        let cil = u8::decode(reader, ())?;
        reader.read_into(&mut ci[..cil as usize])?;
        Ok(Self::new(&ci[..cil as usize]).ok_or(BufError::UnexpectedValue)?)
    }
}

impl Codec<u8> for ConnectionId {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: u8) -> BufResult<()> {
        let (cil, ci) = self.into_inner();
        writer.write_slice(&ci[..cil as usize])
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, cil: u8) -> BufResult<Self> {
        let ci = &mut [0u8; Self::MAXIMAL_LENGTH];
        reader.read_into(&mut ci[..cil as usize])?;
        Ok(Self::new(&ci[..cil as usize]).ok_or(BufError::UnexpectedValue)?)
    }
}

/// A Packet Number Length.
///
/// > description
///
/// Defined in [IETF RFC 9000, Section 17.2](https://datatracker.ietf.org/doc/html/rfc9000#section-17.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PacketNumberLength(pub u8);

impl PacketNumberLength {
    /// Выбирает минимальную длину, достаточную для кодирования данного номера пакета.
    pub fn from_packet_number(packet_number: PacketNumber) -> BufResult<Self> {
        // Предполагается, что VariableLengthInteger имеет поле .0 типа u64
        let pn = packet_number.0.0;

        if pn <= u8::MAX as u64 {
            Ok(Self(0)) // 1 byte
        } else if pn <= u16::MAX as u64 {
            Ok(Self(1)) // 2 bytes
        } else if pn <= 0xFFFFFF {
            Ok(Self(2)) // 3 bytes
        } else {
            Ok(Self(3)) // 4 bytes
        }
    }

    /// Возвращает фактическое количество байт, занимаемое номером пакета (1..=4).
    pub fn byte_length(&self) -> u8 {
        self.0 + 1
    }
}

impl Codec for PacketNumberLength {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let current_byte = writer.peek_u8().unwrap_or(0x00);
        let bit_mask = self.0 & 0x03;
        let updated_byte = (current_byte & !0x03) | bit_mask;

        writer.write_u8(updated_byte)
    }

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

/// A Packet Number.
///
/// > description
///
/// Defined in [IETF RFC 9000, Section 17.2](https://datatracker.ietf.org/doc/html/rfc9000#section-17.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PacketNumber(pub VariableLengthInteger);
impl PacketNumber {
    ///
    pub fn new(last_sent: PacketNumber) -> Self {
        let mut last_sent = last_sent;
        last_sent.0.0 += 1;
        Self(last_sent.0)
    }

    ///
    pub fn length(&self) -> BufResult<PacketNumberLength> {
        PacketNumberLength::from_packet_number(*self)
    }
}
impl Codec<PacketNumberLength> for PacketNumber {
    fn encode<W: BufMut>(
        &self,
        writer: &mut Cursor<W>,
        length: PacketNumberLength,
    ) -> BufResult<()> {
        let pn = self.0.0;

        match length.0 {
            0 => writer.write_u8(pn as u8),
            1 => writer.write_u16_be(pn as u16), // Big-endian согласно RFC
            2 => {
                // 3 bytes: записываем по одному байту в big-endian порядке
                writer.write_u8((pn >> 16) as u8)?;
                writer.write_u8((pn >> 8) as u8)?;
                writer.write_u8(pn as u8)
            }
            3 => writer.write_u32_be(pn as u32),
            _ => Err(BufError::UnexpectedValue),
        }
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, length: PacketNumberLength) -> BufResult<Self> {
        let pn = match length.0 {
            0 => reader.read_u8()? as u64,
            1 => reader.read_u16_be()? as u64,
            2 => {
                // Читаем 3 байта и собираем в u64 в big-endian порядке
                let b1 = reader.read_u8()? as u64;
                let b2 = reader.read_u8()? as u64;
                let b3 = reader.read_u8()? as u64;
                (b1 << 16) | (b2 << 8) | b3
            }
            3 => reader.read_u32_be()? as u64,
            _ => return Err(BufError::UnexpectedValue),
        };

        Ok(Self(VariableLengthInteger(pn)))
    }
}

/// A length of the [PacketNumber] and Payload fields in bytes following [Section 17.2].
///
/// > description
///
/// Defined in [Section 17.2](https://datatracker.ietf.org/doc/html/rfc9000#section-17.2).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Length(pub VariableLengthInteger);
impl Length {
    ///
    pub fn calculate(
        packet_payload_length: usize,
        packet_number_length: PacketNumberLength,
    ) -> BufResult<Self> {
        Ok(Self(VariableLengthInteger::new(
            packet_payload_length as u64 + packet_number_length.0 as u64,
        )?))
    }
}

impl Codec for Length {
    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(VariableLengthInteger::decode(reader, ())?))
    }
}

/// A Token.
///
/// > description
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RetryToken(pub Vec<u8>);

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

    ///
    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let remaining = reader.remaining();
        if remaining < 16 {
            return Err(BufError::OutOfBounds);
        }
        let length = remaining - 16;
        Ok(Self(Vec::decode(reader, length)?))
    }
}

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

    ///
    fn decode<R: Buf>(reader: &mut Cursor<R>, length: VariableLengthInteger) -> BufResult<Self> {
        Ok(Self(Vec::decode(reader, length.0 as usize)?))
    }
}

/// A Retry Integrity Tag.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RetryIntegrityTag(pub [u8; 16]);

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

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

/// A Spin Bit of the [1-RTT packet].
///
/// > description
///
/// [1-RTT packet]: OneRttPacket
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum SpinBit {
    ///
    Zero = 0,
    ///
    One = 1,
}

impl SpinBit {
    ///
    pub fn spin(&mut self) {
        *self = match self {
            SpinBit::Zero => SpinBit::One,
            SpinBit::One => SpinBit::Zero,
        }
    }
}

impl Codec for SpinBit {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let current_byte = writer.peek_u8().unwrap_or(0x00);
        let bit_mask = (*self as u8) << 5;
        let updated_byte = (current_byte & !0b100000) | bit_mask;
        writer.poke_u8(updated_byte)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let value = reader.peek_u8()? & 0b100000;
        match value {
            0 => Ok(Self::Zero),
            _ => Ok(Self::One),
        }
    }
}

/// A Key Phase of the [1-RTT packet].
///
/// > description
///
/// [1-RTT packet]: OneRttPacket
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum KeyPhase {
    /// .
    Zero = 0,
    /// .
    One = 1,
}

impl Codec for KeyPhase {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        let current_byte = writer.peek_u8().unwrap_or(0x00);
        let bit_mask = (*self as u8) << 2;
        let updated_byte = (current_byte & !0b100) | bit_mask;
        writer.poke_u8(updated_byte)
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let value = reader.peek_u8()? & 0b100;
        match value {
            0 => Ok(Self::Zero),
            _ => Ok(Self::One),
        }
    }
}

/// An Initial Packet following [Section 17.2.2].
///
/// Carries the first [CRYPTO frames] from client and [ACK frames] in either direction.
///
/// [CRYPTO frames]: crate::quicv1::CryptoFrame
/// [ACK frames]: crate::quicv1::AckFrame
/// [Section 17.2.2]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.2
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InitialPacket {
    /// The version.
    pub version: Version,
    /// The destination connection ID.
    pub destination_connection_id: ConnectionId,
    /// The source connection ID.
    pub source_connection_id: ConnectionId,
    /// The token received from the the server [Retry packet](RetryPacket).
    pub token: RetryToken,
    /// The Packet Number.
    pub packet_number: PacketNumber,
    /// The Packet Payload.
    pub packet_payload: Vec<u8>,
}

impl InitialPacket {
    /// The header form.
    pub const HEADER_FORM: HeaderForm = HeaderForm::LongHeader;
    /// The fixed bit.
    pub const FIXED_BIT: FixedBit = FixedBit::One;
    /// The long packet type.
    pub const LONG_PACKET_TYPE: LongHeaderPacketType = LongHeaderPacketType::Initial;
}

impl Codec for InitialPacket {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::HEADER_FORM.encode(writer, ())?;
        Self::FIXED_BIT.encode(writer, ())?;
        Self::LONG_PACKET_TYPE.encode(writer, ())?;
        let packet_number_length = self.packet_number.length()?;
        packet_number_length.encode(writer, ())?;
        self.version.encode(writer, ())?;
        self.destination_connection_id.encode(writer, ())?;
        self.source_connection_id.encode(writer, ())?;
        VariableLengthInteger::new(self.token.0.len() as u64)?.encode(writer, ())?;
        self.token.0.encode(writer, ())?;
        Length::calculate(self.packet_payload.len(), packet_number_length)?.encode(writer, ())?;
        self.packet_number.encode(writer, packet_number_length)?;
        self.packet_payload.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if HeaderForm::decode(reader, ())? != Self::HEADER_FORM {
            return Err(BufError::UnexpectedValue);
        }
        if FixedBit::decode(reader, ())? != Self::FIXED_BIT {
            return Err(BufError::UnexpectedValue);
        }
        if LongHeaderPacketType::decode(reader, ())? != Self::LONG_PACKET_TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let packet_number_length = PacketNumberLength::decode(reader, ())?;
        let version = Version::decode(reader, ())?;
        let destination_connection_id = ConnectionId::decode(reader, ())?;
        let source_connection_id = ConnectionId::decode(reader, ())?;
        let token_length = VariableLengthInteger::decode(reader, ())?;
        let token_bytes = &mut [0u8; 16];
        reader.read_into(&mut token_bytes[..token_length.0 as usize])?;
        let token = RetryToken((&token_bytes[..token_length.0 as usize]).to_vec());
        let _length = VariableLengthInteger::decode(reader, ())?;
        let packet_number = PacketNumber::decode(reader, packet_number_length)?;
        let packet_payload = Vec::decode(reader, ())?;

        Ok(Self {
            version,
            destination_connection_id,
            source_connection_id,
            token,
            packet_number,
            packet_payload,
        })
    }
}

/// A 0-RTT Packet following [Section 17.2.3].
///
/// Carries early data from the client to the server prior to handshake completion.
///
/// [Section 17.2.3]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.3
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ZeroRttPacket {
    /// The version.
    pub version: Version,
    /// The destination connection ID.
    pub destination_connection_id: ConnectionId,
    /// The source connection ID.
    pub source_connection_id: ConnectionId,
    /// The packet number.
    pub packet_number: PacketNumber,
    /// The packet payload.
    pub packet_payload: Vec<u8>,
}

impl ZeroRttPacket {
    /// The header form.
    pub const HEADER_FORM: HeaderForm = HeaderForm::LongHeader;
    /// The fixed bit.
    pub const FIXED_BIT: FixedBit = FixedBit::One;
    /// The long packet type.
    pub const LONG_PACKET_TYPE: LongHeaderPacketType = LongHeaderPacketType::ZeroRtt;
}

impl Codec for ZeroRttPacket {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::HEADER_FORM.encode(writer, ())?;
        Self::FIXED_BIT.encode(writer, ())?;
        Self::LONG_PACKET_TYPE.encode(writer, ())?;
        let packet_number_length = self.packet_number.length()?;
        packet_number_length.encode(writer, ())?;
        self.version.encode(writer, ())?;
        self.destination_connection_id.encode(writer, ())?;
        self.source_connection_id.encode(writer, ())?;
        Length::calculate(self.packet_payload.len(), packet_number_length)?.encode(writer, ())?;
        self.packet_number.encode(writer, packet_number_length)?;
        self.packet_payload.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if HeaderForm::decode(reader, ())? != Self::HEADER_FORM {
            return Err(BufError::UnexpectedValue);
        }
        if FixedBit::decode(reader, ())? != Self::FIXED_BIT {
            return Err(BufError::UnexpectedValue);
        }
        if LongHeaderPacketType::decode(reader, ())? != Self::LONG_PACKET_TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let packet_number_length = PacketNumberLength::decode(reader, ())?;
        let version = Version::decode(reader, ())?;
        let destination_connection_id = ConnectionId::decode(reader, ())?;
        let source_connection_id = ConnectionId::decode(reader, ())?;
        let _length = VariableLengthInteger::decode(reader, ())?;
        let packet_number = PacketNumber::decode(reader, packet_number_length)?;
        let packet_payload = Vec::decode(reader, ())?;

        Ok(Self {
            version,
            destination_connection_id,
            source_connection_id,
            packet_number,
            packet_payload,
        })
    }
}

/// A Handshake Packet following [Section 17.2.4].
///
/// Carries cryptographic handshake messages and acknowledgments from the server and client.
///
/// [Section 17.2.4]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.4
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HandshakePacket {
    /// The version.
    pub version: Version,
    /// The destination connection ID.
    pub destination_connection_id: ConnectionId,
    /// The source connection ID.
    pub source_connection_id: ConnectionId,
    /// The packet number.
    pub packet_number: PacketNumber,
    /// The packet payload.
    pub packet_payload: Vec<u8>,
}

impl HandshakePacket {
    /// The header form.
    pub const HEADER_FORM: HeaderForm = HeaderForm::LongHeader;
    /// The fixed bit.
    pub const FIXED_BIT: FixedBit = FixedBit::One;
    /// The long packet type.
    pub const LONG_PACKET_TYPE: LongHeaderPacketType = LongHeaderPacketType::Handshake;
}

impl Codec for HandshakePacket {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::HEADER_FORM.encode(writer, ())?;
        Self::FIXED_BIT.encode(writer, ())?;
        Self::LONG_PACKET_TYPE.encode(writer, ())?;
        let packet_number_length = self.packet_number.length()?;
        packet_number_length.encode(writer, ())?;
        self.version.encode(writer, ())?;
        self.destination_connection_id.encode(writer, ())?;
        self.source_connection_id.encode(writer, ())?;
        Length::calculate(self.packet_payload.len(), packet_number_length)?.encode(writer, ())?;
        self.packet_number.encode(writer, packet_number_length)?;
        self.packet_payload.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if HeaderForm::decode(reader, ())? != Self::HEADER_FORM {
            return Err(BufError::UnexpectedValue);
        }
        if FixedBit::decode(reader, ())? != Self::FIXED_BIT {
            return Err(BufError::UnexpectedValue);
        }
        if LongHeaderPacketType::decode(reader, ())? != Self::LONG_PACKET_TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let packet_number_length = PacketNumberLength::decode(reader, ())?;
        let version = Version::decode(reader, ())?;
        let destination_connection_id = ConnectionId::decode(reader, ())?;
        let source_connection_id = ConnectionId::decode(reader, ())?;
        let _length = VariableLengthInteger::decode(reader, ())?;
        let packet_number = PacketNumber::decode(reader, packet_number_length)?;
        let packet_payload = Vec::decode(reader, ())?;

        Ok(Self {
            version,
            destination_connection_id,
            source_connection_id,
            packet_number,
            packet_payload,
        })
    }
}

/// A Retry Packet following [Section 17.2.5].
///
/// Carries an [address validation token] created by the server to the client.
///
/// [Section 17.2.5]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.2.5
/// [address validation token]: RetryToken
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RetryPacket {
    /// The version.
    pub version: Version,
    /// The destination connection ID.
    pub destination_connection_id: ConnectionId,
    /// The source connection ID.
    pub source_connection_id: ConnectionId,
    /// The retry token.
    pub retry_token: RetryToken,
    /// The retry integrity tag.
    pub retry_integrity_tag: RetryIntegrityTag,
}

impl RetryPacket {
    /// The header form.
    pub const HEADER_FORM: HeaderForm = HeaderForm::LongHeader;
    /// The fixed bit.
    pub const FIXED_BIT: FixedBit = FixedBit::One;
    /// The long packet type.
    pub const LONG_PACKET_TYPE: LongHeaderPacketType = LongHeaderPacketType::Retry;
}

impl Codec for RetryPacket {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::HEADER_FORM.encode(writer, ())?;
        Self::FIXED_BIT.encode(writer, ())?;
        Self::LONG_PACKET_TYPE.encode(writer, ())?;
        writer.advance(1)?;
        self.version.encode(writer, ())?;
        self.destination_connection_id.encode(writer, ())?;
        self.source_connection_id.encode(writer, ())?;
        self.retry_token.encode(writer, ())?;
        self.retry_integrity_tag.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if HeaderForm::decode(reader, ())? != Self::HEADER_FORM {
            return Err(BufError::UnexpectedValue);
        }
        if FixedBit::decode(reader, ())? != Self::FIXED_BIT {
            return Err(BufError::UnexpectedValue);
        }
        if LongHeaderPacketType::decode(reader, ())? != Self::LONG_PACKET_TYPE {
            return Err(BufError::UnexpectedValue);
        }
        reader.advance(1)?;
        let version = Version::decode(reader, ())?;
        let destination_connection_id = ConnectionId::decode(reader, ())?;
        let source_connection_id = ConnectionId::decode(reader, ())?;
        let mut left = Vec::decode(reader, ())?;
        let length = left.len();
        let (retry_token, _retry_integrity_tag) = left.split_at_mut_checked(length - 16).unwrap();
        let retry_token = RetryToken(retry_token.to_vec());
        let retry_integrity_tag = match _retry_integrity_tag.try_into() {
            Ok(x) => x,
            Err(_) => return Err(BufError::UnexpectedValue),
        };
        let retry_integrity_tag = RetryIntegrityTag(retry_integrity_tag);
        Ok(Self {
            version,
            destination_connection_id,
            source_connection_id,
            retry_token,
            retry_integrity_tag,
        })
    }
}

/// A 1-RTT Packet by [Section 17.3.1].
///
/// Used after the version and 1-RTT keys are negotiated.
///
/// [Section 17.3.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-17.3.1
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct OneRttPacket {
    /// The Spin Bit.
    pub spin_bit: SpinBit,
    /// The Key Phase.
    pub key_phase: KeyPhase,
    /// The negotiated destination connection ID.
    pub destination_connection_id: ConnectionId,
    /// The number of this packet.
    pub packet_number: PacketNumber,
    /// The Packet Payload.
    pub packet_payload: Vec<u8>,
}

impl OneRttPacket {
    /// The header form.
    pub const HEADER_FORM: HeaderForm = HeaderForm::ShortHeader;
    /// The fixed bit.
    pub const FIXED_BIT: FixedBit = FixedBit::One;
}

impl Codec<u8> for OneRttPacket {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, dcid_length: u8) -> BufResult<()> {
        Self::HEADER_FORM.encode(writer, ())?;
        Self::FIXED_BIT.encode(writer, ())?;
        self.spin_bit.encode(writer, ())?;
        self.key_phase.encode(writer, ())?;
        let packet_number_length = self.packet_number.length()?;
        packet_number_length.encode(writer, ())?;
        self.destination_connection_id.encode(writer, dcid_length)?;
        self.packet_number.encode(writer, packet_number_length)?;
        self.packet_payload.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, dcid_length: u8) -> BufResult<Self> {
        if HeaderForm::decode(reader, ())? != Self::HEADER_FORM {
            return Err(BufError::UnexpectedValue);
        }
        if FixedBit::decode(reader, ())? != Self::FIXED_BIT {
            return Err(BufError::UnexpectedValue);
        }
        let spin_bit = SpinBit::decode(reader, ())?;
        let key_phase = KeyPhase::decode(reader, ())?;
        let packet_number_length = PacketNumberLength::decode(reader, ())?;
        let destination_connection_id = ConnectionId::decode(reader, dcid_length)?;
        let packet_number = PacketNumber::decode(reader, packet_number_length)?;
        let packet_payload = Vec::decode(reader, ())?;

        Ok(Self {
            spin_bit,
            key_phase,
            destination_connection_id,
            packet_number,
            packet_payload,
        })
    }
}

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

    use crate::{
        Codec, Cursor,
        quic::Version,
        quicv1::{
            ConnectionId, FixedBit, HandshakePacket, InitialPacket, KeyPhase, LongHeaderPacketType,
            OneRttPacket, PacketNumber, PacketNumberLength, RetryIntegrityTag, RetryPacket,
            RetryToken, SpinBit, VariableLengthInteger, ZeroRttPacket,
        },
    };

    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 fixed_bit() {
        let etalon_bytes = &[0b01000000];
        let etalon_struct = FixedBit::One;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b00000000];
        let etalon_struct = FixedBit::VersionNegotiationPacket;
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn long_header_packet_type() {
        let etalon_bytes = &[0b00000000];
        let etalon_struct = LongHeaderPacketType::Initial;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b00010000];
        let etalon_struct = LongHeaderPacketType::ZeroRtt;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b00100000];
        let etalon_struct = LongHeaderPacketType::Handshake;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b00110000];
        let etalon_struct = LongHeaderPacketType::Retry;
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn connection_id() {
        assert_eq!(ConnectionId::new(&[0x08; 21]), None);

        let etalon_bytes = &[0x08; 9];
        let etalon_struct = ConnectionId::new(&[0x08; 8]).unwrap();
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0x010; 17];
        let etalon_struct = ConnectionId::new(&[0x010; 16]).unwrap();
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0x014; 21];
        let etalon_struct = ConnectionId::new(&[0x014; 20]).unwrap();
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn packet_number_length() {
        let etalon_bytes = &[0x00];
        let etalon_struct = PacketNumberLength::from_packet_number(PacketNumber(
            VariableLengthInteger::new(0).unwrap(),
        ))
        .unwrap();
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn packet_number() {
        let etalon_bytes = &[0x00];
        let etalon_struct = PacketNumber(VariableLengthInteger::new(0).unwrap());
        codec_roundtrip(etalon_struct, etalon_bytes, etalon_struct.length().unwrap());
    }

    #[test]
    fn token() {
        let etalon_bytes = &[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, // token
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, // retry integrity tag
        ];
        let etalon_struct = RetryToken(vec![0x00; 16]);
        {
            let context = ();
            let mut encoded_bytes = vec![];
            {
                let writer = &mut Cursor::new(&mut encoded_bytes);
                etalon_struct.encode(writer, context).unwrap();
            }
            encoded_bytes.extend_from_slice(&[0x00; 16]);
            assert_eq!(&etalon_bytes.to_vec(), &encoded_bytes);

            let decoded_struct = {
                let reader = &mut Cursor::new(&mut encoded_bytes);
                RetryToken::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.to_vec(), &encoded_bytes);
        };

        let etalon_bytes = &[
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00,
        ];
        let etalon_struct = RetryToken(vec![0x00; 16]);
        codec_roundtrip(
            etalon_struct,
            etalon_bytes,
            VariableLengthInteger::new_const(16),
        );
    }

    #[test]
    fn retry_integrity_tag() {
        let etalon_bytes = &[0; 16];
        let etalon_struct = RetryIntegrityTag([0; 16]);

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn spin_bit() {
        let etalon_bytes = &[0b00000000];
        let etalon_struct = SpinBit::Zero;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b00100000];
        let etalon_struct = SpinBit::One;
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn key_phase() {
        let etalon_bytes = &[0b00000000];
        let etalon_struct = KeyPhase::Zero;
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0b100];
        let etalon_struct = KeyPhase::One;
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn initial_packet() {
        let etalon_struct = InitialPacket {
            version: Version(1),
            destination_connection_id: ConnectionId::new(&[0x82; 8]).unwrap(),
            source_connection_id: ConnectionId::new(&[0x41; 8]).unwrap(),
            token: RetryToken(vec![0]),
            packet_number: PacketNumber(VariableLengthInteger::new(0).unwrap()),
            packet_payload: vec![],
        };

        // 0xC0 = Long Header, Initial packet type, packet number length = 1 byte.
        // Length = 0x01, так как payload пустой и packet number занимает 1 байт.
        let etalon_bytes: &[u8] = &[
            0xC0, // Version = 1
            0x00, 0x00, 0x00, 0x01, // Destination Connection ID Length + Value
            0x08, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,
            // Source Connection ID Length + Value
            0x08, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // Token Length = 1
            0x01, // Token
            0x00, // Length = Packet Number length + Payload length = 1 + 0
            0x00, // Packet Number
            0x00,
        ];

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn zero_rtt_packet() {
        let etalon_struct = ZeroRttPacket {
            version: Version(1),
            destination_connection_id: ConnectionId::new(&[0x82; 8]).unwrap(),
            source_connection_id: ConnectionId::new(&[0x41; 8]).unwrap(),
            packet_number: PacketNumber(VariableLengthInteger::new(0).unwrap()),
            packet_payload: vec![],
        };

        // 0xD0 = Long Header, 0-RTT packet type, packet number length = 1 byte.
        let etalon_bytes: &[u8] = &[
            // First byte
            0xD0, // Version = 1
            0x00, 0x00, 0x00, 0x01, // Destination Connection ID Length + Value
            0x08, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,
            // Source Connection ID Length + Value
            0x08, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
            // Length = Packet Number length + Payload length = 1 + 0
            0x00, // Packet Number
            0x00,
        ];

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn handshake_packet() {
        let etalon_struct = HandshakePacket {
            version: Version(1),
            destination_connection_id: ConnectionId::new(&[0x82; 8]).unwrap(),
            source_connection_id: ConnectionId::new(&[0x41; 8]).unwrap(),
            packet_number: PacketNumber(VariableLengthInteger::new(0).unwrap()),
            packet_payload: vec![],
        };

        // 0xE0 = Long Header, Handshake packet type, packet number length = 1 byte.
        let etalon_bytes: &[u8] = &[
            // First byte
            0xE0, // Version = 1
            0x00, 0x00, 0x00, 0x01, // Destination Connection ID Length + Value
            0x08, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,
            // Source Connection ID Length + Value
            0x08, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41,
            // Length = Packet Number length + Payload length = 1 + 0
            0x00, 0x00, // Packet Number
        ];

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn retry_packet() {
        let etalon_struct = RetryPacket {
            version: Version(1),
            destination_connection_id: ConnectionId::new(&[0x82; 8]).unwrap(),
            source_connection_id: ConnectionId::new(&[0x41; 8]).unwrap(),
            retry_token: RetryToken(vec![0]),
            retry_integrity_tag: RetryIntegrityTag([0x55; 16]),
        };

        let etalon_bytes: &[u8] = &[
            // First byte
            0xF0, // Version = 1
            0x00, 0x00, 0x00, 0x01, // Destination Connection ID Length + Value
            0x08, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82,
            // Source Connection ID Length + Value
            0x08, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, 0x41, // Retry Token
            0x00, // Retry Integrity Tag, 16 bytes
            0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55, 0x55,
            0x55, 0x55,
        ];

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn one_rtt_packet() {
        let etalon_struct = OneRttPacket {
            spin_bit: SpinBit::Zero,
            key_phase: KeyPhase::Zero,
            destination_connection_id: ConnectionId::new(&[0x82; 8]).unwrap(),
            packet_number: PacketNumber(VariableLengthInteger::new(0).unwrap()),
            packet_payload: vec![],
        };

        let etalon_bytes: &[u8] = &[
            0b01000000, // First byte
            0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, 0x82, // Destination Connection ID
            0x00, // Packet Number
        ];

        codec_roundtrip(etalon_struct, etalon_bytes, 8);
    }
}