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
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
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
//! Frames encoding following [Section 19].
//!
//! Frames are units of the packet payload.
//!
//! Encoding is supported for the following structures:
//!
//!  - [`PaddingFrame`]
//!  - [`PingFrame`]
//!  - [`AckFrame`]
//!  - [`AckRange`]
//!  - [`EcnCounts`]
//!  - [`CryptoFrame`]
//!  - [`ResetStreamFrame`]
//!  - [`StopSendingFrame`]
//!  - [`NewTokenFrame`]
//!  - [`StreamFrame`]
//!  - [`StreamId`]
//!  - [`StreamType`]
//!  - [`MaxDataFrame`]
//!  - [`MaxStreamDataFrame`]
//!  - [`MaxStreamsFrame`]
//!  - [`DataBlockedFrame`]
//!  - [`StreamDataBlockedFrame`]
//!  - [`StreamsBlockedFrame`]
//!  - [`NewConnectionIdFrame`]
//!  - [`RetireConnectionIdFrame`]
//!  - [`PathChallengeFrame`]
//!  - [`PathResponseFrame`]
//!  - [`ConnectionCloseFrame`]
//!  - [`HandshakeDoneFrame`]
//!
//! Encoding is in process for the following structures:
//!
//! - [`FrameType`]
//! - [`TransportErrorCode`]
//!
//! [Section 19]: https://datatracker.ietf.org/doc/html/rfc9000#section-19

use crate::{
    Buf,
    BufError::{self},
    BufMut, BufResult, Codec, Cursor,
    ietf::quicv1::{ConnectionId, RetryToken, VarInt, VariableLengthInteger},
};

/// A Frame Types following [Section 12.4].
///
/// The `Type` field values of all frames.
///
/// [Section 12.4](https://datatracker.ietf.org/doc/html/rfc9000#section-12.4).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u64)]
pub enum FrameType {
    /// (PADDING frame)[PaddingFrame].
    Padding = 0x00,

    /// (PING frame)[PaddingFrame].
    Ping = 0x01,

    /// (PING frame)[PaddingFrame].
    Ack = 0x02,

    /// (PING frame)[PaddingFrame].
    ResetStream = 0x04,

    /// (PING frame)[PaddingFrame].
    StopSending = 0x05,

    /// (PING frame)[PaddingFrame].
    Crypto = 0x06,

    /// (PING frame)[PaddingFrame].
    NewToken = 0x07,

    /// (PING frame)[PaddingFrame].
    Stream = 0x08,

    /// The (MAX_DATA frame)[MaxDataFrame].
    MaxData = 0x10,

    /// The (MaxStreamData frame)[MaxStreamDataFrame].
    MaxStreamData = 0x11,

    /// The (MaxStreams frame)[MaxStreamsFrame].
    MaxStreams = 0x12,

    /// The (DataBlocked frame)[DataBlockedFrame].
    DataBlocked = 0x14,

    /// The (StreamDataBlocked frame)[StreamDataBlockedFrame].
    StreamDataBlocked = 0x15,

    /// The (StreamsBlocked frame)[StreamsBlockedFrame].
    StreamsBlocked = 0x16,

    /// The (NewConnectionId frame)[NewConnectionIdFrame].
    NewConnectionId = 0x18,

    /// The (RetireConnectionId frame)[RetireConnectionIdFrame].
    RetireConnectionId = 0x19,

    /// The (PathChallenge frame)[PathChallengeFrame].
    PathChallenge = 0x1a,

    /// The (PathResponse frame)[PathResponseFrame].
    PathResponse = 0x1b,

    /// The (ConnectionClose frame)[ConnectionCloseFrame].
    ConnectionClose = 0x1c,

    /// The (HandshakeDone frame)[HandshakeDoneFrame].
    HandshakeDone = 0x1e,
}

impl Codec for FrameType {
    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::Padding as u8) => Ok(Self::Padding),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A PADDING frame following [Section 19.1].
///
/// Used to increase the packet size by 1 byte.
///
/// [Section 19.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PaddingFrame;

impl PaddingFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::Padding as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {})
    }
}

/// A PING frame following [Section 19.2].
///
/// Can be used to:
///  - keep connection alive
///  - check that peer is alive
///  - check that peer is reachable
///
/// The receiver needs to acknowledge the packet containing that frame.
///
/// [Section 19.2]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.2
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PingFrame;

impl PingFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::Ping as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {})
    }
}

/// An ACK frame following [Section 19.3].
///
/// Informs senders about packets that receiver have received and processed.
///
/// [Section 19.3]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.3
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AckFrame {
    /// The largest acknowledged packet number.
    pub largest_acknowledged: VarInt,
    /// The ack delay in mcs rshifted by `ack_delay_exponent`
    pub ack_delay: VarInt,
    /// The count of ack ranges after first ack range.
    // pub ack_range_count: VarInt, // -EVALUATED
    ///
    pub first_ack_range: VarInt,
    ///
    pub ack_ranges: Vec<AckRange>,
    ///
    pub ecn_counts: Option<EcnCounts>,
}

impl AckFrame {
    ///
    pub fn calculate_type(&self) -> VarInt {
        match self.ecn_counts {
            Some(_) => VariableLengthInteger(0x03),
            None => VariableLengthInteger(0x02),
        }
    }
}

impl Codec for AckFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.calculate_type().encode(writer, ())?;
        self.largest_acknowledged.encode(writer, ())?;
        self.ack_delay.encode(writer, ())?;
        (VariableLengthInteger::new(self.ack_ranges.len() as u64)?).encode(writer, ())?;
        self.first_ack_range.encode(writer, ())?;
        self.ack_ranges.encode(writer, ())?;

        match self.ecn_counts {
            Some(ecn_counts) => ecn_counts.encode(writer, ()),
            None => Ok(()),
        }
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let r#type = (VarInt::decode(reader, ())?).into_inner();
        let largest_acknowledged = VarInt::decode(reader, ())?;
        let ack_delay = VarInt::decode(reader, ())?;
        let ack_range_count = VarInt::decode(reader, ())?;
        let first_ack_range = VarInt::decode(reader, ())?;
        let ack_ranges = Vec::decode(reader, ack_range_count.0 as usize)?;

        let ecn_counts = match r#type {
            0x02 => None,
            0x03 => Some(EcnCounts::decode(reader, ())?),
            _ => return Err(BufError::UnexpectedValue),
        };

        Ok(Self {
            largest_acknowledged,
            ack_delay,
            // ack_range_count,
            first_ack_range,
            ack_ranges,
            ecn_counts,
        })
    }
}

/// An Ack Range of the [ACK frame] by [Section 19.3.1].
///
/// Acknowledges a contiguous range of packets by indicating the number of acknowledged packets
/// that precede the largest packet number in that range.
///
/// [ACK frame]: AckFrame
/// [Section 19.3.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.3.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AckRange {
    ///
    pub gap: VarInt,
    ///
    pub ack_range_length: VarInt,
}

impl Codec for AckRange {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.gap.encode(writer, ())?;
        self.ack_range_length.encode(writer, ())
    }

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

/// An ECN Counts of the [ACK frame] by [Section 19.3.2].
///
/// Indicate ECN feedback and report receipt of QUIC packets with associated ECN codepoints
/// of ECT(0), ECT(1), or ECN-CE in the packet's IP header.
///
/// [ACK frame]: AckFrame
/// [Section 19.3.2]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.3.2
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct EcnCounts {
    /// Total number of packets received with the ECT(0) codepoint in the packet number space of the ACK frame.
    pub ect0_count: VarInt,
    /// Total number of packets received with the ECT(1) codepoint in the packet number space of the ACK frame.
    pub ect1_count: VarInt,
    /// Total number of packets received with the ECN-CE codepoint in the packet number space of the ACK frame.
    pub ecn_ce_count: VarInt,
}

impl Codec for EcnCounts {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.ect0_count.encode(writer, ())?;
        self.ect1_count.encode(writer, ())?;
        self.ecn_ce_count.encode(writer, ())
    }

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

/// A RESET_STREAM frame following [Section 19.4].
///
/// Abruptly terminates the sending part of a stream.
///
/// [Section 19.4]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.4
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ResetStreamFrame {
    /// An ID of the stream being terminated.
    pub stream_id: StreamId,
    /// The application protocol error code.
    pub application_protocol_error_code: VarInt,
    /// The final size of the stream by the RESET_STREAM sender, in units of bytes
    pub final_size: VarInt,
}

impl ResetStreamFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::ResetStream as u64);
}

impl Codec for ResetStreamFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.stream_id.encode(writer, ())?;
        self.application_protocol_error_code.encode(writer, ())?;
        self.final_size.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let stream_id = StreamId::decode(reader, ())?;
        let application_protocol_error_code = VarInt::decode(reader, ())?;
        let final_size = VarInt::decode(reader, ())?;
        Ok(Self {
            stream_id,
            application_protocol_error_code,
            final_size,
        })
    }
}

/// A STOP_SENDING frame following [Section 19.5].
///
/// Communicates that incoming data is being discarded on receipt per application request.
///
/// [Section 19.5]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.5
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StopSendingFrame {
    /// The [stream ID](StreamId) of the stream being ignored.
    pub stream_id: StreamId,
    /// The application-specified reason the sender is ignoring the stream.
    pub application_protocol_error_code: VarInt,
}

impl StopSendingFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::StopSending as u64);
}

impl Codec for StopSendingFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.stream_id.encode(writer, ())?;
        self.application_protocol_error_code.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let stream_id = StreamId::decode(reader, ())?;
        let application_protocol_error_code = VarInt::decode(reader, ())?;
        Ok(Self {
            stream_id,
            application_protocol_error_code,
        })
    }
}

/// A CRYPTO frame following [Section 19.6].
///
/// Transmits cryptographic handshake messages.
///
/// [Section 19.6]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.6
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CryptoFrame {
    /// The byte offset in the stream for the data in this CRYPTO frame.
    pub offset: VarInt,
    /// The cryptographic message data.
    pub crypto_data: Vec<u8>,
}

impl CryptoFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::Crypto as u64);

    /// The length of the Crypto Data field in this CRYPTO frame
    pub fn calculate_length(&self) -> VarInt {
        VariableLengthInteger(self.crypto_data.len() as u64)
    }
}

impl Codec for CryptoFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.offset.encode(writer, ())?;
        self.calculate_length().encode(writer, ())?;
        self.crypto_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let offset = VarInt::decode(reader, ())?;
        let length = (VarInt::decode(reader, ())?).into_inner();
        let mut crypto_data = [0u8; 1400];
        let mut crypto_data = &mut crypto_data[..length as usize];
        reader.read_into(&mut crypto_data)?;
        let crypto_data = crypto_data.to_vec();
        Ok(Self {
            offset,
            crypto_data,
        })
    }
}

/// A NEW_TOKEN frame following [Section 19.7].
///
/// Provides the client with a token to send in the header of an Initial packet for
/// a future connection.
///
/// [Section 19.7]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.7
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NewTokenFrame {
    /// An opaque blob that the client can use with a future Initial packet.
    pub token: RetryToken,
}

impl NewTokenFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::NewToken as u64);

    /// The length of the token in bytes.
    pub fn calculate_token_length(&self) -> VarInt {
        VariableLengthInteger(self.token.0.len() as u64)
    }
}

impl Codec for NewTokenFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.calculate_token_length().encode(writer, ())?;
        self.token.0.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        let length = (VarInt::decode(reader, ())?).into_inner();
        let mut token = [0u8; 1400];
        let mut token = &mut token[..length as usize];
        reader.read_into(&mut token)?;
        let token = RetryToken(token.to_vec());
        Ok(Self { token })
    }
}

/// A STREAM frame following [Section 19.8].
///
/// Implicitly creates a stream and carries stream data.
///
/// [Section 19.8]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.8
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StreamFrame {
    /// The stream ID of the stream.
    pub stream_id: StreamId,
    /// The byte offset in the stream for the data in this STREAM frame.
    pub offset: Option<VarInt>,
    ///
    pub length: Option<VarInt>,
    ///
    pub fin: bool,
    /// The bytes from the designated stream to be delivered.
    pub stream_data: Vec<u8>,
}

impl StreamFrame {
    ///
    pub const TYPE: VarInt = VarInt::new_const(0x08);
    ///
    pub const TYPE_OFF: VarInt = VarInt::new_const(0x0c);
    ///
    pub const TYPE_LEN: VarInt = VarInt::new_const(0x0a);
    ///
    pub const TYPE_FIN: VarInt = VarInt::new_const(0x09);
    ///
    pub const TYPE_LEN_FIN: VarInt = VarInt::new_const(0x0b);
    ///
    pub const TYPE_OFF_LEN: VarInt = VarInt::new_const(0x0e);
    ///
    pub const TYPE_OFF_FIN: VarInt = VarInt::new_const(0x0d);
    ///
    pub const TYPE_OFF_LEN_FIN: VarInt = VarInt::new_const(0x0f);

    ///
    pub fn calculate_type(&self) -> VarInt {
        match self.offset {
            // OFF
            Some(_) => match self.length {
                // LEN
                Some(_) => match self.fin {
                    true => Self::TYPE_OFF_LEN_FIN,
                    false => Self::TYPE_OFF_LEN,
                },
                // !LEN
                None => match self.fin {
                    true => Self::TYPE_OFF_FIN,
                    false => Self::TYPE_OFF,
                },
            },
            // !OFF
            None => match self.length {
                // LEN
                Some(_) => match self.fin {
                    true => Self::TYPE_LEN_FIN,
                    false => Self::TYPE_LEN,
                },
                // !LEN
                None => match self.fin {
                    // FIN
                    true => Self::TYPE_FIN,
                    // !FIN
                    false => Self::TYPE,
                },
            },
        }
    }

    /// The length of the Stream Data field in this STREAM frame.
    pub fn calculate_length(&self) -> VarInt {
        VariableLengthInteger(self.stream_data.len() as u64)
    }
}

impl Codec for StreamFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.calculate_type().encode(writer, ())?;
        self.stream_id.encode(writer, ())?;

        match self.offset {
            Some(offset) => offset.encode(writer, ()),
            None => Ok(()),
        }?;

        match self.length {
            Some(_) => self.calculate_length().encode(writer, ()),
            None => Ok(()),
        }?;

        self.stream_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let typ = VariableLengthInteger::decode(reader, ())?;
        let stream_id = StreamId::decode(reader, ())?;
        let (offset, length, fin) = match typ {
            Self::TYPE => (None, None, false),
            Self::TYPE_FIN => (None, None, true),
            Self::TYPE_LEN => (None, Some(VarInt::decode(reader, ())?), false),
            Self::TYPE_LEN_FIN => (None, Some(VarInt::decode(reader, ())?), true),
            Self::TYPE_OFF => (
                Some(VariableLengthInteger::decode(reader, ())?),
                None,
                false,
            ),
            Self::TYPE_OFF_FIN => (Some(VarInt::decode(reader, ())?), None, true),
            Self::TYPE_OFF_LEN => (
                Some(VarInt::decode(reader, ())?),
                Some(VarInt::decode(reader, ())?),
                false,
            ),
            Self::TYPE_OFF_LEN_FIN => (
                Some(VarInt::decode(reader, ())?),
                Some(VarInt::decode(reader, ())?),
                true,
            ),
            _ => return Err(BufError::UnexpectedValue),
        };

        let stream_data = match length {
            Some(x) => Vec::decode(reader, x.0 as usize)?,
            None => Vec::decode(reader, ())?,
        };

        Ok(Self {
            stream_id,
            offset,
            length,
            fin,
            stream_data,
        })
    }
}

/// A stream ID of the [STREAM frame] by [Section 2.1].
///
/// > description
///
/// [STREAM frame]: StreamFrame
/// [Section 2.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-2.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StreamId(pub VarInt);

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

/// A Stream Type of the [stream ID] by [Section 2.1].
///
/// > description
///
/// [stream ID]: StreamId
/// [Section 2.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-2.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u8)]
pub enum StreamType {
    /// Client-Initiated, Bidirectional.
    ClientInitiatedBidirectional = 0x00,
    /// Server-Initiated, Bidirectional.
    ServerInitiatedBidirectional = 0x01,
    /// Client-Initiated, Unidirectional.
    ClientInitiatedUnidirectional = 0x02,
    /// Server-Initiated, Unidirectional.
    ServerInitiatedUnidirectional = 0x03,
}

impl Codec for StreamType {
    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::ClientInitiatedBidirectional as u8) => {
                Ok(Self::ClientInitiatedBidirectional)
            }
            x if x == (Self::ServerInitiatedBidirectional as u8) => {
                Ok(Self::ServerInitiatedBidirectional)
            }
            x if x == (Self::ClientInitiatedUnidirectional as u8) => {
                Ok(Self::ClientInitiatedUnidirectional)
            }
            x if x == (Self::ServerInitiatedUnidirectional as u8) => {
                Ok(Self::ServerInitiatedUnidirectional)
            }
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A MAX_DATA frame following [Section 19.9].
///
/// Informs the peer of the maximum amount of data that can be sent on the connection as a whole.
///
/// [Section 19.9]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.9
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaxDataFrame {
    /// The maximum amount of data that can be sent on the entire connection, in units of bytes.
    pub maximum_data: VarInt,
}

impl MaxDataFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::MaxData as u64);
}

impl Codec for MaxDataFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.maximum_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            maximum_data: VarInt::decode(reader, ())?,
        })
    }
}

/// A MAX_STREAM_DATA frame following [Section 19.10].
///
/// Inform a peer of the maximum amount of data that can be sent on a stream.
///
/// [Section 19.10]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.10
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaxStreamDataFrame {
    /// The [stream ID](StreamId) of the affected stream.
    pub stream_id: StreamId,
    /// The maximum amount of data that can be sent on the identified stream, in units of bytes.
    pub maximum_stream_data: VarInt,
}

impl MaxStreamDataFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::MaxStreamData as u64);
}

impl Codec for MaxStreamDataFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.stream_id.encode(writer, ())?;
        self.maximum_stream_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            stream_id: StreamId::decode(reader, ())?,
            maximum_stream_data: VariableLengthInteger::decode(reader, ())?,
        })
    }
}

/// A MAX_STREAMS frame following [Section 19.11].
///
/// Informs the peer of the cumulative number of streams of a given type it is permitted to open.
///
/// [Section 19.11]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.11
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct MaxStreamsFrame {
    /// A count of the cumulative number of streams of the corresponding type
    /// that can be opened over the lifetime of the connection.
    pub maximum_streams: VarInt,
    ///
    pub bidirectional: bool,
}

impl MaxStreamsFrame {
    ///
    pub const TYPE_BIDIRECTRIONAL: VarInt = VarInt::new_const(0x12);
    ///
    pub const TYPE_UNIDIRECTRIONAL: VarInt = VarInt::new_const(0x13);

    ///
    pub fn calculate_type(&self) -> VarInt {
        match self.bidirectional {
            true => Self::TYPE_BIDIRECTRIONAL,
            false => Self::TYPE_UNIDIRECTRIONAL,
        }
    }
}

impl Codec for MaxStreamsFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.calculate_type().encode(writer, ())?;
        self.maximum_streams.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let bidirectional = match VarInt::decode(reader, ())? {
            Self::TYPE_BIDIRECTRIONAL => true,
            Self::TYPE_UNIDIRECTRIONAL => false,
            _ => return Err(BufError::UnexpectedValue),
        };
        let maximum_streams = VariableLengthInteger::decode(reader, ())?;
        Ok(Self {
            maximum_streams,
            bidirectional,
        })
    }
}

/// A DATA_BLOCKED frame following [Section 19.12].
///
/// Indicates that sender wishes to send data but is unable to do so due
/// to connection-level flow control.
///
/// [Section 19.12]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.12
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DataBlockedFrame {
    /// The connection-level limit at which blocking occurred.
    pub maximum_data: VarInt,
}

impl DataBlockedFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::DataBlocked as u64);
}

impl Codec for DataBlockedFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.maximum_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            maximum_data: VarInt::decode(reader, ())?,
        })
    }
}

/// A STREAM_DATA_BLOCKED frame following [Section 19.13].
///
/// Indicates that sender wishes to send data but is unable to do so due
/// to stream-level flow control.
///
/// [Section 19.13]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.13
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StreamDataBlockedFrame {
    /// The stream that is blocked due to flow control.
    pub stream_id: StreamId,
    /// The offset of the stream at which the blocking occurred.
    pub maximum_stream_data: VarInt,
}

impl StreamDataBlockedFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::StreamDataBlocked as u64);
}

impl Codec for StreamDataBlockedFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.stream_id.encode(writer, ())?;
        self.maximum_stream_data.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            stream_id: StreamId::decode(reader, ())?,
            maximum_stream_data: VarInt::decode(reader, ())?,
        })
    }
}

/// A STREAMS_BLOCKED frame following [Section 19.14].
///
/// Indicates that a sender wishes to open a stream but is unable to do so due to
/// the maximum stream limit set by peer.
///
/// [Section 19.14]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.14
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StreamsBlockedFrame {
    /// The maximum number of streams allowed at the time the frame was sent.
    pub maximum_streams: VarInt,
    ///
    pub bidirectional: bool,
}

impl StreamsBlockedFrame {
    ///
    pub const TYPE_BIDIRECTRIONAL: VarInt = VarInt::new_const(0x16);
    ///
    pub const TYPE_UNIDIRECTRIONAL: VarInt = VarInt::new_const(0x17);

    ///
    pub fn calculate_type(&self) -> VarInt {
        match self.bidirectional {
            true => Self::TYPE_BIDIRECTRIONAL,
            false => Self::TYPE_UNIDIRECTRIONAL,
        }
    }
}

impl Codec for StreamsBlockedFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.calculate_type().encode(writer, ())?;
        self.maximum_streams.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let bidirectional = match VarInt::decode(reader, ())? {
            Self::TYPE_BIDIRECTRIONAL => true,
            Self::TYPE_UNIDIRECTRIONAL => false,
            _ => return Err(BufError::UnexpectedValue),
        };
        let maximum_streams = VariableLengthInteger::decode(reader, ())?;
        Ok(Self {
            maximum_streams,
            bidirectional,
        })
    }
}

/// A NEW_CONNECTION_ID frame following [Section 19.15].
///
/// Provides its peer with alternative [connection ID]s that can be used to break linkability
/// when migrating connections.
///
/// [connection ID]: ConnectionId
/// [Section 19.15]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.15
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NewConnectionIdFrame {
    /// The sequence number assigned to the connection ID by the sender.
    pub sequence_number: VarInt,
    /// An integer indicating which connection IDs should be retired.
    pub retire_prior_to: VarInt,
    /// The Connection ID.
    pub connection_id: ConnectionId,
    /// A value that will be used for a stateless reset when the associated connection ID is used.
    pub stateless_reset_token: [u8; 16],
}

impl NewConnectionIdFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::NewConnectionId as u64);
}

impl Codec for NewConnectionIdFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        Self::TYPE.encode(writer, ())?;
        self.sequence_number.encode(writer, ())?;
        self.retire_prior_to.encode(writer, ())?;
        self.connection_id.encode(writer, ())?;
        self.stateless_reset_token.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            sequence_number: VarInt::decode(reader, ())?,
            retire_prior_to: VarInt::decode(reader, ())?,
            connection_id: ConnectionId::decode(reader, ())?,
            stateless_reset_token: reader.read_array::<16>()?,
        })
    }
}

/// A RETIRE_CONNECTION_ID frame following [Section 19.16].
///
/// Indicates that sending endpoint no longer use a [connection ID] that was issued by its peer.
///
/// [connection ID]: ConnectionId
/// [Section 19.16]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.16
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct RetireConnectionIdFrame {
    /// The sequence number of the connection ID being retired.
    pub sequence_number: VarInt,
}

impl RetireConnectionIdFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::RetireConnectionId as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            sequence_number: VarInt::decode(reader, ())?,
        })
    }
}

/// A PATH_CHALLENGE frame following [Section 19.17].
///
/// Checks reachability to the peer and validates path during connection migration.
///
/// [Section 19.17]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.17
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PathChallengeFrame {
    /// Arbitrary data.
    pub data: [u8; 8],
}

impl PathChallengeFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::PathChallenge as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            data: reader.read_array::<8>()?,
        })
    }
}

/// A PATH_RESPONSE frame following [Section 19.18].
///
/// Response to a [PATH_CHALLENGE frame].
///
/// [PATH_CHALLENGE frame]: PathChallengeFrame
/// [Section 19.18]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.18
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PathResponseFrame {
    /// The same data as in the Data field of the [PATH_CHALLENGE frame](PathChallengeFrame).
    pub data: [u8; 8],
}

impl PathResponseFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::PathResponse as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {
            data: reader.read_array::<8>()?,
        })
    }
}

/// A CONNECTION_CLOSE frame following [Section 19.19].
///
/// Notifies peer that the connection is being closed.
///
/// [Section 19.19]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.19
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ConnectionCloseFrame {
    ///
    pub error_code: VarInt,
    ///
    pub frame_type: Option<VarInt>,
    ///
    pub reason_phrase: Vec<u8>,
}

impl ConnectionCloseFrame {
    ///
    pub const TYPE_QUIC: VarInt = VarInt::new_const(0x1c);
    ///
    pub const TYPE_APPLICATION: VarInt = VarInt::new_const(0x1d);

    ///
    pub fn calculate_type(&self) -> VarInt {
        match self.frame_type {
            Some(_) => Self::TYPE_QUIC,
            None => Self::TYPE_APPLICATION,
        }
    }
}

impl Codec for ConnectionCloseFrame {
    fn encode<W: BufMut>(&self, writer: &mut Cursor<W>, _: ()) -> BufResult<()> {
        self.calculate_type().encode(writer, ())?;
        self.error_code.encode(writer, ())?;

        match self.frame_type {
            Some(frame_type) => frame_type.encode(writer, ()),
            None => Ok(()),
        }?;

        (VarInt::new(self.reason_phrase.len() as u64)?).encode(writer, ())?;
        self.reason_phrase.encode(writer, ())
    }

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        let r#type = (VarInt::decode(reader, ())?).0;
        let error_code = VarInt::decode(reader, ())?;
        let frame_type = match r#type {
            0x1d => None,
            0x1c => Some(VarInt::decode(reader, ())?),
            _ => return Err(BufError::UnexpectedValue),
        };
        let reason_phrase_length = (VarInt::decode(reader, ())?).0;
        let mut reason_phrase = [0u8; 1400];
        let mut reason_phrase = &mut reason_phrase[..reason_phrase_length as usize];
        reader.read_into(&mut reason_phrase)?;
        let reason_phrase = reason_phrase.to_vec();
        Ok(Self {
            error_code,
            frame_type,
            reason_phrase,
        })
    }
}

/// Transport Error Codes of the [CONNECTION_CLOSE frame] by [Section 20.1].
///
/// > description
///
/// [CONNECTION_CLOSE frame]: ConnectionCloseFrame
/// [Section 20.1]: https://datatracker.ietf.org/doc/html/rfc9000#section-20.1
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(u64)]
pub enum TransportErrorCode {
    /// NO_ERROR 0x00: No error
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    NoError = 0x00,

    /// INTERNAL_ERROR 0x01: Implementation error
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    InternalError = 0x01,

    /// CONNECTION_REFUSED 0x02: Server refuses a connection
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    ConnectionRefused = 0x02,

    /// FLOW_CONTROL_ERROR 0x03: Flow control error
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    FlowControlError = 0x03,

    /// STREAM_LIMIT_ERROR 0x04: Too many streams opened
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    StreamLimitError = 0x04,

    /// STREAM_STATE_ERROR 0x05: Frame received in invalid stream state
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    StreamStateError = 0x05,

    /// FINAL_SIZE_ERROR 0x06: Change to final size
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    FinalSizeError = 0x06,

    /// FRAME_ENCODING_ERROR 0x07: Frame encoding error
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    FrameEncodingError = 0x07,

    /// TRANSPORT_PARAMETER_ERROR 0x08: Error in transport parameters
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    TransportParameterError = 0x08,

    /// CONNECTION_ID_LIMIT_ERROR 0x09: Too many connection IDs received
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    ConnectionIdLimitError = 0x09,

    /// PROTOCOL_VIOLATION 0x0a: Generic protocol violation
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    ProtocolViolation = 0x0a,

    /// INVALID_TOKEN 0x0b: Invalid Token received
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    InvalidToken = 0x0b,

    /// APPLICATION_ERROR 0x0c: Application error
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    ApplicationError = 0x0c,

    /// CRYPTO_BUFFER_EXCEEDED 0x0d: CRYPTO data buffer overflowed
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    CryptoBufferExceeded = 0x0d,

    /// KEY_UPDATE_ERROR 0x0e: Invalid packet protection update
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    KeyUpdateError = 0x0e,

    /// AEAD_LIMIT_REACHED 0x0f: Excessive use of packet protection keys
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    AeadLimitReached = 0x0f,

    /// NO_VIABLE_PATH 0x10: No viable network path exists
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    NoViablePath = 0x10,

    /// CRYPTO_ERROR 0x0100..0x01ff: TLS alert code
    /// [Section 20.1](https://datatracker.ietf.org/doc/html/rfc9000#section-20.1)
    CryptoError = 0x0100,
}

impl From<TransportErrorCode> for VarInt {
    fn from(value: TransportErrorCode) -> Self {
        Self(value as u64)
    }
}

impl TryFrom<VarInt> for TransportErrorCode {
    type Error = BufError;

    fn try_from(value: VarInt) -> Result<Self, Self::Error> {
        Self::try_from(value.into_inner())
    }
}

impl From<TransportErrorCode> for u64 {
    fn from(value: TransportErrorCode) -> Self {
        value as u64
    }
}

impl TryFrom<u64> for TransportErrorCode {
    type Error = BufError;

    fn try_from(value: u64) -> Result<Self, Self::Error> {
        match value {
            x if x == Self::NoError as u64 => Ok(Self::NoError),
            x if x == Self::InternalError as u64 => Ok(Self::InternalError),
            x if x == Self::ConnectionRefused as u64 => Ok(Self::ConnectionRefused),
            x if x == Self::FlowControlError as u64 => Ok(Self::FlowControlError),
            x if x == Self::StreamLimitError as u64 => Ok(Self::StreamLimitError),
            x if x == Self::StreamStateError as u64 => Ok(Self::StreamStateError),
            x if x == Self::FinalSizeError as u64 => Ok(Self::FinalSizeError),
            x if x == Self::FrameEncodingError as u64 => Ok(Self::FrameEncodingError),
            x if x == Self::TransportParameterError as u64 => Ok(Self::TransportParameterError),
            x if x == Self::ConnectionIdLimitError as u64 => Ok(Self::ConnectionIdLimitError),
            x if x == Self::ProtocolViolation as u64 => Ok(Self::ProtocolViolation),
            x if x == Self::InvalidToken as u64 => Ok(Self::InvalidToken),
            x if x == Self::ApplicationError as u64 => Ok(Self::ApplicationError),
            x if x == Self::CryptoBufferExceeded as u64 => Ok(Self::CryptoBufferExceeded),
            x if x == Self::KeyUpdateError as u64 => Ok(Self::KeyUpdateError),
            x if x == Self::AeadLimitReached as u64 => Ok(Self::AeadLimitReached),
            x if x == Self::NoViablePath as u64 => Ok(Self::NoViablePath),
            x if x >= Self::CryptoError as u64 && x <= 0x01ff => Ok(Self::CryptoError),
            _ => Err(BufError::UnexpectedValue),
        }
    }
}

/// A HANDSHAKE_DONE frame following [Section 19.20].
///
/// Signals confirmation of the handshake to the client.
///
/// [Section 19.20]: https://datatracker.ietf.org/doc/html/rfc9000#section-19.20
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct HandshakeDoneFrame;

impl HandshakeDoneFrame {
    ///
    pub const TYPE: VarInt = VariableLengthInteger(FrameType::HandshakeDone as u64);
}

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

    fn decode<R: Buf>(reader: &mut Cursor<R>, _: ()) -> BufResult<Self> {
        if VarInt::decode(reader, ())? != Self::TYPE {
            return Err(BufError::UnexpectedValue);
        }
        Ok(Self {})
    }
}

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

    use crate::{
        Codec, Cursor,
        ietf::quicv1::{
            AckFrame, AckRange, ConnectionCloseFrame, ConnectionId, CryptoFrame, DataBlockedFrame,
            EcnCounts, HandshakeDoneFrame, MaxDataFrame, MaxStreamDataFrame, MaxStreamsFrame,
            NewConnectionIdFrame, NewTokenFrame, PaddingFrame, PathChallengeFrame,
            PathResponseFrame, PingFrame, ResetStreamFrame, RetireConnectionIdFrame, RetryToken,
            StopSendingFrame, StreamDataBlockedFrame, StreamFrame, StreamId, StreamsBlockedFrame,
            VariableLengthInteger,
        },
    };

    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 padding() {
        let etalon_bytes = &[0x00];
        let etalon_struct = PaddingFrame {};

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn ping() {
        let etalon_bytes = &[0x01];
        let etalon_struct = PingFrame {};

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn ack() {
        let etalon_bytes = &[0x02, 0x05, 0x00, 0x01, 0x01, 0x00, 0x00];
        let etalon_struct = AckFrame {
            largest_acknowledged: VariableLengthInteger(5),
            ack_delay: VariableLengthInteger(0),
            first_ack_range: VariableLengthInteger(1),
            ack_ranges: vec![AckRange {
                gap: VariableLengthInteger(0),
                ack_range_length: VariableLengthInteger(0),
            }],
            ecn_counts: None,
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0x03, 0x05, 0x00, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00];
        let etalon_struct = AckFrame {
            largest_acknowledged: VariableLengthInteger(5),
            ack_delay: VariableLengthInteger(0),
            first_ack_range: VariableLengthInteger(1),
            ack_ranges: vec![AckRange {
                gap: VariableLengthInteger(0),
                ack_range_length: VariableLengthInteger(0),
            }],
            ecn_counts: Some(EcnCounts {
                ect0_count: VariableLengthInteger(0),
                ect1_count: VariableLengthInteger(0),
                ecn_ce_count: VariableLengthInteger(0),
            }),
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn reset_stream() {
        let etalon_bytes = &[0x04, 0x00, 0x00, 0x00];
        let etalon_struct = ResetStreamFrame {
            stream_id: StreamId(VariableLengthInteger::new_const(0)),
            application_protocol_error_code: VariableLengthInteger::new_const(0),
            final_size: VariableLengthInteger::new_const(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn stop_sending() {
        let etalon_bytes = &[0x05, 0x00, 0x00];
        let etalon_struct = StopSendingFrame {
            stream_id: StreamId(VariableLengthInteger::new_const(0)),
            application_protocol_error_code: VariableLengthInteger::new_const(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn crypto() {
        let etalon_bytes = &[0x06, 0x00, 0x03, 0x40, 0x40, 0x40];
        let etalon_struct = CryptoFrame {
            offset: VariableLengthInteger(0),
            crypto_data: vec![0x40, 0x40, 0x40],
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn new_token() {
        let etalon_bytes = &[0x07, 0x05, 0x05, 0x05, 0x05, 0x05, 0x05];
        let etalon_struct = NewTokenFrame {
            token: RetryToken(vec![0x05, 0x05, 0x05, 0x05, 0x05]),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn stream() {
        // []
        let etalon_bytes = &[0x08, 0x00, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: None,
            length: None,
            fin: false,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ OFF ]
        let etalon_bytes = &[0x0c, 0x00, 0x00, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: Some(VariableLengthInteger::new_const(0)),
            length: None,
            fin: false,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ LEN ]
        let etalon_bytes = &[0x0a, 0x00, 0x01, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: None,
            length: Some(VariableLengthInteger::new_const(1)),
            fin: false,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ FIN ]
        let etalon_bytes = &[0x09, 0x00, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: None,
            length: None,
            fin: true,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ OFF, LEN ]
        let etalon_bytes = &[0x0e, 0x00, 0x00, 0x01, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: Some(VariableLengthInteger::new_const(0)),
            length: Some(VariableLengthInteger::new_const(1)),
            fin: false,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ OFF, FIN ]
        let etalon_bytes = &[0x0d, 0x00, 0x00, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: Some(VariableLengthInteger::new_const(0)),
            length: None,
            fin: true,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        // [ OFF, LEN, FIN ]
        let etalon_bytes = &[0x0f, 0x00, 0x00, 0x01, 0x00];
        let etalon_struct = StreamFrame {
            stream_id: StreamId(VariableLengthInteger(0)),
            offset: Some(VariableLengthInteger::new_const(0)),
            length: Some(VariableLengthInteger::new_const(1)),
            fin: true,
            stream_data: vec![0x00],
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn max_data() {
        let etalon_bytes = &[0x10, 0x00];
        let etalon_struct = MaxDataFrame {
            maximum_data: VariableLengthInteger::new_const(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn max_stream_data() {
        let etalon_bytes = &[0x11, 0x00, 0x00];
        let etalon_struct = MaxStreamDataFrame {
            stream_id: StreamId(VariableLengthInteger::new_const(0)),
            maximum_stream_data: VariableLengthInteger::new_const(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn max_streams() {
        let etalon_bytes = &[0x12, 0x00];
        let etalon_struct = MaxStreamsFrame {
            maximum_streams: VariableLengthInteger::new_const(0),
            bidirectional: true,
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0x13, 0x00];
        let etalon_struct = MaxStreamsFrame {
            maximum_streams: VariableLengthInteger::new_const(0),
            bidirectional: false,
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn data_blocked() {
        let etalon_bytes = &[0x14, 0x00];
        let etalon_struct = DataBlockedFrame {
            maximum_data: VariableLengthInteger::new_const(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn stream_data_blocked() {
        let etalon_bytes = &[0x15, 0x00, 0x00];
        let etalon_struct = StreamDataBlockedFrame {
            stream_id: StreamId(VariableLengthInteger::new_const(0)),
            maximum_stream_data: VariableLengthInteger::new_const(0),
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn streams_blocked() {
        let etalon_bytes = &[0x16, 0x00];
        let etalon_struct = StreamsBlockedFrame {
            maximum_streams: VariableLengthInteger(0),
            bidirectional: true,
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[0x17, 0x00];
        let etalon_struct = StreamsBlockedFrame {
            maximum_streams: VariableLengthInteger(0),
            bidirectional: false,
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn new_connection_id() {
        let etalon_bytes = &[
            0x018, 0x01, 0x02, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10,
            0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,
        ];
        let etalon_struct = NewConnectionIdFrame {
            sequence_number: VariableLengthInteger(1),
            retire_prior_to: VariableLengthInteger(2),
            connection_id: ConnectionId::new(&[0x08; 8]).unwrap(),
            stateless_reset_token: [16u8; 16],
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn retire_connection_id() {
        let etalon_bytes = &[0x19, 0x00];
        let etalon_struct = RetireConnectionIdFrame {
            sequence_number: VariableLengthInteger(0),
        };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn path_challenge() {
        let etalon_bytes = &[0x1A, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11];
        let etalon_struct = PathChallengeFrame { data: [0x11u8; 8] };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn path_response() {
        let etalon_bytes = &[0x1B, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13, 0x13];
        let etalon_struct = PathResponseFrame { data: [0x13u8; 8] };

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn connection_close() {
        let etalon_bytes = &[
            0x1c, 0x14, 0x06, 0x14, 50, 49, 55, 58, 72, 97, 110, 100, 115, 104, 97, 107, 101, 32,
            102, 97, 105, 108, 101, 100,
        ];
        let etalon_struct = ConnectionCloseFrame {
            error_code: VariableLengthInteger(0x14),
            frame_type: Some(VariableLengthInteger(0x06)),
            reason_phrase: b"217:Handshake failed".to_vec(),
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());

        let etalon_bytes = &[
            0x1d, 0x14, 0x14, 50, 49, 55, 58, 72, 97, 110, 100, 115, 104, 97, 107, 101, 32, 102,
            97, 105, 108, 101, 100,
        ];
        let etalon_struct = ConnectionCloseFrame {
            error_code: VariableLengthInteger(0x14),
            frame_type: None,
            reason_phrase: b"217:Handshake failed".to_vec(),
        };
        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }

    #[test]
    fn handshake_done() {
        let etalon_bytes = &[0x1E];
        let etalon_struct = HandshakeDoneFrame {};

        codec_roundtrip(etalon_struct, etalon_bytes, ());
    }
}