slither 0.4.0

Encrypted peer-to-peer UDP transport: reliable messages, streams and datagrams, authenticated by raw public keys - no certificates, no TLS. WireGuard-shaped handshake, QUIC-shaped frames.
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
//! §8 — the frame layer: the codec, the table, and the packing order.
//!
//! This is the *inner* wire. §2–§4's outer packet is [`crate::packet`] and
//! is complete; everything here lives inside a sealed Data packet's
//! plaintext, which the AEAD has already authenticated and whose exact
//! length the AEAD supplies (§8.2 — there is no packet-level length
//! prefix).
//!
//! # Four frames, and why the table still has fourteen rows
//!
//! Slice 3 implements PADDING (`0x00`), PING (`0x01`), ACK (`0x02`) and
//! CLOSE (`0x1c`). ACK is **codec only** here: §12's derivation and
//! processing are slice 5, so a received ACK parses and is then ignored.
//!
//! PADDING is not optional. §8.2 makes an unrecognised type a
//! `PROTOCOL_VIOLATION` kill, and §8.4 says of PADDING that "any number may
//! appear anywhere" — so a codec that implemented three frames would kill a
//! connection on a legal packet.
//!
//! The **classifiers** ([`is_ack_eliciting`], [`retransmission`]) cover all
//! fourteen rows of §8.3 — twelve at slice 3, plus §7.3's two path frames
//! (**[ruling 208]**) — including the types the parser cannot yet
//! build. That is deliberate and it is the only way they are testable:
//! every frame slice 3 builds is in the `never` retransmission class and
//! PING is the only ack-eliciting one among them, so a two-arm classifier
//! would be correct-by-accident for the whole slice. Slices 4–6 add parse
//! arms; they must not need to touch the classifiers.
//!
//! The parser and the classifiers therefore disagree, on purpose, about
//! what "known" means: the classifiers answer for the ratified table, the
//! parser answers for what this build can apply. Every type the parser does
//! not implement takes §8.2's unknown-type path.
//!
//! # Parse-then-apply is literal
//!
//! §8.2: *"**Parse the whole plaintext first, then apply.**"* [`parse`]
//! returns a `Vec<Frame>` and applies nothing. A streaming
//! parse-and-apply loop would pass every test that only checks "an unknown
//! type produces `ProtocolViolation`", and would differ observably on a
//! plaintext of `[valid CLOSE][unknown type]`: the correct implementation
//! surfaces `ProtocolViolation`, the streaming one surfaces `PeerClosed`.

use std::ops::RangeInclusive;

use crate::constants;
use crate::varint::{self, VarInt};

use super::stream_id::StreamId;

/// §8.5's round-robin quantum — *"one quantum per stream per fill pass, the
/// quantum size **implementation-defined**"*.
///
/// It lives here and **not** in [`crate::constants`] on purpose: a value in
/// that table is asserted by `tests/spec_constants.rs`, which would turn an
/// implementation-defined choice into a wire pin by accident. 1 KiB is a
/// little under one packet's plaintext, so a single stream still fills a
/// packet in one pass while two streams alternate within one.
pub(super) const STREAM_FILL_QUANTUM: usize = 1024;

// Ruling 270's conforming-frame hypothesis, guarded where it can drift:
// slither-as-sender must fill frames at least as large as the minimum its
// own receiver's credit-derived reassembly ceiling assumes conforming
// (`REASSEMBLY_MIN_CONFORMING_FRAME`). Lowering this quantum below that
// constant would silently carry slither's own saturating sender outside
// the guarantee ruling 270 proves — this assertion makes that a compile
// error instead (review finding F1, 2026/08/18).
const _: () =
    assert!(STREAM_FILL_QUANTUM as u64 >= crate::constants::REASSEMBLY_MIN_CONFORMING_FRAME);

/// §8.4's fixed body width for `PATH_CHALLENGE`/`PATH_RESPONSE`: **eight
/// opaque bytes, not a varint**. **[ruling 208]**
///
/// It lives here rather than in [`crate::constants`] for the same reason
/// [`STREAM_FILL_QUANTUM`] does not — except inverted: this one *is* wire,
/// and it is already pinned there by the §1.6 const assertion and by the
/// frame's own round-trip tests. A second name for it in the constants
/// table would be a second place to change it.
pub(super) const PATH_CHALLENGE_LEN: usize = 8;

/// A parsed frame. §8.3, §8.4.
///
/// The types this build does not implement are **absent rather than
/// stubbed**, following this module tree's precedent: a variant is a claim
/// that the layer can produce and consume the thing. Slice 4 adds §9's and
/// §10's six; §11's DATAGRAM arrives with slice 6.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Frame {
    /// `0x00` — a single byte, no fields, any number anywhere. §8.4.
    Padding,
    /// `0x01` — the type byte alone. Ack-eliciting. §8.4, §13.4.
    Ping,
    /// `0x02` — §12's acknowledgement. Codec only in this slice.
    Ack(Ack),
    /// `0x04` — §9.6's abrupt abandonment of a send half.
    ResetStream(ResetStream),
    /// `0x08`–`0x0f` — §9.5's labelled byte range.
    Stream(Stream),
    /// `0x10` — §10.3's connection-level credit grant.
    MaxData(u64),
    /// `0x11` — §10.3's stream-level credit grant.
    MaxStreamData(MaxStreamData),
    /// `0x12` — §10.4's cumulative bidirectional stream allowance.
    MaxStreamsBidi(u64),
    /// `0x13` — §10.4's cumulative unidirectional stream allowance.
    MaxStreamsUni(u64),
    /// `0x1a` — §7.3's return-routability challenge, eight opaque bytes.
    /// Ack-eliciting. **[ruling 208]**
    PathChallenge([u8; 8]),
    /// `0x1b` — `0x1a`'s eight bytes, echoed verbatim. Ack-eliciting.
    /// **[ruling 208]**
    PathResponse([u8; 8]),
    /// `0x1c` — §15's teardown signal.
    Close(Close),
    /// `0x30`/`0x31` — §11's unreliable payload. §8.4.
    Datagram(Datagram),
}

impl Frame {
    /// This frame's §8.3 type code.
    pub(crate) fn type_code(&self) -> u64 {
        match self {
            Frame::Padding => constants::FRAME_PADDING,
            Frame::Ping => constants::FRAME_PING,
            Frame::Ack(_) => constants::FRAME_ACK,
            Frame::ResetStream(_) => constants::FRAME_RESET_STREAM,
            Frame::Stream(stream) => stream.type_code(),
            Frame::MaxData(_) => constants::FRAME_MAX_DATA,
            Frame::MaxStreamData(_) => constants::FRAME_MAX_STREAM_DATA,
            Frame::MaxStreamsBidi(_) => constants::FRAME_MAX_STREAMS_BIDI,
            Frame::MaxStreamsUni(_) => constants::FRAME_MAX_STREAMS_UNI,
            Frame::PathChallenge(_) => constants::FRAME_PATH_CHALLENGE,
            Frame::PathResponse(_) => constants::FRAME_PATH_RESPONSE,
            Frame::Close(_) => constants::FRAME_CLOSE,
            Frame::Datagram(datagram) => datagram.type_code(),
        }
    }

    /// Whether this frame is ack-eliciting (§8.3's column).
    pub(crate) fn is_ack_eliciting(&self) -> bool {
        is_ack_eliciting(self.type_code())
    }

    /// The encoded length in bytes, type code included.
    pub(crate) fn encoded_len(&self) -> usize {
        match self {
            Frame::Padding | Frame::Ping => 1,
            Frame::Ack(ack) => 1 + ack.body_len(),
            Frame::ResetStream(reset) => 1 + reset.body_len(),
            Frame::Stream(stream) => 1 + stream.body_len(),
            Frame::MaxData(max) | Frame::MaxStreamsBidi(max) | Frame::MaxStreamsUni(max) => {
                1 + varint_len(*max)
            }
            Frame::MaxStreamData(grant) => 1 + grant.body_len(),
            // **[ruling 208]** Nine bytes, fixed: the one-byte type code
            // (both codes are far below 64, §8.1) and eight opaque bytes
            // with no length prefix.
            Frame::PathChallenge(_) | Frame::PathResponse(_) => 1 + PATH_CHALLENGE_LEN,
            Frame::Close(close) => 1 + close.body_len(),
            Frame::Datagram(datagram) => 1 + datagram.body_len(),
        }
    }

    /// Whether this frame extends to the end of the plaintext — §8.5's
    /// *"at most one … per packet, in final position"*.
    ///
    /// Two frame types can wear the form and [`Packing`] enforces the rule
    /// for both from here, which is why the check is a property of the
    /// **frame** and never of a fill loop: slice 6 adds DATAGRAM as a second
    /// contributor to stage 3, and a duplicated check is the one that
    /// drifts.
    pub(crate) fn extends_to_end(&self) -> bool {
        match self {
            Frame::Stream(s) => !s.len_present,
            Frame::Datagram(d) => !d.len_present,
            _ => false,
        }
    }

    /// Append this frame's wire encoding to `out`. §8.4.
    ///
    /// The type code is a varint like every other field (§8.1), and every
    /// code in §8.3's table is below 64, so each occupies one byte.
    pub(crate) fn encode(&self, out: &mut Vec<u8>) {
        varint::encode(
            VarInt::new(self.type_code()).expect("§8.3's type codes are all far below 2⁶² − 1"),
            out,
        );
        match self {
            Frame::Padding | Frame::Ping => {}
            Frame::Ack(ack) => ack.encode_body(out),
            Frame::ResetStream(reset) => reset.encode_body(out),
            Frame::Stream(stream) => stream.encode_body(out),
            Frame::MaxData(max) | Frame::MaxStreamsBidi(max) | Frame::MaxStreamsUni(max) => {
                put_varint(*max, out)
            }
            Frame::MaxStreamData(grant) => grant.encode_body(out),
            Frame::PathChallenge(value) | Frame::PathResponse(value) => {
                out.extend_from_slice(value)
            }
            Frame::Close(close) => close.encode_body(out),
            Frame::Datagram(datagram) => datagram.encode_body(out),
        }
    }
}

/// §8.4's DATAGRAM — §11's unreliable payload, in its two forms.
///
/// `type(0x30) ‖ data(to the end of the plaintext)` or
/// `type(0x31) ‖ length ‖ data`.
///
/// **The `0x30` form is not an optimisation.** `MAX_DATAGRAM_PAYLOAD` is
/// 1169 = `MAX_PLAINTEXT` − 1 and is *defined by* that form (§11.2): the
/// same payload as `0x31` needs `1 + 2 + 1169 = 1172` bytes and does not
/// fit a packet at all, so a build emitting only `0x31` can never send the
/// ratified maximum — and the failure is silent, the datagram simply never
/// fitting and eventually being evicted (ruling 155).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Datagram {
    /// The payload.
    pub(crate) data: Vec<u8>,
    /// `false` ⇒ type `0x30`, no length field, **extends to the end of the
    /// plaintext and must be the packet's final frame**.
    /// `true` ⇒ type `0x31`, explicit varint length.
    pub(crate) len_present: bool,
}

impl Datagram {
    /// The type code, with §8.4's one flag bit applied.
    pub(crate) fn type_code(&self) -> u64 {
        if self.len_present {
            constants::FRAME_DATAGRAM_LEN
        } else {
            constants::FRAME_DATAGRAM
        }
    }

    fn body_len(&self) -> usize {
        if self.len_present {
            varint_len(self.data.len() as u64) + self.data.len()
        } else {
            self.data.len()
        }
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        if self.len_present {
            put_varint(self.data.len() as u64, out);
        }
        out.extend_from_slice(&self.data);
    }

    /// Parse a DATAGRAM body. `ty` carries the LEN bit.
    ///
    /// §8.4's second structural error — *"a `0x30` frame that is not the
    /// packet's final frame"* — is **not decidable here** and is not
    /// attempted here: a `0x30` body consumes the remainder by definition,
    /// so after this returns the cursor is at the end and the loop
    /// terminates. See [`parse`] for where the check would have to live and
    /// why it is unreachable there too.
    fn parse_body(ty: u64, buf: &[u8]) -> Result<(Datagram, usize), Structural> {
        let len_present = ty == constants::FRAME_DATAGRAM_LEN;
        let mut cursor = Cursor::new(buf);
        let data = if len_present {
            let len = cursor.varint()?;
            let len = usize::try_from(len).map_err(|_| Structural::LengthOverrun)?;
            cursor.bytes(len)?.to_vec()
        } else {
            let rest = cursor.rest().to_vec();
            cursor.advance(rest.len());
            rest
        };
        Ok((Datagram { data, len_present }, cursor.consumed()))
    }
}

/// §8.4's RESET_STREAM: `type(0x04) ‖ stream_id ‖ error_code ‖ final_size`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ResetStream {
    /// The stream being abandoned.
    pub(crate) id: StreamId,
    /// §9.6's application code.
    pub(crate) error_code: u64,
    /// The number of bytes the stream would have carried.
    pub(crate) final_size: u64,
}

impl ResetStream {
    fn body_len(&self) -> usize {
        varint_len(self.id.as_u64()) + varint_len(self.error_code) + varint_len(self.final_size)
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        put_varint(self.id.as_u64(), out);
        put_varint(self.error_code, out);
        put_varint(self.final_size, out);
    }

    fn parse_body(buf: &[u8]) -> Result<(ResetStream, usize), Structural> {
        let mut cursor = Cursor::new(buf);
        let id = StreamId::from_u64(cursor.varint()?);
        let error_code = cursor.varint()?;
        let final_size = cursor.varint()?;
        Ok((
            ResetStream {
                id,
                error_code,
                final_size,
            },
            cursor.consumed(),
        ))
    }
}

/// §8.4's STREAM frame — the labelled byte range of §9.5.
///
/// The three flag bits are carried explicitly rather than derived, so a
/// parse-then-encode round trip is byte-identical for any frame a peer sent:
/// `OFF` with an offset of zero is legal and distinguishable from `¬OFF`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Stream {
    /// The stream this range belongs to.
    pub(crate) id: StreamId,
    /// The offset of the first byte.
    pub(crate) offset: u64,
    /// Whether the `OFF` bit is set. Implied by `offset != 0`, but a sender
    /// may set it for offset zero.
    pub(crate) off_present: bool,
    /// Whether the `LEN` bit is set. When clear the data extends to the end
    /// of the plaintext.
    pub(crate) len_present: bool,
    /// §9.5: FIN pins the final size as this frame's end offset.
    pub(crate) fin: bool,
    /// The bytes.
    pub(crate) data: Vec<u8>,
}

impl Stream {
    /// A frame this implementation emits: `LEN` always present, `OFF` only
    /// when it carries information.
    ///
    /// slither never emits the `¬LEN` form. §8.5 bounds it (*"at most
    /// one"*) rather than requiring it, and the one or two bytes it saves
    /// are not worth a stage-ordering hazard that only misfires once slice 6
    /// adds a second fill contributor. [`Packing`] still enforces the rule,
    /// so slice 6 inherits it rather than rebuilding it.
    pub(crate) fn new(id: StreamId, offset: u64, data: Vec<u8>, fin: bool) -> Self {
        Self {
            id,
            offset,
            off_present: offset != 0,
            len_present: true,
            fin,
            data,
        }
    }

    /// The type code with §8.4's three flag bits applied.
    pub(crate) fn type_code(&self) -> u64 {
        let mut ty = constants::FRAME_STREAM_BASE;
        if self.off_present {
            ty |= constants::STREAM_OFF;
        }
        if self.len_present {
            ty |= constants::STREAM_LEN;
        }
        if self.fin {
            ty |= constants::STREAM_FIN;
        }
        ty
    }

    fn body_len(&self) -> usize {
        varint_len(self.id.as_u64())
            + if self.off_present {
                varint_len(self.offset)
            } else {
                0
            }
            + if self.len_present {
                varint_len(self.data.len() as u64)
            } else {
                0
            }
            + self.data.len()
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        put_varint(self.id.as_u64(), out);
        if self.off_present {
            put_varint(self.offset, out);
        }
        if self.len_present {
            put_varint(self.data.len() as u64, out);
        }
        out.extend_from_slice(&self.data);
    }

    /// Parse a STREAM body. `ty` carries the flags.
    fn parse_body(ty: u64, buf: &[u8]) -> Result<(Stream, usize), Structural> {
        let off_present = ty & constants::STREAM_OFF != 0;
        let len_present = ty & constants::STREAM_LEN != 0;
        let fin = ty & constants::STREAM_FIN != 0;

        let mut cursor = Cursor::new(buf);
        let id = StreamId::from_u64(cursor.varint()?);
        let offset = if off_present { cursor.varint()? } else { 0 };
        let data = if len_present {
            let len = cursor.varint()?;
            let len = usize::try_from(len).map_err(|_| Structural::LengthOverrun)?;
            cursor.bytes(len)?.to_vec()
        } else {
            // §8.4: *"the data extends to the end of the plaintext, and the
            // frame must be the packet's final frame."* Consuming the rest
            // is what makes the second clause hold by construction — see
            // this module's docs on the sender-side rule it really is.
            let rest = cursor.rest().to_vec();
            cursor.advance(rest.len());
            rest
        };

        // §8.4: *"`offset + length` exceeding 2⁶² − 1"* is structural. Every
        // downstream comparison in §9/§10 is then inside the varint domain.
        let end = offset
            .checked_add(data.len() as u64)
            .filter(|end| *end <= VarInt::MAX_VALUE)
            .ok_or(Structural::StreamOffsetOverflow)?;
        let _ = end;

        Ok((
            Stream {
                id,
                offset,
                off_present,
                len_present,
                fin,
                data,
            },
            cursor.consumed(),
        ))
    }
}

/// §8.4's MAX_STREAM_DATA: `type(0x11) ‖ stream_id ‖ max`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct MaxStreamData {
    /// The stream the grant applies to.
    pub(crate) id: StreamId,
    /// The absolute limit.
    pub(crate) max: u64,
}

impl MaxStreamData {
    fn body_len(&self) -> usize {
        varint_len(self.id.as_u64()) + varint_len(self.max)
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        put_varint(self.id.as_u64(), out);
        put_varint(self.max, out);
    }

    fn parse_body(buf: &[u8]) -> Result<(MaxStreamData, usize), Structural> {
        let mut cursor = Cursor::new(buf);
        let id = StreamId::from_u64(cursor.varint()?);
        let max = cursor.varint()?;
        Ok((MaxStreamData { id, max }, cursor.consumed()))
    }
}

/// §8.4's ACK, as its wire fields.
///
/// Held verbatim rather than as a decoded range set: slice 3 is the codec
/// and a round trip must be byte-identical. §12's semantics — what an ACK
/// means, when one is owed, how one is derived from §7.2's window — are
/// slice 5's.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Ack {
    /// The largest counter this ACK acknowledges.
    pub(crate) largest: u64,
    /// The delay between receiving `largest` and sending this ACK, in µs.
    pub(crate) ack_delay: u64,
    /// How many counters below `largest` the first range also covers.
    pub(crate) first_range: u64,
    /// Additional `(gap, range)` pairs, descending. At most
    /// [`MAX_ACK_RANGES`](crate::constants::MAX_ACK_RANGES).
    pub(crate) ranges: Vec<(u64, u64)>,
}

impl Ack {
    /// The acknowledged counter ranges, **newest-first, descending** —
    /// §12.2's construction order, read back.
    ///
    /// Only meaningful on an ACK that has been validated by [`parse`] or
    /// built from a validated window; [`Ack::validate`] is what excludes
    /// the descent below counter zero that would make this saturate.
    pub(crate) fn ranges_desc(&self) -> Vec<RangeInclusive<u64>> {
        let mut out = Vec::with_capacity(1 + self.ranges.len());
        let mut smallest = self.largest.saturating_sub(self.first_range);
        out.push(smallest..=self.largest);
        for (gap, range) in &self.ranges {
            let largest = smallest.saturating_sub(*gap).saturating_sub(2);
            smallest = largest.saturating_sub(*range);
            out.push(smallest..=largest);
        }
        out
    }

    /// §8.4's two structural error cases for ACK.
    ///
    /// *"`range_count` > `MAX_ACK_RANGES` (64); any range descending below
    /// counter zero."* The descent is QUIC's: each additional pair starts
    /// `gap + 2` below the previous range's smallest counter, so an
    /// underflow anywhere is the frame claiming counters that cannot exist.
    fn validate(&self) -> Result<(), Structural> {
        if self.ranges.len() > constants::MAX_ACK_RANGES {
            return Err(Structural::AckRangeCount(self.ranges.len() as u64));
        }
        let mut smallest = self
            .largest
            .checked_sub(self.first_range)
            .ok_or(Structural::AckRangeUnderflow)?;
        for (gap, range) in &self.ranges {
            let largest = smallest
                .checked_sub(*gap)
                .and_then(|v| v.checked_sub(2))
                .ok_or(Structural::AckRangeUnderflow)?;
            smallest = largest
                .checked_sub(*range)
                .ok_or(Structural::AckRangeUnderflow)?;
        }
        Ok(())
    }

    /// The encoded length in bytes, type code included — §12.2's
    /// packet-capacity truncation measures with this after every candidate
    /// pair, because a `(gap, range)` pair's own width depends on its
    /// values.
    pub(crate) fn encoded_len(&self) -> usize {
        varint_len(constants::FRAME_ACK) + self.body_len()
    }

    fn body_len(&self) -> usize {
        varint_len(self.largest)
            + varint_len(self.ack_delay)
            + varint_len(self.ranges.len() as u64)
            + varint_len(self.first_range)
            + self
                .ranges
                .iter()
                .map(|(gap, range)| varint_len(*gap) + varint_len(*range))
                .sum::<usize>()
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        put_varint(self.largest, out);
        put_varint(self.ack_delay, out);
        put_varint(self.ranges.len() as u64, out);
        put_varint(self.first_range, out);
        for (gap, range) in &self.ranges {
            put_varint(*gap, out);
            put_varint(*range, out);
        }
    }

    /// Parse an ACK body, returning it and the bytes consumed.
    fn parse_body(buf: &[u8]) -> Result<(Ack, usize), Structural> {
        let mut cursor = Cursor::new(buf);
        let largest = cursor.varint()?;
        let ack_delay = cursor.varint()?;
        let range_count = cursor.varint()?;

        // Checked before the pairs are read, so a bogus count cannot make
        // the parser allocate against a `u64` it will then fail on.
        if range_count > constants::MAX_ACK_RANGES as u64 {
            return Err(Structural::AckRangeCount(range_count));
        }
        let first_range = cursor.varint()?;

        let mut ranges = Vec::with_capacity(range_count as usize);
        for _ in 0..range_count {
            let gap = cursor.varint()?;
            let range = cursor.varint()?;
            ranges.push((gap, range));
        }

        let ack = Ack {
            largest,
            ack_delay,
            first_range,
            ranges,
        };
        ack.validate()?;
        Ok((ack, cursor.consumed()))
    }
}

/// §8.4's CLOSE.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Close {
    /// §15.3's registry code, or an application code ≥ `0x10`.
    pub(crate) code: u64,
    /// At most [`CLOSE_REASON_MAX`](crate::constants::CLOSE_REASON_MAX)
    /// bytes. SHOULD be UTF-8, carried as bytes.
    pub(crate) reason: Vec<u8>,
}

impl Close {
    /// A CLOSE, with `reason` truncated to `CLOSE_REASON_MAX` and `code`
    /// capped at the varint maximum.
    ///
    /// §8.4: *"an implementation must not be able to **produce** the
    /// over-length case it must kill on receipt."* §16.2 truncates at the
    /// handle; truncating here as well means no path through the core can
    /// build one, including the handle-free core tests.
    ///
    /// The `code` cap is **ruling 86**, and it lives here rather than in
    /// the encoder for one reason: it is the same rule as `reason`'s and
    /// belongs beside it. §16.2's `close(code: u64, …)` takes a bare
    /// `u64`, so a caller can hand it a value no varint encodes; §8.1's
    /// stated-consequence list named ACK `largest`, stream offsets and
    /// final sizes and **omitted this one** until ruling 86 added it.
    /// Capping rather than refusing keeps `close()` infallible, which
    /// §15.2's teardown requires.
    pub(crate) fn new(code: u64, reason: &[u8]) -> Self {
        let n = reason.len().min(constants::CLOSE_REASON_MAX);
        Self {
            code: code.min(VarInt::MAX_VALUE),
            reason: reason[..n].to_vec(),
        }
    }

    fn body_len(&self) -> usize {
        varint_len(self.code) + varint_len(self.reason.len() as u64) + self.reason.len()
    }

    fn encode_body(&self, out: &mut Vec<u8>) {
        debug_assert!(
            self.reason.len() <= constants::CLOSE_REASON_MAX,
            "§8.4: a CLOSE this implementation produced must never exceed CLOSE_REASON_MAX"
        );
        put_varint(self.code, out);
        put_varint(self.reason.len() as u64, out);
        out.extend_from_slice(&self.reason);
    }

    fn parse_body(buf: &[u8]) -> Result<(Close, usize), Structural> {
        let mut cursor = Cursor::new(buf);
        let code = cursor.varint()?;
        let reason_len = cursor.varint()?;
        if reason_len > constants::CLOSE_REASON_MAX as u64 {
            return Err(Structural::CloseReasonTooLong(reason_len));
        }
        let reason = cursor.bytes(reason_len as usize)?.to_vec();
        Ok((Close { code, reason }, cursor.consumed()))
    }
}

/// §8.2's structural failure class — a **signalled death**.
///
/// Every variant is answered identically on the wire: one trace on
/// `slither::frames`, CLOSE with `PROTOCOL_VIOLATION`, the closing state,
/// and `ConnectionLost::ProtocolViolation { code }`. The variants exist for
/// the trace, which is operator-visible contract (§18.2) — not for a
/// per-case behaviour, of which there is exactly one.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub(crate) enum Structural {
    /// A type code outside §8.3's table, or one reserved (`0x05`) or not
    /// implemented by this build.
    #[error("unknown frame type {0:#x}")]
    UnknownType(u64),
    /// A varint ran past the end of the plaintext.
    #[error("a varint overruns the plaintext")]
    VarintOverrun,
    /// A length-delimited field ran past the end of the plaintext.
    #[error("a length field overruns the plaintext")]
    LengthOverrun,
    /// ACK's `range_count` exceeded `MAX_ACK_RANGES`.
    #[error("ACK range_count {0} exceeds MAX_ACK_RANGES")]
    AckRangeCount(u64),
    /// An ACK range descended below counter zero.
    #[error("an ACK range descends below counter zero")]
    AckRangeUnderflow,
    /// CLOSE's `reason_len` exceeded `CLOSE_REASON_MAX`.
    #[error("CLOSE reason_len {0} exceeds CLOSE_REASON_MAX")]
    CloseReasonTooLong(u64),
    /// A STREAM frame's `offset + length` exceeded 2⁶² − 1. §8.4.
    #[error("a STREAM frame's offset + length exceeds 2⁶² − 1")]
    StreamOffsetOverflow,
    /// MAX_STREAMS' `max` exceeded 2⁶⁰ — unrepresentable as a stream index.
    /// §8.4. The boundary is `>`, not `≥`.
    #[error("MAX_STREAMS max {0} exceeds 2⁶⁰")]
    MaxStreamsTooLarge(u64),
    /// §8.4's *"a `0x30` frame that is not the packet's final frame"* — a
    /// frame followed something that extends to the end of the plaintext.
    ///
    /// **Unreachable against this parser, and minted anyway.** An
    /// extends-to-end body consumes the remainder *by definition*, so a
    /// following frame is absorbed into its data and is unobservable: the
    /// error §8.4 states on the receiver is really a **sender**
    /// prohibition wearing a receiver's clothes (`PLAN-6.md` §6 U-3, §7
    /// C-6). It exists so the rule is nameable in the trace §18.2 makes
    /// operator contract, and so the day a body parser gains a bound the
    /// guard is already the thing that fires.
    #[error("a frame follows one that extends to the end of the plaintext")]
    TrailingFrame,
}

/// §8.2's parse phase: the **whole** plaintext, applying nothing.
///
/// The caller applies the returned frames only if this returns `Ok` —
/// §8.2: *"Nothing from the packet is applied (no ACK scheduling, no state
/// change beyond the already-performed replay mark)."*
///
/// An empty plaintext never reaches here: it is §3.4's keepalive and
/// bypasses the frame layer entirely. Passing one in yields an empty frame
/// list rather than an error, because "no frames" is not a structural
/// failure — the short-circuit belongs at the receive path, where §3.4 puts
/// it, and is not duplicated here as a second opinion.
pub(crate) fn parse(plaintext: &[u8]) -> Result<Vec<Frame>, Structural> {
    let mut frames = Vec::new();
    let mut cursor = Cursor::new(plaintext);

    while !cursor.is_empty() {
        // §8.5: *"at most one extends-to-end frame … in final position"*.
        // Reaching here with one already parsed means a frame followed it.
        //
        // **This is dead by construction and deliberately written.** Both
        // extends-to-end bodies (¬LEN STREAM and `0x30` DATAGRAM) consume
        // `cursor.rest()`, so the loop condition above is already false —
        // see [`Structural::TrailingFrame`] for why the rule is minted
        // rather than dropped. It is not a second opinion on a check that
        // exists elsewhere: nothing else states it on the receive side.
        if frames.last().is_some_and(Frame::extends_to_end) {
            return Err(Structural::TrailingFrame);
        }
        // The type code is itself a varint (§8.1, §8.3's note on the gaps).
        let ty = cursor.varint()?;
        let frame = match ty {
            constants::FRAME_PADDING => Frame::Padding,
            constants::FRAME_PING => Frame::Ping,
            constants::FRAME_ACK => {
                let (ack, used) = Ack::parse_body(cursor.rest())?;
                cursor.advance(used);
                Frame::Ack(ack)
            }
            constants::FRAME_RESET_STREAM => {
                let (reset, used) = ResetStream::parse_body(cursor.rest())?;
                cursor.advance(used);
                Frame::ResetStream(reset)
            }
            ty @ constants::FRAME_STREAM_BASE..=constants::FRAME_STREAM_MAX => {
                let (stream, used) = Stream::parse_body(ty, cursor.rest())?;
                cursor.advance(used);
                Frame::Stream(stream)
            }
            constants::FRAME_MAX_DATA => Frame::MaxData(cursor.varint()?),
            constants::FRAME_MAX_STREAM_DATA => {
                let (grant, used) = MaxStreamData::parse_body(cursor.rest())?;
                cursor.advance(used);
                Frame::MaxStreamData(grant)
            }
            constants::FRAME_MAX_STREAMS_BIDI | constants::FRAME_MAX_STREAMS_UNI => {
                let max = cursor.varint()?;
                // §8.4's one structural error for MAX_STREAMS. The boundary
                // is `>`, not `≥`: §10.4's *"opening stream index `i`
                // requires cumulative limit > `i`"* makes 2⁶⁰ exactly the
                // limit that admits the largest representable index.
                if max > super::stream_id::MAX_STREAMS_CEILING {
                    return Err(Structural::MaxStreamsTooLarge(max));
                }
                if ty == constants::FRAME_MAX_STREAMS_BIDI {
                    Frame::MaxStreamsBidi(max)
                } else {
                    Frame::MaxStreamsUni(max)
                }
            }
            // **[ruling 208]** §8.4: *"fewer than 8 bytes remain in the
            // plaintext after the type byte"* is the **only** structural
            // error either frame has, and it is the existing
            // [`Structural::LengthOverrun`] — §8.2 answers every structural
            // failure identically and the variants exist for the trace, so a
            // new one would be an invention. Exactly eight bytes are taken:
            // a ninth belongs to the next frame, not to this one.
            ty @ (constants::FRAME_PATH_CHALLENGE | constants::FRAME_PATH_RESPONSE) => {
                let mut value = [0u8; PATH_CHALLENGE_LEN];
                value.copy_from_slice(cursor.bytes(PATH_CHALLENGE_LEN)?);
                if ty == constants::FRAME_PATH_CHALLENGE {
                    Frame::PathChallenge(value)
                } else {
                    Frame::PathResponse(value)
                }
            }
            constants::FRAME_CLOSE => {
                let (close, used) = Close::parse_body(cursor.rest())?;
                cursor.advance(used);
                Frame::Close(close)
            }
            constants::FRAME_DATAGRAM | constants::FRAME_DATAGRAM_LEN => {
                let (datagram, used) = Datagram::parse_body(ty, cursor.rest())?;
                cursor.advance(used);
                Frame::Datagram(datagram)
            }
            // Everything else — §8.3's `0x05` reserved row and any code
            // outside the table — is §8.2's unknown type.
            other => return Err(Structural::UnknownType(other)),
        };
        frames.push(frame);
    }

    Ok(frames)
}

/// Whether a packet carrying these frames is ack-eliciting (§8.7).
///
/// *"A packet is ack-eliciting iff it contains at least one ack-eliciting
/// frame."*
pub(crate) fn packet_is_ack_eliciting(frames: &[Frame]) -> bool {
    frames.iter().any(Frame::is_ack_eliciting)
}

/// §8.3's ack-eliciting column, as a pure function of the type code.
///
/// Table-driven over **all fourteen rows** — §8.3's twelve plus ruling
/// 208's `PATH_CHALLENGE`/`PATH_RESPONSE` — including the types this slice
/// cannot construct; see the module docs for why that is the only way this
/// is testable at all.
///
/// A code outside the table is not ack-eliciting because it is not a frame:
/// receiving one is §8.2's structural failure and the packet is never
/// applied. The answer here is unreachable for such a code and is `false`
/// rather than a panic, because a panic reachable from a received packet is
/// the wrong failure for a transport.
pub(crate) fn is_ack_eliciting(ty: u64) -> bool {
    match ty {
        constants::FRAME_PADDING => false,
        constants::FRAME_PING => true,
        constants::FRAME_ACK => false,
        constants::FRAME_RESET_STREAM => true,
        constants::FRAME_STREAM_BASE..=constants::FRAME_STREAM_MAX => true,
        constants::FRAME_MAX_DATA
        | constants::FRAME_MAX_STREAM_DATA
        | constants::FRAME_MAX_STREAMS_BIDI
        | constants::FRAME_MAX_STREAMS_UNI => true,
        // **[ruling 208]** Load-bearing twice over (§8.4): it is what puts
        // the challenge in the sent map so §7.3's death clock arms on it,
        // and it is what makes the response elicit the peer's own ACK.
        constants::FRAME_PATH_CHALLENGE | constants::FRAME_PATH_RESPONSE => true,
        constants::FRAME_CLOSE => false,
        constants::FRAME_DATAGRAM | constants::FRAME_DATAGRAM_LEN => true,
        _ => false,
    }
}

/// §8.7's three retransmission classes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Retransmission {
    /// STREAM: un-ACKed sub-ranges return to the pending set and are
    /// re-framed on fresh counters.
    Ranges,
    /// The frame's *identity* re-queues and carries the freshest value.
    Regenerate,
    /// Loss is absorbed by the next ACK, probe, the unreliability
    /// contract, or the linger reply rule.
    Never,
}

/// §8.3's retransmission column, as a pure function of the type code.
///
/// `None` for a code outside the table, and for `0x05` — which §8.3 marks
/// reserved with a `—` in every column, so answering for it would be an
/// invention.
pub(crate) fn retransmission(ty: u64) -> Option<Retransmission> {
    match ty {
        constants::FRAME_PADDING | constants::FRAME_PING | constants::FRAME_ACK => {
            Some(Retransmission::Never)
        }
        constants::FRAME_RESET_STREAM => Some(Retransmission::Regenerate),
        constants::FRAME_STREAM_BASE..=constants::FRAME_STREAM_MAX => Some(Retransmission::Ranges),
        constants::FRAME_MAX_DATA
        | constants::FRAME_MAX_STREAM_DATA
        | constants::FRAME_MAX_STREAMS_BIDI
        | constants::FRAME_MAX_STREAMS_UNI => Some(Retransmission::Regenerate),
        // **[ruling 208]** `never` — **plus a standing obligation** (§8.7,
        // ruling 212(d)). Neither frame is ever re-queued by loss
        // detection: the challenge is re-offered by §7.3's pump for as long
        // as the arming stands, and a lost response is asked for again by
        // the peer's still-standing challenge. "Never retransmitted" here
        // does not mean "sent once and lost forever", which §7.3's
        // no-deadlock argument could not survive.
        constants::FRAME_PATH_CHALLENGE | constants::FRAME_PATH_RESPONSE => {
            Some(Retransmission::Never)
        }
        // §8.7 lists CLOSE under `never`; §8.3's column calls the same
        // thing "linger rule (§15.2)". They agree: CLOSE is never
        // *loss*-retransmitted, and the linger's reply is a separate
        // mechanism that does not run through loss recovery.
        constants::FRAME_CLOSE => Some(Retransmission::Never),
        constants::FRAME_DATAGRAM | constants::FRAME_DATAGRAM_LEN => Some(Retransmission::Never),
        _ => None,
    }
}

/// §8.5's packing order, expressed as stages that can only run forwards.
///
/// *"Within a packet the sender packs in this order: the ACK first (if
/// owed), then control frames — **[AMENDED 2026/08/16 — ruling 208]**
/// `PATH_RESPONSE` and `PATH_CHALLENGE` **first among the control frames**,
/// then credit grants, RESET_STREAM, CLOSE — then STREAM and DATAGRAM fill,
/// then PING last if a probe still owes ack-eliciting content."*
///
/// **§8.5 and §7.3's priority order answer different questions.** §8.5
/// decides byte placement inside a packet whose size is already settled;
/// §7.3 decides which class of output gets a scarce budget at all. That is
/// why the path frames sit inside stage 2 here while ranking above the pure
/// ACK there: a packet carrying both carries both.
///
/// Slice 3 has three of those stages' contents (ACK, CLOSE, PING). The
/// missing middle is slice 4's STREAM fill and slice 6's DATAGRAM fill:
/// they insert a stage here, between [`control`](Packing::control) and
/// [`ping`](Packing::ping), rather than rewriting the order.
pub(crate) struct Packing {
    frames: Vec<Frame>,
    used: usize,
    budget: usize,
    stage: Stage,
    /// §8.5's *"at most one extends-to-end frame … per packet, in final
    /// position"*.
    ///
    /// **§12.3's seam:** the rule is a property of the **stage**, not of
    /// STREAM. Slice 6 adds DATAGRAM as a second contributor to the same
    /// stage; a check living in the stream fill loop would be duplicated
    /// there, and the duplicate would be the one that drifts.
    extends_to_end: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Stage {
    Ack,
    Control,
    Fill,
    Ping,
}

impl Packing {
    /// A packet plan with `MAX_PLAINTEXT` of room (§8.6).
    pub(crate) fn new() -> Self {
        Self::bounded(constants::MAX_PLAINTEXT)
    }

    /// A packet plan bounded by something **smaller** than §8.6's budget.
    ///
    /// **[ruling 203]** §7.3's remaining anti-amplification room is the one
    /// such bound today. The pump sizes what it *builds* to what the budget
    /// will admit instead of building at full size and discovering the
    /// refusal, because a refusal is a **hold**: the packet that would have
    /// escaped the budget in one round trip is the one the full-size build
    /// never emits.
    ///
    /// `budget` is a **plaintext** length — ruling 207(c)'s units, not the
    /// datagram's — and is clamped to `MAX_PLAINTEXT`, so this can only ever
    /// shrink a packet and never widen §8.6's bound.
    pub(crate) fn bounded(budget: usize) -> Self {
        Self {
            frames: Vec::new(),
            used: 0,
            budget: budget.min(constants::MAX_PLAINTEXT),
            stage: Stage::Ack,
            extends_to_end: false,
        }
    }

    /// Stage 1 — the ACK, if one is owed (§12.3).
    pub(crate) fn ack(&mut self, ack: Ack) -> bool {
        self.push(Stage::Ack, Frame::Ack(ack))
    }

    /// Stage 2 — control frames: credit grants, RESET_STREAM, CLOSE.
    pub(crate) fn control(&mut self, frame: Frame) -> bool {
        self.push(Stage::Control, frame)
    }

    /// Stage 2, **first among the control frames** — §7.3's challenge.
    ///
    /// **[ruling 208, §8.5 as amended]** *"Packing the path frames ahead of
    /// every other control frame is what keeps the frame that **ends** the
    /// scarcity inside the packet the scarcity allowed, rather than trimmed
    /// out of it by a credit grant."* It is emphatically **not**
    /// [`Stage::Ping`]: that stage is last, and under a room clamped near
    /// 39 bytes, last is nowhere.
    ///
    /// `false` when fewer than nine bytes remain, like every other planner
    /// verb — the frame is not truncated and the caller keeps owing it.
    pub(crate) fn path_challenge(&mut self, value: [u8; PATH_CHALLENGE_LEN]) -> bool {
        self.push(Stage::Control, Frame::PathChallenge(value))
    }

    /// Stage 2, beside [`path_challenge`](Self::path_challenge) — the echo.
    pub(crate) fn path_response(&mut self, value: [u8; PATH_CHALLENGE_LEN]) -> bool {
        self.push(Stage::Control, Frame::PathResponse(value))
    }

    /// Stage 3 — the STREAM and DATAGRAM fill (§8.5).
    pub(crate) fn fill(&mut self, frame: Frame) -> bool {
        self.push(Stage::Fill, frame)
    }

    /// Stage 3 — one DATAGRAM, in whichever of §8.4's two forms fits.
    ///
    /// `false` leaves `data` unpacked and this packet untouched; the caller
    /// keeps it queued for the next one.
    ///
    /// **The form is chosen, not fixed** (ruling 155, `PLAN-6.md` §4.2):
    ///
    /// 1. `0x31` when the length varint also fits — it leaves the packet
    ///    open, so the STREAM fill can still use the remaining room;
    /// 2. otherwise `0x30`, which extends to the end and therefore closes
    ///    the packet. This branch is what makes the ratified maximum
    ///    reachable at all: 1169 bytes need `1 + 2 + 1169 = 1172 >
    ///    MAX_PLAINTEXT` in the `0x31` form (§11.2), so a build without it
    ///    silently never sends a maximum-size datagram;
    /// 3. otherwise nothing fits and the datagram waits.
    ///
    /// Trying `0x31` **first** is what bounds the cost to the streams: the
    /// extends-to-end form is used only when the length-prefixed one cannot
    /// be, never as a default.
    pub(crate) fn datagram(&mut self, data: &[u8]) -> bool {
        let n = data.len();
        // The type byte comes off the top for both forms; what is left is
        // what the body has to fit in.
        let Some(body) = self.room().checked_sub(1) else {
            return false;
        };
        let len_present = if varint_len(n as u64) + n <= body {
            true
        } else if n <= body {
            false
        } else {
            return false;
        };
        self.push(
            Stage::Fill,
            Frame::Datagram(Datagram {
                data: data.to_vec(),
                len_present,
            }),
        )
    }

    /// Stage 4 — PING last, if a probe still owes ack-eliciting content.
    pub(crate) fn ping(&mut self) -> bool {
        self.push(Stage::Ping, Frame::Ping)
    }

    /// Bytes still available under §8.6's budget.
    pub(crate) fn room(&self) -> usize {
        self.budget.saturating_sub(self.used)
    }

    /// The largest STREAM payload that still fits, given the frame's fixed
    /// fields. `None` when not even an empty frame fits.
    ///
    /// **The two answers are opposites and a caller must not collapse
    /// them** — `None` is *"no frame of any size fits"*, `Some(0)` is *"a
    /// frame fits, with no payload"*, which is reachable only at
    /// `room() == fixed + 1` and is exactly the width of §9.5's empty
    /// FIN-bearing frame. **[ruling 257]** `Streams::fill` read them
    /// through `unwrap_or(0)` and guarded only the second, so a bare FIN
    /// against a full packet was built and handed to
    /// [`fill`](Packing::fill), which could only refuse it.
    ///
    /// Written here because the length varint's own width depends on the
    /// payload length it describes — the one place in the codec where a
    /// field's size is a function of the value it precedes.
    ///
    /// # Scope: this query does **not** consult `extends_to_end`
    ///
    /// [`push`](Packing::push) refuses *everything* once that flag is set,
    /// whatever [`room`](Packing::room) says, and this answer is derived
    /// from `room()` alone. The gap is unreachable today only by an
    /// arithmetic accident: the sole frame that sets the flag is a ¬LEN
    /// (`0x30`) DATAGRAM, chosen only when `varint_len(n) + n > body`, so
    /// it always leaves `body - n < varint_len(n) <= 2` bytes — below the
    /// `fixed >= 2` of any STREAM frame, which makes this return `None`
    /// anyway. **[ruling 257]** Add a third extends-to-end contributor, or
    /// start emitting the ¬LEN STREAM form
    /// [`Stream::new`](Stream::new) declines, and that accident stops
    /// holding: the flag must then move into this query rather than being
    /// checked one layer down.
    pub(crate) fn stream_payload_room(&self, id: StreamId, offset: u64) -> Option<usize> {
        let fixed = 1 + varint_len(id.as_u64()) + if offset != 0 { varint_len(offset) } else { 0 };
        let avail = self.room().checked_sub(fixed)?;
        // The smallest `len` varint that admits its own payload wins, and
        // trying them in increasing width yields the largest payload.
        for width in [1usize, 2, 4, 8] {
            if avail
                .checked_sub(width)
                .is_some_and(|p| varint_len(p as u64) <= width)
            {
                return Some(avail - width);
            }
        }
        None
    }

    /// The frames planned so far, in packing order.
    pub(crate) fn frames(&self) -> &[Frame] {
        &self.frames
    }

    /// The planned plaintext.
    pub(crate) fn into_plaintext(self) -> Vec<u8> {
        let mut out = Vec::with_capacity(self.used);
        for frame in &self.frames {
            frame.encode(&mut out);
        }
        debug_assert_eq!(out.len(), self.used, "encoded_len disagrees with encode");
        debug_assert!(
            out.len() <= constants::MAX_PLAINTEXT,
            "§8.6's per-seal bound"
        );
        out
    }

    fn push(&mut self, stage: Stage, frame: Frame) -> bool {
        debug_assert!(
            stage >= self.stage,
            "§8.5's packing order runs forwards only: {stage:?} after {:?}",
            self.stage
        );
        self.stage = stage;

        // §8.5: an extends-to-end frame is final, so nothing may follow it,
        // and there is at most one.
        if self.extends_to_end {
            return false;
        }

        let len = frame.encoded_len();
        if self.used + len > self.budget {
            return false;
        }
        self.extends_to_end = frame.extends_to_end();
        self.used += len;
        self.frames.push(frame);
        true
    }
}

// ═══════════════════════════════════════════════════════════════════════
// Cursor — the one place a length check is written
// ═══════════════════════════════════════════════════════════════════════

/// A parse cursor over the plaintext.
///
/// Every overrun check in §8.2's structural class lives here, so no frame
/// parser above rewrites one and gets it wrong once.
struct Cursor<'a> {
    buf: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    fn new(buf: &'a [u8]) -> Self {
        Self { buf, pos: 0 }
    }

    fn is_empty(&self) -> bool {
        self.pos >= self.buf.len()
    }

    fn rest(&self) -> &'a [u8] {
        &self.buf[self.pos..]
    }

    fn consumed(&self) -> usize {
        self.pos
    }

    fn advance(&mut self, n: usize) {
        self.pos += n;
    }

    fn varint(&mut self) -> Result<u64, Structural> {
        let (v, n) = varint::decode(self.rest()).ok_or(Structural::VarintOverrun)?;
        self.pos += n;
        Ok(v.into_inner())
    }

    fn bytes(&mut self, n: usize) -> Result<&'a [u8], Structural> {
        let rest = self.rest();
        if rest.len() < n {
            return Err(Structural::LengthOverrun);
        }
        self.pos += n;
        Ok(&rest[..n])
    }
}

/// The encoded length of a value that must fit a varint.
///
/// Values above 2⁶² − 1 are saturated rather than refused: every field
/// slither *produces* is either a counter, a length bounded by
/// `MAX_PLAINTEXT`, or an application-chosen CLOSE code, and §16.2's
/// `close(code, reason)` takes a bare `u64` with no documented cap. See
/// `.slices/03-skeleton/IMPLEMENTATION.md` — §8.1's "stated consequence"
/// list names ACK `largest`, stream offsets and final sizes, and omits the
/// CLOSE code.
fn to_varint(v: u64) -> VarInt {
    VarInt::new(v).unwrap_or(VarInt::MAX)
}

fn varint_len(v: u64) -> usize {
    to_varint(v).encoded_len()
}

fn put_varint(v: u64, out: &mut Vec<u8>) {
    varint::encode(to_varint(v), out);
}

#[cfg(test)]
mod tests {
    use super::*;

    fn round_trip(frame: &Frame) -> Vec<Frame> {
        let mut bytes = Vec::new();
        frame.encode(&mut bytes);
        assert_eq!(bytes.len(), frame.encoded_len(), "encoded_len is wrong");
        parse(&bytes).expect("a frame this codec produced must parse")
    }

    #[test]
    fn padding_and_ping_are_one_byte_each() {
        assert_eq!(round_trip(&Frame::Padding), vec![Frame::Padding]);
        assert_eq!(round_trip(&Frame::Ping), vec![Frame::Ping]);

        let mut bytes = Vec::new();
        Frame::Padding.encode(&mut bytes);
        assert_eq!(bytes, vec![0x00]);
        bytes.clear();
        Frame::Ping.encode(&mut bytes);
        assert_eq!(bytes, vec![0x01]);
    }

    /// **[ruling 208]** §8.4's two fixed-width frames: nine bytes each, the
    /// eight opaque bytes carried verbatim and in order.
    #[test]
    fn the_path_frames_round_trip_as_nine_fixed_bytes() {
        let value = [1u8, 2, 3, 4, 5, 6, 7, 8];
        for frame in [Frame::PathChallenge(value), Frame::PathResponse(value)] {
            assert_eq!(frame.encoded_len(), 9, "1 type byte + 8 opaque bytes");
            assert_eq!(round_trip(&frame), vec![frame.clone()]);

            let mut bytes = Vec::new();
            frame.encode(&mut bytes);
            assert_eq!(bytes[0], frame.type_code() as u8);
            assert_eq!(&bytes[1..], &value, "the body is the eight bytes, raw");
        }
    }

    /// §8.4: "any number may appear anywhere" — before, between and after.
    #[test]
    fn padding_may_appear_anywhere() {
        let plaintext = vec![0x00, 0x00, 0x01, 0x00, 0x01, 0x00];
        assert_eq!(
            parse(&plaintext).expect("PADDING is legal anywhere"),
            vec![
                Frame::Padding,
                Frame::Padding,
                Frame::Ping,
                Frame::Padding,
                Frame::Ping,
                Frame::Padding
            ]
        );
    }

    #[test]
    fn close_round_trips_with_code_and_reason() {
        let frame = Frame::Close(Close::new(0x42, b"because"));
        assert_eq!(
            round_trip(&frame),
            vec![Frame::Close(Close {
                code: 0x42,
                reason: b"because".to_vec()
            })]
        );
    }

    /// An empty reason is the graceful close's shape, and it must encode
    /// as `reason_len = 0` with no bytes rather than being skipped.
    #[test]
    fn close_with_an_empty_reason_round_trips() {
        let mut bytes = Vec::new();
        Frame::Close(Close::new(constants::NO_ERROR, b"")).encode(&mut bytes);
        assert_eq!(bytes, vec![0x1c, 0x00, 0x00]);
        assert_eq!(
            parse(&bytes).unwrap(),
            vec![Frame::Close(Close {
                code: 0,
                reason: Vec::new()
            })]
        );
    }

    /// §8.4: `close()` truncates at the handle — and the core must not be
    /// able to produce the over-length case it kills on receipt.
    #[test]
    fn close_new_truncates_at_close_reason_max() {
        let long = vec![b'x'; constants::CLOSE_REASON_MAX + 64];
        let close = Close::new(1, &long);
        assert_eq!(close.reason.len(), constants::CLOSE_REASON_MAX);
    }

    /// Both sides of the boundary: exactly `CLOSE_REASON_MAX` parses,
    /// one more is a structural failure. Testing only the failing side
    /// would pass an implementation whose window is 16 bytes.
    #[test]
    fn close_reason_len_boundary_is_two_sided() {
        for (len, ok) in [
            (constants::CLOSE_REASON_MAX - 1, true),
            (constants::CLOSE_REASON_MAX, true),
            (constants::CLOSE_REASON_MAX + 1, false),
        ] {
            let mut bytes = vec![0x1c];
            put_varint(7, &mut bytes);
            put_varint(len as u64, &mut bytes);
            bytes.extend(std::iter::repeat_n(b'z', len));

            let parsed = parse(&bytes);
            assert_eq!(
                parsed.is_ok(),
                ok,
                "reason_len {len} should {} parse",
                if ok { "" } else { "not" }
            );
            if !ok {
                assert_eq!(
                    parsed.unwrap_err(),
                    Structural::CloseReasonTooLong(len as u64)
                );
            }
        }
    }

    #[test]
    fn close_reason_running_past_the_plaintext_is_structural() {
        let mut bytes = vec![0x1c];
        put_varint(1, &mut bytes);
        put_varint(8, &mut bytes);
        bytes.extend_from_slice(b"only4");
        assert_eq!(parse(&bytes).unwrap_err(), Structural::LengthOverrun);
    }

    #[test]
    fn ack_round_trips_with_extra_ranges() {
        let ack = Ack {
            largest: 100,
            ack_delay: 1234,
            first_range: 3,
            ranges: vec![(0, 1), (4, 2)],
        };
        assert_eq!(round_trip(&Frame::Ack(ack.clone())), vec![Frame::Ack(ack)]);
    }

    /// §12.2's newest-first descending order, read back off the wire.
    #[test]
    fn ack_ranges_are_descending_and_newest_first() {
        let ack = Ack {
            largest: 100,
            ack_delay: 0,
            first_range: 3,
            ranges: vec![(0, 1), (4, 2)],
        };
        // 97..=100, then gap 0 → largest 95, range 1 → 94..=95, then
        // gap 4 → largest 88, range 2 → 86..=88.
        assert_eq!(ack.ranges_desc(), vec![97..=100, 94..=95, 86..=88]);
    }

    /// Both sides of `MAX_ACK_RANGES`.
    #[test]
    fn ack_range_count_boundary_is_two_sided() {
        for (count, ok) in [
            (constants::MAX_ACK_RANGES - 1, true),
            (constants::MAX_ACK_RANGES, true),
            (constants::MAX_ACK_RANGES + 1, false),
        ] {
            let ack = Ack {
                largest: 1_000_000,
                ack_delay: 0,
                first_range: 0,
                ranges: vec![(0, 0); count],
            };
            let mut bytes = Vec::new();
            Frame::Ack(ack).encode(&mut bytes);

            let parsed = parse(&bytes);
            assert_eq!(parsed.is_ok(), ok, "range_count {count}");
            if !ok {
                assert_eq!(parsed.unwrap_err(), Structural::AckRangeCount(count as u64));
            }
        }
    }

    #[test]
    fn an_ack_range_below_counter_zero_is_structural() {
        // first_range alone descends past zero.
        let mut bytes = Vec::new();
        Frame::Ack(Ack {
            largest: 2,
            ack_delay: 0,
            first_range: 5,
            ranges: Vec::new(),
        })
        .encode(&mut bytes);
        assert_eq!(parse(&bytes).unwrap_err(), Structural::AckRangeUnderflow);

        // And a later pair descends past zero.
        let mut bytes = Vec::new();
        Frame::Ack(Ack {
            largest: 10,
            ack_delay: 0,
            first_range: 4,
            ranges: vec![(9, 0)],
        })
        .encode(&mut bytes);
        assert_eq!(parse(&bytes).unwrap_err(), Structural::AckRangeUnderflow);
    }

    #[test]
    fn a_truncated_ack_is_structural() {
        let bytes = vec![0x02, 0x05]; // type + largest, then nothing
        assert_eq!(parse(&bytes).unwrap_err(), Structural::VarintOverrun);
    }

    /// §8.3's `0x05` is reserved, "not implemented: like any unknown type,
    /// receiving it is a structural failure".
    #[test]
    fn the_reserved_type_is_an_unknown_type() {
        assert_eq!(
            parse(&[constants::FRAME_STOP_SENDING_RESERVED as u8]).unwrap_err(),
            Structural::UnknownType(0x05)
        );
    }

    /// `0x3f` is one byte and unassigned; `0x7f` is the first byte of a
    /// **two**-byte varint (prefix `01`), so on its own it is a truncated
    /// varint rather than an unknown type — both are §8.2's structural
    /// class, and the distinction is the trace's, not the wire's.
    #[test]
    fn an_unknown_type_is_structural() {
        assert_eq!(parse(&[0x3f]).unwrap_err(), Structural::UnknownType(0x3f));
        assert_eq!(parse(&[0x7f]).unwrap_err(), Structural::VarintOverrun);
        // A well-formed two-byte encoding of an unassigned code is an
        // unknown type, not a truncation.
        assert_eq!(
            parse(&[0x40, 0x7f]).unwrap_err(),
            Structural::UnknownType(0x7f)
        );
    }

    /// A **valid** frame followed by an unknown type is still a structural
    /// failure, and the valid frame is not returned — this is the
    /// assertion that separates parse-then-apply from a streaming
    /// parse-and-apply loop (§8.2).
    #[test]
    fn a_valid_frame_before_an_unknown_type_is_not_applied() {
        let mut bytes = Vec::new();
        Frame::Close(Close::new(9, b"bye")).encode(&mut bytes);
        bytes.push(0x3f);
        assert_eq!(parse(&bytes).unwrap_err(), Structural::UnknownType(0x3f));
    }

    /// A non-minimal varint type code is legal (§8.1: a receiver accepts
    /// any length), so a two-byte-encoded PING is a PING.
    #[test]
    fn a_non_minimally_encoded_type_code_still_parses() {
        assert_eq!(parse(&[0x40, 0x01]).unwrap(), vec![Frame::Ping]);
    }

    /// §8.3's ack-eliciting column, **every row** — including the types
    /// this slice cannot construct. A two-arm classifier is correct
    /// by accident for the whole of slice 3; this is what separates them.
    ///
    /// **[ruling 208]** §8.3 gained two rows and so did this table. Both
    /// are `true`, and both are load-bearing: the challenge's arms §7.3's
    /// death clock, the response's elicits the peer's ACK.
    #[test]
    fn ack_eliciting_matches_the_whole_of_table_8_3() {
        let expected: &[(u64, bool)] = &[
            (constants::FRAME_PADDING, false),
            (constants::FRAME_PING, true),
            (constants::FRAME_ACK, false),
            (constants::FRAME_RESET_STREAM, true),
            (0x08, true),
            (0x09, true),
            (0x0a, true),
            (0x0b, true),
            (0x0c, true),
            (0x0d, true),
            (0x0e, true),
            (0x0f, true),
            (constants::FRAME_MAX_DATA, true),
            (constants::FRAME_MAX_STREAM_DATA, true),
            (constants::FRAME_MAX_STREAMS_BIDI, true),
            (constants::FRAME_MAX_STREAMS_UNI, true),
            (constants::FRAME_PATH_CHALLENGE, true),
            (constants::FRAME_PATH_RESPONSE, true),
            (constants::FRAME_CLOSE, false),
            (constants::FRAME_DATAGRAM, true),
            (constants::FRAME_DATAGRAM_LEN, true),
        ];
        assert_eq!(
            expected.len(),
            21,
            "§8.3's fourteen rows, less the reserved `0x05`, with the STREAM \
             and DATAGRAM rows expanded to their eight and two codes"
        );
        for (ty, want) in expected {
            assert_eq!(is_ack_eliciting(*ty), *want, "type {ty:#x}");
        }
    }

    /// §8.7's three classes, every row of §8.3.
    #[test]
    fn retransmission_classes_match_the_whole_of_table_8_3() {
        use Retransmission::*;
        let expected: &[(u64, Option<Retransmission>)] = &[
            (constants::FRAME_PADDING, Some(Never)),
            (constants::FRAME_PING, Some(Never)),
            (constants::FRAME_ACK, Some(Never)),
            (constants::FRAME_RESET_STREAM, Some(Regenerate)),
            (constants::FRAME_STOP_SENDING_RESERVED, None),
            (0x08, Some(Ranges)),
            (0x0f, Some(Ranges)),
            (constants::FRAME_MAX_DATA, Some(Regenerate)),
            (constants::FRAME_MAX_STREAM_DATA, Some(Regenerate)),
            (constants::FRAME_MAX_STREAMS_BIDI, Some(Regenerate)),
            (constants::FRAME_MAX_STREAMS_UNI, Some(Regenerate)),
            (constants::FRAME_PATH_CHALLENGE, Some(Never)),
            (constants::FRAME_PATH_RESPONSE, Some(Never)),
            (constants::FRAME_CLOSE, Some(Never)),
            (constants::FRAME_DATAGRAM, Some(Never)),
            (constants::FRAME_DATAGRAM_LEN, Some(Never)),
            (0x77, None),
        ];
        for (ty, want) in expected {
            assert_eq!(retransmission(*ty), *want, "type {ty:#x}");
        }
    }

    /// A packet is ack-eliciting iff at least one of its frames is — so a
    /// CLOSE-and-PADDING packet is not, and adding a PING makes it so.
    #[test]
    fn packet_ack_eliciting_is_an_any_over_frames() {
        let quiet = vec![Frame::Close(Close::new(0, b"")), Frame::Padding];
        assert!(!packet_is_ack_eliciting(&quiet));

        let mut loud = quiet.clone();
        loud.push(Frame::Ping);
        assert!(packet_is_ack_eliciting(&loud));
    }

    /// §8.5's order, as the packer produces it: ACK, then CLOSE, then PING.
    #[test]
    fn packing_emits_ack_then_control_then_ping() {
        let mut packing = Packing::new();
        assert!(packing.ack(Ack {
            largest: 5,
            ack_delay: 0,
            first_range: 0,
            ranges: Vec::new()
        }));
        assert!(packing.control(Frame::Close(Close::new(0, b""))));
        assert!(packing.ping());

        let types: Vec<u64> = packing.frames().iter().map(Frame::type_code).collect();
        assert_eq!(
            types,
            vec![
                constants::FRAME_ACK,
                constants::FRAME_CLOSE,
                constants::FRAME_PING
            ]
        );

        let plaintext = packing.into_plaintext();
        let parsed = parse(&plaintext).unwrap();
        assert_eq!(
            parsed.iter().map(Frame::type_code).collect::<Vec<_>>(),
            types
        );
    }

    /// §8.6's budget: the packer refuses a frame that would not fit rather
    /// than truncating one.
    #[test]
    fn packing_refuses_a_frame_that_would_overrun_max_plaintext() {
        let mut packing = Packing::new();
        // Fill the budget with CLOSEs, then check the next one is refused
        // and the plaintext still fits.
        let mut accepted = 0;
        while packing.control(Frame::Close(Close::new(
            1,
            &[b'x'; constants::CLOSE_REASON_MAX],
        ))) {
            accepted += 1;
            assert!(accepted < 64, "the budget must bind");
        }
        assert!(accepted > 0);
        assert!(packing.into_plaintext().len() <= constants::MAX_PLAINTEXT);
    }
}