yodel 0.2.0

Bell 202 AFSK (1200/2200 Hz) software modem: no-std, allocation-free, streaming modulator
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
//! Integration tests for the IL2P frame codec: header round trips,
//! scrambler self-inversion, full encode→decode round trips for
//! representative AX.25 frames, and FEC corruption proofs.
//!
//! Known-answer provenance, which matters here: the `spec_v06_*` tests
//! use the **published verification vectors** from IL2P Specification
//! Draft v0.6, "Example Encoded Packets". Everything else is a
//! self-consistent vector generated by this crate's own documented
//! recurrences.
//!
//! That distinction is not pedantry. This file previously contained a
//! self-generated "known answer" for the scrambler, which froze this
//! crate's own (wrong) register preset and passed happily while the
//! implementation could not exchange a single frame with any other
//! IL2P station. A round-trip test proves only that the encoder and
//! decoder are mutual inverses — a property any wrong-but-consistent
//! constant preserves. Conformance needs an external vector.
#![cfg(feature = "il2p")]

use yodel::ax25::{Address, UiFrame};
use yodel::il2p::{
    self, ENCODED_MAX, HEADER_LEN, HEADER_PARITY_LEN, Il2pError, Il2pHeader, Il2pParity,
    Il2pScrambler, MAX_BASELINE_BLOCK_DATA, PAYLOAD_MAX, SYNC_BYTES, SYNC_LEN, encode_raw,
    encode_ui_frame,
};

fn addr(call: &[u8], ssid: u8) -> Address {
    Address::new(call, ssid).unwrap()
}

/// Encode a UI frame, return (tx bytes, length).
fn encode_frame(frame: &UiFrame<'_>, parity: Il2pParity) -> ([u8; ENCODED_MAX], usize) {
    let mut tx = [0u8; ENCODED_MAX];
    let len = encode_ui_frame(frame, parity, &mut tx).unwrap();
    (tx, len)
}

/// Decode bytes after sync and reconstruct the UI frame, asserting it
/// matches `expect`.
fn assert_roundtrip(tx: &[u8], parity: Il2pParity, expect: &UiFrame<'_>) {
    let mut payload = [0u8; PAYLOAD_MAX];
    let decoded = il2p::decode(&tx[SYNC_LEN..], parity, &mut payload).unwrap();
    let back = il2p::to_ui_frame(&decoded.header, &payload[..decoded.payload_len]).unwrap();
    assert_eq!(&back, expect);
}

#[test]
fn ui_frame_roundtrip_no_path() {
    let frame = UiFrame::new(addr(b"APRS", 0), addr(b"N0CALL", 7), b">status report");
    let (tx, len) = encode_frame(&frame, Il2pParity::Sixteen);
    assert_eq!(&tx[..SYNC_LEN], &SYNC_BYTES);
    assert_roundtrip(&tx[..len], Il2pParity::Sixteen, &frame);
}

#[test]
fn ui_frame_roundtrip_with_digipeater_path() {
    // A digipeater path forces the type 0 transparent translation.
    let path = [addr(b"WIDE1", 1), addr(b"WIDE2", 2)];
    let frame = UiFrame::with_path(
        addr(b"APRS", 0),
        addr(b"N0CALL", 9),
        &path,
        b"!4903.50N/07201.75W-",
    )
    .unwrap();
    let (tx, len) = encode_frame(&frame, Il2pParity::Four);
    let mut payload = [0u8; PAYLOAD_MAX];
    let decoded = il2p::decode(&tx[SYNC_LEN..len], Il2pParity::Four, &mut payload).unwrap();
    assert!(matches!(decoded.header, Il2pHeader::Transparent { .. }));
    let back = il2p::to_ui_frame(&decoded.header, &payload[..decoded.payload_len]).unwrap();
    assert_eq!(back, frame);
    assert_eq!(back.path(), &path);
}

#[test]
fn ui_frame_roundtrip_empty_payload() {
    let frame = UiFrame::new(addr(b"CQ", 0), addr(b"K1ABC", 0), b"");
    let (tx, len) = encode_frame(&frame, Il2pParity::Two);
    assert_eq!(
        len,
        SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN // no payload blocks
    );
    assert_roundtrip(&tx[..len], Il2pParity::Two, &frame);
}

#[test]
fn max_size_raw_payload_roundtrip() {
    let payload: [u8; PAYLOAD_MAX] = core::array::from_fn(|i| (i % 251) as u8);
    for parity in Il2pParity::ALL {
        let mut tx = [0u8; ENCODED_MAX];
        let len = encode_raw(&payload, parity, &mut tx).unwrap();
        assert_eq!(len, il2p::encoded_len(PAYLOAD_MAX, parity));
        let mut out = [0u8; PAYLOAD_MAX];
        let decoded = il2p::decode(&tx[SYNC_LEN..len], parity, &mut out).unwrap();
        assert_eq!(decoded.payload_len, PAYLOAD_MAX);
        assert_eq!(out, payload);
        assert_eq!(decoded.corrected(), 0);
    }
}

#[test]
fn header_pack_unpack_roundtrips() {
    let headers = [
        Il2pHeader::Transparent { payload_len: 0 },
        Il2pHeader::Transparent { payload_len: 1023 },
        Il2pHeader::Translated {
            command: true,
            dest: addr(b"APRS", 0),
            src: addr(b"N0CALL", 15),
            pid: 0xF0,
            payload_len: 512,
        },
        // A response, so the round trip covers both settings of the
        // command bit rather than only the one we transmit.
        Il2pHeader::Translated {
            command: false,
            dest: addr(b"Q", 15),
            src: addr(b"W1AW", 1),
            pid: 0xCF, // NET/ROM, exercising the PID table
            payload_len: 1,
        },
    ];
    for header in headers {
        let packed = header.pack(true).unwrap();
        assert_eq!(Il2pHeader::unpack(&packed).unwrap(), header);
    }
}

#[test]
fn scrambler_is_self_inverse() {
    let mut data = [0u8; 8];
    Il2pScrambler::new().scramble(&mut data);
    assert_ne!(data, [0u8; 8]);
    Il2pScrambler::new().descramble(&mut data);
    assert_eq!(data, [0u8; 8]);
}

// --- Published verification vectors -------------------------------
//
// From "Example Encoded Packets", IL2P Specification Draft v0.6
// (16 March 2024). These are the spec's own samples, contributed for
// exactly this purpose: "intended for use as verification samples to
// help individuals implementing their own IL2P encoders and decoders".
//
// The AX.25 samples have no flags and are not bit-stuffed. The IL2P
// samples omit the Sync Word and INCLUDE the optional Trailing CRC,
// which this crate does not implement -- so each expectation below
// covers the 15-byte header codeblock (13 header + 2 RS parity) and,
// where present, the payload blocks, stopping before the final four
// Hamming-coded CRC bytes.
//
// These vectors exist because the previous "known answer" test was
// self-generated: it froze this crate's own scrambler preset, so it
// passed while the implementation could not exchange a single frame
// with any other station. A round-trip test proves the encoder and
// decoder are mutual inverses, which a wrong-but-consistent constant
// preserves. Only an external vector can prove conformance.

/// Spec v0.6 U-frame: an AX.25 UI frame, i.e. the APRS case.
/// Destination `CQ-0`, source `KK4HEJ-15`, P/F 0, C 0, PID 0xF0.
const SPEC_U_AX25: [u8; 16] = [
    0x86, 0xA2, 0x40, 0x40, 0x40, 0x40, 0x60, 0x96, 0x96, 0x68, 0x90, 0x8A, 0x94, 0xFF, 0x03, 0xF0,
];
/// The 15-byte header codeblock of the U-frame sample (the four bytes
/// that follow it on the wire are the optional Trailing CRC).
const SPEC_U_IL2P_HEADER: [u8; 15] = [
    0x6A, 0xEA, 0x9C, 0xC2, 0x01, 0x11, 0xFC, 0x14, 0x1F, 0xDA, 0x6E, 0xF2, 0x53, 0x91, 0xBD,
];

/// Spec v0.6 S-frame header codeblock. This crate does not translate
/// S-frames, so only the scrambler and RS layers are checked with it.
const SPEC_S_IL2P_HEADER: [u8; 15] = [
    0x26, 0x57, 0x4D, 0x57, 0xF1, 0xD2, 0xA8, 0xF0, 0x6A, 0xF2, 0x7B, 0xAD, 0x23, 0xBD, 0xC0,
];

/// Our translated-UI encoder must reproduce the spec's U-frame header
/// codeblock byte for byte. This single assertion pins the scrambler
/// preset, the PID code, the control subfield, the header bit map and
/// the header RS parity simultaneously — any one of them wrong and the
/// bytes diverge.
#[test]
fn spec_v06_u_frame_header_matches() {
    // The spec sample's AX.25 form: destination CQ-0, source
    // KK4HEJ-15, control 0x03 (UI, P/F 0), PID 0xF0, no info.
    let frame = UiFrame::new(addr(b"CQ", 0), addr(b"KK4HEJ", 15), b"");
    let mut ax25 = [0u8; 64];
    let ax25_len = frame.build(&mut ax25).unwrap();
    // Bit 7 of each SSID octet is the AX.25 command/response bit: the
    // spec's sample is a response, `UiFrame::new` builds a command.
    // IL2P carries C in its own control subfield rather than in the
    // translated addresses, so it cannot affect the bytes under test;
    // mask it out and compare everything else.
    let mut ours = ax25[..ax25_len].to_vec();
    let mut theirs = SPEC_U_AX25.to_vec();
    for buf in [&mut ours, &mut theirs] {
        buf[6] &= 0x7F;
        buf[13] &= 0x7F;
    }
    assert_eq!(
        ours, theirs,
        "our AX.25 serialization must match the spec sample (C bits aside)"
    );

    // The header is built EXPLICITLY rather than through
    // `encode_ui_frame`, because the spec's sample is not a frame that
    // path can produce, in two independent ways:
    //
    //  * It is a RESPONSE. Its AX.25 destination SSID octet is 0x60 (C
    //    clear) and its source 0xFF (C set). `UiFrame::build` always
    //    writes the command encoding, so every frame it produces is a
    //    command. Both are legal; they are simply different frames.
    //  * Its FEC-level bit is CLEAR. v0.6 declares that bit RESERVED
    //    while also mandating 16 parity symbols everywhere, and its own
    //    examples were generated with the bit clear -- the two
    //    statements cannot both be honoured on the wire, so what we
    //    transmit (set, because deployed receivers size the payload
    //    from it) is pinned separately by
    //    `max_fec_bit_is_set_for_sixteen_parity`.
    //
    // Both differences are single plaintext bits that the multiplicative
    // scrambler smears across almost the whole codeblock, so neither
    // can be masked out after the fact -- the frame has to be built as
    // the sample was. Constructing it directly is also more exact: the
    // vector is a specific frame, C bit included.
    let header = Il2pHeader::Translated {
        command: false,
        dest: addr(b"CQ", 0),
        src: addr(b"KK4HEJ", 15),
        pid: 0xF0,
        payload_len: 0,
    };
    let mut tx = [0u8; ENCODED_MAX];
    let len = il2p::encode(&header, b"", Il2pParity::Two, &mut tx).unwrap();
    assert_eq!(len, SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN);
    assert_eq!(
        &tx[SYNC_LEN..len],
        &SPEC_U_IL2P_HEADER[..],
        "IL2P header codeblock must match spec v0.6 example"
    );
}

/// Header byte 0 bit 7 must announce the parity the payload carries.
///
/// The bit is the v0.4 "FEC level"; v0.6 deleted baseline FEC and
/// redefined it as RESERVED. Deployed receivers did not follow: they
/// still read it to decide **how many bytes to take off the air** for
/// the payload. Clearing it while sending 16-symbol parity tells such a
/// receiver to collect far too few bytes, its RS decode fails, and the
/// frame is dropped -- which is why this crate's IL2P transmissions
/// were undecodable by every other implementation despite reproducing
/// the specification's own header vectors byte for byte.
///
/// Pinned here at the wire level so the header bit and the payload
/// parity cannot drift apart again.
#[test]
fn max_fec_bit_is_set_for_sixteen_parity() {
    let frame = UiFrame::new(addr(b"CQ", 0), addr(b"KK4HEJ", 15), b"");
    for (parity, expect_set) in [
        (Il2pParity::Two, false),
        (Il2pParity::Four, false),
        (Il2pParity::Six, false),
        (Il2pParity::Eight, false),
        (Il2pParity::Sixteen, true),
    ] {
        assert_eq!(parity.is_max_fec(), expect_set, "{parity:?}");
        let (tx, len) = encode_frame(&frame, parity);
        // Recover the header by undoing RS-free scrambling: the first
        // 13 bytes after the sync word are the scrambled header.
        let mut header = [0u8; HEADER_LEN];
        header.copy_from_slice(&tx[SYNC_LEN..SYNC_LEN + HEADER_LEN]);
        Il2pScrambler::new().descramble(&mut header);
        assert_eq!(
            header[0] & 0x80 != 0,
            expect_set,
            "{parity:?}: header FEC-level bit disagrees with the payload parity"
        );
        assert_eq!(len, SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN);
    }
}

/// The same vector in the receive direction: the spec's own on-air
/// bytes must decode back to the frame it says they encode.
#[test]
fn spec_v06_u_frame_decodes() {
    let mut wire = [0u8; ENCODED_MAX];
    wire[..SYNC_LEN].copy_from_slice(&SYNC_BYTES);
    wire[SYNC_LEN..SYNC_LEN + 15].copy_from_slice(&SPEC_U_IL2P_HEADER);
    let decoded = il2p::decode(
        &wire[SYNC_LEN..SYNC_LEN + 15],
        Il2pParity::Sixteen,
        &mut [0u8; PAYLOAD_MAX],
    )
    .expect("spec vector must decode");
    match decoded.header {
        Il2pHeader::Translated {
            dest,
            src,
            pid,
            payload_len,
            ..
        } => {
            assert_eq!(dest.callsign.as_bytes(), b"CQ");
            assert_eq!(dest.ssid.value(), 0);
            assert_eq!(src.callsign.as_bytes(), b"KK4HEJ");
            assert_eq!(src.ssid.value(), 15);
            assert_eq!(pid, 0xF0);
            assert_eq!(payload_len, 0);
        }
        other => panic!("expected a translated UI header, got {other:?}"),
    }
}

/// The S-frame vector pins the scrambler independently of this crate's
/// header translation (S-frames are not translated here). Descrambling
/// the spec's wire bytes must reveal the callsigns the spec states.
#[test]
fn spec_v06_s_frame_scrambler_matches() {
    let mut header = SPEC_S_IL2P_HEADER[..HEADER_LEN].to_vec();
    Il2pScrambler::new().descramble(&mut header);
    // Callsigns live in the low 6 bits, SIXBIT (ASCII - 0x20).
    let sixbit = |r: core::ops::Range<usize>| -> String {
        header[r]
            .iter()
            .map(|b| ((b & 0x3F) + 0x20) as char)
            .collect()
    };
    assert_eq!(sixbit(0..6), "KA2DEW", "destination callsign");
    assert_eq!(sixbit(6..12), "KK4HEJ", "source callsign");
    assert_eq!(header[12] >> 4, 2, "destination SSID");
    assert_eq!(header[12] & 0x0F, 7, "source SSID");
    // Header type 1 (translated). Byte 0 bit 7 is v0.6's RESERVED and
    // v0.4's FEC level -- the spec's own examples transmit it clear,
    // i.e. baseline FEC, which is why this vector is a baseline frame.
    assert_eq!(header[1] >> 7, 1, "header type must be translated");
    assert_eq!(header[0] >> 7, 0, "FEC-level bit is clear in the vector");
}

/// Corrupt `n` symbols of each payload block and the header, prove the
/// FEC recovers exactly; one symbol beyond `t` fails cleanly.
#[test]
fn fec_corrects_up_to_t_per_block_and_fails_beyond() {
    // Payload lengths chosen to land in each baseline parity band, plus a
    // two-block max-FEC case. At the baseline level the symbol count is
    // NOT carried on the wire -- the receiver derives it from the block
    // size -- so the effective parity is a function of the payload
    // length, not of what the caller asked for. Deriving the expectation
    // from the library rather than hard-coding it is the point: it pins
    // that rule end to end.
    let source: [u8; 300] = core::array::from_fn(|i| (i as u8).wrapping_mul(29) ^ 0x77);
    let cases: &[(usize, Il2pParity, Il2pParity)] = &[
        (50, Il2pParity::Two, Il2pParity::Two),
        (100, Il2pParity::Two, Il2pParity::Four),
        (150, Il2pParity::Two, Il2pParity::Six),
        (200, Il2pParity::Two, Il2pParity::Eight),
        (300, Il2pParity::Sixteen, Il2pParity::Sixteen),
    ];

    for &(len, requested, expect_effective) in cases {
        let payload = &source[..len];
        let max_fec = requested.is_max_fec();
        let effective = il2p::payload_parity(len, max_fec);
        assert_eq!(
            effective, expect_effective,
            "{len} bytes, max_fec {max_fec}"
        );

        let t = effective.correctable();
        let nblocks = il2p::block_count_for(len, max_fec);
        let small = len / nblocks;
        let big = len % nblocks;

        let mut tx = [0u8; ENCODED_MAX];
        let wire = encode_raw(payload, requested, &mut tx).unwrap();
        let hdr_end = SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN;

        // Byte offset of block `b`'s data within the frame.
        let block_at = |b: usize| {
            let mut at = hdr_end;
            for i in 0..b {
                at += small + usize::from(i < big) + effective.len();
            }
            at
        };

        // Corrupt t symbols in every block, plus one header symbol.
        let mut corrupted = tx;
        corrupted[SYNC_LEN + 2] ^= 0xFF;
        for b in 0..nblocks {
            for e in 0..t {
                corrupted[block_at(b) + 3 + e] ^= 0xA5;
            }
        }
        let mut out = [0u8; PAYLOAD_MAX];
        let decoded = il2p::decode(&corrupted[SYNC_LEN..wire], requested, &mut out).unwrap();
        assert_eq!(&out[..len], payload, "{len} bytes at {effective:?}");
        assert_eq!(decoded.header_corrected, 1);
        assert_eq!(decoded.payload_corrected, nblocks * t);

        // t + 1 errors in block 0: clean typed failure.
        let mut broken = tx;
        for e in 0..=t {
            broken[block_at(0) + 3 + e] ^= 0xA5;
        }
        let err = il2p::decode(&broken[SYNC_LEN..wire], requested, &mut out).unwrap_err();
        assert_eq!(
            err,
            Il2pError::BlockUncorrectable { block: 0 },
            "{len} bytes"
        );
    }
}

#[test]
fn header_beyond_t_fails_cleanly() {
    let frame = UiFrame::new(addr(b"APRS", 0), addr(b"N0CALL", 0), b"x");
    let (mut tx, len) = encode_frame(&frame, Il2pParity::Sixteen);
    // 2 header parity symbols correct 1 error; 2 errors must fail.
    tx[SYNC_LEN] ^= 0xFF;
    tx[SYNC_LEN + 5] ^= 0xFF;
    let mut out = [0u8; PAYLOAD_MAX];
    let err = il2p::decode(&tx[SYNC_LEN..len], Il2pParity::Sixteen, &mut out).unwrap_err();
    assert_eq!(err, Il2pError::HeaderUncorrectable);
}

#[test]
fn truncated_frame_reports_length() {
    let frame = UiFrame::new(addr(b"APRS", 0), addr(b"N0CALL", 0), b"hello");
    let (tx, len) = encode_frame(&frame, Il2pParity::Sixteen);
    let mut out = [0u8; PAYLOAD_MAX];
    let err = il2p::decode(&tx[SYNC_LEN..len - 1], Il2pParity::Sixteen, &mut out).unwrap_err();
    assert!(matches!(err, Il2pError::FrameTooShort { .. }));
}

#[test]
fn oversize_payload_rejected() {
    let big = [0u8; PAYLOAD_MAX + 1];
    let mut tx = [0u8; ENCODED_MAX];
    assert_eq!(
        encode_raw(&big, Il2pParity::Sixteen, &mut tx),
        Err(Il2pError::PayloadTooLong {
            got: PAYLOAD_MAX + 1,
            max: PAYLOAD_MAX,
        })
    );
}

/// Deterministic filler: distinct enough that a mis-split block or a
/// missing scrambler pass shows up as a byte mismatch, not as a run of
/// coincidentally equal zeros.
fn sweep_source() -> [u8; PAYLOAD_MAX] {
    core::array::from_fn(|i| (i as u8).wrapping_mul(89) ^ ((i >> 8) as u8) ^ 0x5A)
}

/// One encode -> decode case at an exact-size output buffer, asserting
/// byte-exact payload recovery and that `encode`'s return value is the
/// number of bytes the frame needs -- no more, no less.
///
/// The output buffer is sized to exactly [`il2p::encoded_len`], which
/// is the size the documentation tells callers to use. An encoder
/// writing past that length is silently truncated by `encode`'s own
/// bounds guard, so "fits in `ENCODED_MAX`" would hide the very defect
/// this checks for.
fn assert_length_case(len: usize, requested: Il2pParity, source: &[u8; PAYLOAD_MAX]) {
    let payload = &source[..len];
    let max_fec = requested.is_max_fec();
    let needed = il2p::encoded_len(len, requested);
    assert_eq!(
        needed,
        SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN + il2p::payload_wire_len(len, max_fec),
        "{len} bytes, max_fec {max_fec}: encoded_len must agree with payload_wire_len"
    );

    // A buffer one byte short must be refused, naming the same length --
    // so `needed` is a true lower bound, not just an upper one.
    let mut tx = [0u8; ENCODED_MAX];
    assert_eq!(
        encode_raw(payload, requested, &mut tx[..needed - 1]),
        Err(Il2pError::BufferTooSmall {
            needed,
            got: needed - 1,
        }),
        "{len} bytes, max_fec {max_fec}"
    );

    let wire = encode_raw(payload, requested, &mut tx[..needed]).unwrap();
    assert_eq!(
        wire, needed,
        "{len} bytes, max_fec {max_fec}: encode returned a length it did not write"
    );

    let mut out = [0u8; PAYLOAD_MAX];
    let decoded = il2p::decode(&tx[SYNC_LEN..wire], requested, &mut out)
        .unwrap_or_else(|e| panic!("{len} bytes, max_fec {max_fec}: decode failed: {e:?}"));
    assert_eq!(decoded.payload_len, len, "{len} bytes, max_fec {max_fec}");
    assert_eq!(
        &out[..len],
        payload,
        "{len} bytes, max_fec {max_fec}: payload not recovered byte for byte"
    );
    assert_eq!(
        decoded.corrected(),
        0,
        "{len} bytes, max_fec {max_fec}: clean channel must need no correction"
    );

    // One byte fewer on the air must be short, which pins `wire` as the
    // exact frame length: the receiver needs every byte encode reported.
    let err = il2p::decode(&tx[SYNC_LEN..wire - 1], requested, &mut out).unwrap_err();
    assert!(
        matches!(err, Il2pError::FrameTooShort { .. }),
        "{len} bytes, max_fec {max_fec}: truncation by one gave {err:?}"
    );
}

/// Every legal payload length, at both FEC levels, through
/// encode -> decode.
///
/// Payload length is a dimension in its own right here, because the two
/// FEC levels split the payload with **different divisors**: 239 data
/// bytes per block at maximum FEC, 247 at the legacy baseline level. The
/// rest of this file samples a handful of lengths, all of which happen to
/// agree under both divisors; the encoder shipped for a while computing
/// its block count with the max-FEC divisor while reporting a length
/// computed with the baseline one, and every existing test passed.
///
/// A sweep is cheap (2048 frames) and is the only shape of test that
/// cannot be blind to a length-dependent split.
#[test]
fn payload_length_sweep_both_fec_levels() {
    // Both levels at every length in `0..=PAYLOAD_MAX`. Asserted as a
    // floor so a loop that silently stopped iterating cannot pass.
    const MIN_CASES: usize = 2 * (PAYLOAD_MAX + 1);

    let source = sweep_source();
    let mut cases = 0usize;
    for len in 0..=PAYLOAD_MAX {
        // `Two` requests the baseline plan (the header's FEC-level bit
        // clear); the effective symbol count is derived from the block
        // size, not from this value. `Sixteen` requests maximum FEC.
        for requested in [Il2pParity::Two, Il2pParity::Sixteen] {
            assert_length_case(len, requested, &source);
            cases += 1;
        }
    }
    assert!(
        cases >= MIN_CASES,
        "sweep tested {cases} cases, expected at least {MIN_CASES}"
    );
}

/// The four payload-length bands where the two FEC plans disagree about
/// the block count, called out by name.
///
/// `ceil(len / 239)` (maximum FEC) and `ceil(len / 247)` (baseline) are
/// equal for 944 of the 1024 legal lengths. They differ in exactly these
/// four bands, 80 lengths in total:
///
/// | band | baseline blocks | max-FEC blocks |
/// |---|---|---|
/// | `240..=247` | 1 | 2 |
/// | `479..=494` | 2 | 3 |
/// | `718..=741` | 3 | 4 |
/// | `957..=988` | 4 | 5 |
///
/// Every one of the 80 failed: the encoder split the payload with the
/// max-FEC count while `encoded_len`, `payload_wire_len` and `decode`
/// used the baseline one, so it wrote past the length it returned and
/// the frame was both mis-split and truncated, with `Ok` reported. The
/// baseline block also reaches 247 bytes in these bands, overflowing a
/// 239-byte scratch buffer whose every access was a silent
/// `unwrap_or(&[])`.
///
/// Baseline FEC is the operating point the CLI and the doc examples do
/// not use, which is why nothing tripped over it.
#[test]
fn baseline_block_count_bands_regression() {
    const BANDS: [(usize, usize, usize); 4] =
        [(240, 247, 1), (479, 494, 2), (718, 741, 3), (957, 988, 4)];
    const MIN_CASES: usize = 80;

    let source = sweep_source();
    let mut cases = 0usize;
    for (first, last, baseline_blocks) in BANDS {
        for len in first..=last {
            // The shape of the bug, stated directly.
            assert_eq!(
                il2p::block_count_for(len, false),
                baseline_blocks,
                "{len}: baseline block count"
            );
            assert_eq!(
                il2p::block_count_for(len, true),
                baseline_blocks + 1,
                "{len}: max-FEC block count must differ by one here"
            );
            assert_length_case(len, Il2pParity::Two, &source);
            cases += 1;
        }
        // The band edges are edges: one byte outside, the counts agree.
        assert_eq!(il2p::block_count_for(first - 1, false), baseline_blocks);
        assert_eq!(il2p::block_count_for(first - 1, true), baseline_blocks);
        if last < PAYLOAD_MAX {
            assert_eq!(il2p::block_count_for(last + 1, false), baseline_blocks + 1);
            assert_eq!(il2p::block_count_for(last + 1, true), baseline_blocks + 1);
        }
    }
    assert_eq!(
        cases, MIN_CASES,
        "the four bands hold exactly {MIN_CASES} payload lengths"
    );
}

/// A single baseline block may hold [`MAX_BASELINE_BLOCK_DATA`] = 247
/// data bytes -- 8 more than the max-FEC ceiling of 239, because only 8
/// parity symbols have to fit alongside them in the same 255-symbol code
/// word.
///
/// Pinned separately from the sweep because it is the exact length at
/// which the encoder's per-block scratch buffer has to be
/// `MAX_BASELINE_BLOCK_DATA` wide rather than `MAX_BLOCK_DATA`: every
/// access to that buffer is an `unwrap_or(&[])`, so one byte too narrow
/// produces an unscrambled block with parity over an empty slice and no
/// error at all.
#[test]
fn widest_baseline_block_is_247_data_bytes() {
    let len = MAX_BASELINE_BLOCK_DATA;
    assert_eq!(il2p::block_count_for(len, false), 1);
    assert_eq!(il2p::payload_parity(len, false), Il2pParity::Eight);
    assert_eq!(
        il2p::encoded_len(len, Il2pParity::Two),
        SYNC_LEN + HEADER_LEN + HEADER_PARITY_LEN + len + 8
    );
    assert_length_case(len, Il2pParity::Two, &sweep_source());
}