trillium-http 1.0.0

the http implementation for the trillium toolkit
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
use super::*;
use crate::{
    HttpConfig, KnownHeaderName,
    h3::Frame,
    headers::qpack::{FieldSection, PseudoHeaders},
};
use encoding_rs::UTF_8;
use futures_lite::{AsyncRead, AsyncReadExt, io::Cursor};
use test_harness::test;
use trillium_testing::harness;

/// Encode a DATA frame (header + payload) into a Vec.
fn data_frame(payload: &[u8]) -> Vec<u8> {
    let frame = Frame::Data(payload.len() as u64);
    let header_len = frame.encoded_len();
    let mut buf = vec![0u8; header_len + payload.len()];
    frame.encode(&mut buf).unwrap();
    buf[header_len..].copy_from_slice(payload);
    buf
}

/// Encode a HEADERS frame header (no payload — caller appends QPACK bytes).
fn headers_frame(payload_len: u64) -> Vec<u8> {
    let frame = Frame::Headers(payload_len);
    let header_len = frame.encoded_len();
    let mut buf = vec![0u8; header_len];
    frame.encode(&mut buf).unwrap();
    buf
}

/// Encode an unknown frame (type not in the H3 spec) with the given payload.
fn unknown_frame(type_value: u8, payload: &[u8]) -> Vec<u8> {
    let mut buf = vec![];
    buf.push(type_value); // 1-byte QUIC varint for type (must be ≤ 0x3F)
    buf.push(payload.len() as u8); // 1-byte QUIC varint for length (must be ≤ 0x3F)
    buf.extend_from_slice(payload);
    buf
}

/// Encode a QUIC varint, appending to `out`.
fn encode_varint(value: u64, out: &mut Vec<u8>) {
    if value < (1 << 6) {
        out.push(value as u8);
    } else if value < (1 << 14) {
        out.push(0x40 | (value >> 8) as u8);
        out.push(value as u8);
    } else if value < (1 << 30) {
        out.extend_from_slice(&[
            0x80 | (value >> 24) as u8,
            (value >> 16) as u8,
            (value >> 8) as u8,
            value as u8,
        ]);
    } else {
        out.extend_from_slice(&[
            0xC0 | (value >> 56) as u8,
            (value >> 48) as u8,
            (value >> 40) as u8,
            (value >> 32) as u8,
            (value >> 24) as u8,
            (value >> 16) as u8,
            (value >> 8) as u8,
            value as u8,
        ]);
    }
}

/// Encode a GREASE frame with a large (8-byte varint) type value.
/// GREASE type values are of the form `0x1f * N + 0x21`.
fn grease_frame(n: u64, payload: &[u8]) -> Vec<u8> {
    let grease_type = 0x1f * n + 0x21;
    let mut buf = vec![];
    encode_varint(grease_type, &mut buf);
    encode_varint(payload.len() as u64, &mut buf);
    buf.extend_from_slice(payload);
    buf
}

/// Helper to call h3_frame_decode and return (state, output_bytes).
fn decode(
    remaining_in_frame: u64,
    total: u64,
    frame_type: H3BodyFrameType,
    input: &[u8],
    content_length: Option<u64>,
) -> io::Result<(ReceivedBodyState, Vec<u8>)> {
    decode_with_max_len(
        remaining_in_frame,
        total,
        frame_type,
        input,
        content_length,
        1024 * 1024,
    )
}

fn decode_with_max_len(
    remaining_in_frame: u64,
    total: u64,
    frame_type: H3BodyFrameType,
    input: &[u8],
    content_length: Option<u64>,
    max_len: u64,
) -> io::Result<(ReceivedBodyState, Vec<u8>)> {
    decode_with_limits(
        remaining_in_frame,
        total,
        frame_type,
        input,
        content_length,
        max_len,
        u64::MAX,
    )
}

fn decode_with_limits(
    remaining_in_frame: u64,
    total: u64,
    frame_type: H3BodyFrameType,
    input: &[u8],
    content_length: Option<u64>,
    max_len: u64,
    max_trailer_size: u64,
) -> io::Result<(ReceivedBodyState, Vec<u8>)> {
    let mut buf = input.to_vec();
    let mut self_buffer = Buffer::default();
    let (state, bytes) = H3Frame {
        self_buffer: &mut self_buffer,
        remaining_in_frame,
        total,
        frame_type,
        buf: &mut buf,
        content_length,
        max_len,
        max_trailer_size,
        trailers: &mut None,
    }
    .decode()?;
    Ok((state, buf[..bytes].to_vec()))
}

#[test]
fn single_data_frame() {
    let input = data_frame(b"hello");
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 5,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn two_data_frames() {
    let mut input = data_frame(b"hello");
    input.extend_from_slice(&data_frame(b" world"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello world");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 11,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn mid_frame_entry() {
    // Simulate entering with 5 bytes remaining in a DATA frame
    let (state, body) = decode(5, 0, H3BodyFrameType::Data, b"hello", None).unwrap();
    assert_eq!(body, b"hello");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 5,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn mid_frame_then_next_frame() {
    // 3 bytes remaining in current frame, then a new DATA frame follows
    let mut input = b"abc".to_vec();
    input.extend_from_slice(&data_frame(b"def"));
    let (state, body) = decode(3, 0, H3BodyFrameType::Data, &input, None).unwrap();
    assert_eq!(body, b"abcdef");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 6,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn partial_frame_at_end() {
    // DATA frame followed by an incomplete frame header (just the type byte)
    let mut input = data_frame(b"hello");
    input.push(0x00); // start of another DATA frame header, but no length
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(
        state,
        ReceivedBodyState::H3Data {
            partial_frame_header: true,
            ..
        }
    ));
}

#[test]
fn content_length_match() {
    let input = data_frame(b"hello");
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, Some(5)).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 5, .. }));
}

#[test]
fn content_length_exceeded() {
    let input = data_frame(b"hello world");
    let err = decode(0, 0, H3BodyFrameType::Start, &input, Some(5)).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidData);
}

#[test]
fn max_len_exceeded() {
    let input = data_frame(b"hello");
    let err = decode_with_max_len(0, 0, H3BodyFrameType::Start, &input, None, 3).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Unsupported);
}

#[test]
fn unknown_frame_skipped() {
    let mut input = unknown_frame(0x21, b"xxx");
    input.extend_from_slice(&data_frame(b"hello"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 5, .. }));
}

#[test]
fn unexpected_frame_type_is_error() {
    // SETTINGS frame (type 0x04) on a request stream
    let input = vec![0x04, 0x00];
    let err = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidData);
}

#[test]
fn empty_data_frame() {
    let input = data_frame(b"");
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 0,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn empty_data_frame_then_data() {
    let mut input = data_frame(b"");
    input.extend_from_slice(&data_frame(b"hello"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 5, .. }));
}

#[test]
fn data_frame_larger_than_buffer() {
    // Simulate a DATA frame with 100 bytes, but we only have 10 bytes of payload
    let (state, body) = decode(100, 0, H3BodyFrameType::Data, b"0123456789", None).unwrap();
    assert_eq!(body, b"0123456789");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 90,
            total: 10,
            frame_type: H3BodyFrameType::Data,
            partial_frame_header: false,
        }
    );
}

#[test]
fn unknown_frame_before_data() {
    let mut input = unknown_frame(0x21, b"skip me");
    input.extend_from_slice(&data_frame(b"body"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"body");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 4, .. }));
}

#[test]
fn multiple_unknown_frames_interspersed() {
    let mut input = data_frame(b"aaa");
    input.extend_from_slice(&unknown_frame(0x21, b"x"));
    input.extend_from_slice(&data_frame(b"bbb"));
    input.extend_from_slice(&unknown_frame(0x22, b"yy"));
    input.extend_from_slice(&data_frame(b"ccc"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"aaabbbccc");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 9, .. }));
}

#[test]
fn zero_length_unknown_frame() {
    let mut input = unknown_frame(0x21, b"");
    input.extend_from_slice(&data_frame(b"hello"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 5, .. }));
}

#[test]
fn trailers_end_body() {
    let mut input = data_frame(b"body");
    let (_sent_trailers, trailers_buf) = build_trailers();
    input.extend_from_slice(&trailers_buf);
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"body");
    assert_eq!(state, End);
}

#[test]
fn trailers_with_content_length_match() {
    let mut input = data_frame(b"body");
    let (_sent_trailers, trailers_buf) = build_trailers();
    input.extend_from_slice(&trailers_buf);
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, Some(4)).unwrap();
    assert_eq!(body, b"body");
    assert_eq!(state, End);
}

#[test]
fn trailers_with_content_length_mismatch() {
    let mut input = data_frame(b"body");
    input.extend_from_slice(&headers_frame(5));
    let (_sent_trailers, trailers_buf) = build_trailers();
    input.extend_from_slice(&trailers_buf);
    let err = decode(0, 0, H3BodyFrameType::Start, &input, Some(10)).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidData);
}

#[test]
fn trailers_exceed_max_trailer_size() {
    // Trailer HEADERS frame declaring 100 bytes of payload, limit is 50 bytes.
    let mut input = data_frame(b"body");
    let (_sent_trailers, trailers_buf) = build_trailers();
    input.extend_from_slice(&trailers_buf);
    let err = decode_with_limits(0, 0, H3BodyFrameType::Start, &input, None, 1024 * 1024, 10)
        .unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Other);
    // Verify we embedded the right H3 error code for the QUIC layer to surface.
    let h3_code = err
        .get_ref()
        .and_then(|e| e.downcast_ref::<H3ErrorCode>())
        .copied();
    assert_eq!(h3_code, Some(H3ErrorCode::MessageError));
}

fn build_trailers() -> (Headers, Vec<u8>) {
    let mut trailers = Headers::new();
    trailers.insert(KnownHeaderName::Trailer, "x-checksum");
    trailers.insert("x-checksum", "abc123");

    let mut qpack_buf = Vec::new();
    FieldSection::new(PseudoHeaders::default(), &trailers).encode(&mut qpack_buf);
    let mut input = vec![];
    input.extend_from_slice(&headers_frame(qpack_buf.len() as u64));
    input.extend_from_slice(&qpack_buf);
    (trailers, input)
}

#[test]
fn trailers_decoded_into_destination() {
    let mut input = data_frame(b"body");
    let (sent_trailers, trailers_buf) = build_trailers();
    input.extend_from_slice(&trailers_buf);
    let mut buf = input.clone();
    let mut self_buffer = Buffer::default();
    let mut trailers: Option<Headers> = None;

    let (state, bytes) = H3Frame {
        self_buffer: &mut self_buffer,
        remaining_in_frame: 0,
        total: 0,
        frame_type: H3BodyFrameType::Start,
        buf: &mut buf,
        content_length: None,
        max_len: 1024 * 1024,
        max_trailer_size: u64::MAX,
        trailers: &mut trailers,
    }
    .decode()
    .unwrap();

    assert_eq!(&buf[..bytes], b"body");
    assert_eq!(state, End);
    let received_trailers = trailers.expect("trailers should be populated");
    assert_eq!(received_trailers.get_str("x-checksum"), Some("abc123"));
    assert_eq!(sent_trailers, received_trailers);
}

#[test]
fn trailers_at_max_trailer_size_allowed() {
    // Exactly at the limit must succeed.
    let mut input = data_frame(b"body");

    let mut trailers = Headers::new();
    trailers.insert(KnownHeaderName::Trailer, "x-checksum");
    trailers.insert("x-checksum", "abc123");

    let mut qpack_buf = Vec::new();
    FieldSection::new(PseudoHeaders::default(), &trailers).encode(&mut qpack_buf);
    let payload_len = qpack_buf.len() as u64;
    input.extend_from_slice(&headers_frame(payload_len));
    input.extend_from_slice(&qpack_buf);

    let (state, body) = decode_with_limits(
        0,
        0,
        H3BodyFrameType::Start,
        &input,
        None,
        1024 * 1024,
        payload_len,
    )
    .unwrap();
    assert_eq!(body, b"body");
    assert_eq!(state, End);
}

#[test]
fn unknown_frame_larger_than_buffer() {
    // Unknown frame with 20 bytes payload, but only 5 bytes of it are in this buffer
    let (state, body) = decode(20, 0, H3BodyFrameType::Unknown, b"12345", None).unwrap();
    assert_eq!(body, b"");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 15,
            total: 0,
            frame_type: H3BodyFrameType::Unknown,
            partial_frame_header: false,
        }
    );
}

#[test]
fn mid_unknown_then_data() {
    // 3 bytes remaining in unknown frame, then a DATA frame
    let mut input = b"xxx".to_vec();
    input.extend_from_slice(&data_frame(b"real"));
    let (state, body) = decode(3, 0, H3BodyFrameType::Unknown, &input, None).unwrap();
    assert_eq!(body, b"real");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 4, .. }));
}

#[test]
fn content_length_exceeded_across_frames() {
    // Two DATA frames that together exceed content-length
    let mut input = data_frame(b"abc");
    input.extend_from_slice(&data_frame(b"def"));
    let err = decode(0, 0, H3BodyFrameType::Start, &input, Some(5)).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::InvalidData);
}

#[test]
fn max_len_exceeded_mid_frame() {
    // Enter mid-frame with total already near the limit
    let err =
        decode_with_max_len(10, 95, H3BodyFrameType::Data, b"0123456789", None, 100).unwrap_err();
    assert_eq!(err.kind(), ErrorKind::Unsupported);
}

// --- Async tests using ReceivedBody ---

async fn read_with_buffers_of_size<R>(reader: &mut R, size: usize) -> crate::Result<String>
where
    R: AsyncRead + Unpin,
{
    let mut return_buffer = vec![];
    loop {
        let mut buf = vec![0; size];
        match reader.read(&mut buf).await? {
            0 => break Ok(String::from_utf8_lossy(&return_buffer).into()),
            bytes_read => return_buffer.extend_from_slice(&buf[..bytes_read]),
        }
    }
}

fn new_h3_body(
    input: Vec<u8>,
    content_length: Option<u64>,
    config: &HttpConfig,
) -> ReceivedBody<'_, Cursor<Vec<u8>>> {
    ReceivedBody::new_with_config(
        content_length,
        Buffer::from(Vec::with_capacity(config.response_header_initial_capacity)),
        Cursor::new(input),
        ReceivedBodyState::H3Data {
            remaining_in_frame: 0,
            total: 0,
            frame_type: H3BodyFrameType::Start,
            partial_frame_header: false,
        },
        None,
        UTF_8,
        config,
    )
}

/// Build DATA-framed bytes from a raw body string.
fn frame_body(body: &str) -> Vec<u8> {
    data_frame(body.as_bytes())
}

/// Build DATA-framed bytes as multiple small frames of `chunk_size`.
fn frame_body_chunked(body: &str, chunk_size: usize) -> Vec<u8> {
    let mut out = vec![];
    for chunk in body.as_bytes().chunks(chunk_size) {
        out.extend_from_slice(&data_frame(chunk));
    }
    out
}

async fn h3_decode(input: Vec<u8>, poll_size: usize) -> crate::Result<String> {
    let mut rb = new_h3_body(input, None, &HttpConfig::DEFAULT);
    read_with_buffers_of_size(&mut rb, poll_size).await
}

#[test(harness)]
async fn async_single_frame_various_buffer_sizes() {
    let body = "hello world";
    let framed = frame_body(body);
    for size in 1..50 {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, body, "size: {size}");
    }
}

#[test(harness)]
async fn async_multiple_frames_various_buffer_sizes() {
    let body = "the quick brown fox jumps over the lazy dog";
    let framed = frame_body_chunked(body, 5);
    for size in 1..50 {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, body, "size: {size}");
    }
}

#[test(harness)]
async fn async_with_unknown_frames_interspersed() {
    let mut framed = vec![];
    framed.extend_from_slice(&data_frame(b"hello"));
    framed.extend_from_slice(&unknown_frame(0x21, b"skip"));
    framed.extend_from_slice(&data_frame(b" "));
    framed.extend_from_slice(&unknown_frame(0x22, b""));
    framed.extend_from_slice(&data_frame(b"world"));
    for size in 1..50 {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, "hello world", "size: {size}");
    }
}

#[test(harness)]
async fn async_content_length_valid() {
    let body = "test ".repeat(50);
    let framed = frame_body(&body);
    let rb = new_h3_body(framed, Some(body.len() as u64), &HttpConfig::DEFAULT);
    let output = rb.read_string().await.unwrap();
    assert_eq!(output, body);
}

#[test(harness)]
async fn async_content_length_mismatch() {
    let body = "test ".repeat(50);
    let framed = frame_body(&body);
    // Claim content-length is shorter than actual
    let rb = new_h3_body(framed, Some(10), &HttpConfig::DEFAULT);
    assert!(rb.read_string().await.is_err());
}

#[test(harness)]
async fn async_max_len() {
    let body = "test ".repeat(100);
    let framed = frame_body(&body);

    // Should succeed with default max_len
    let rb = new_h3_body(framed.clone(), None, &HttpConfig::DEFAULT);
    assert!(rb.read_string().await.is_ok());

    // Should fail with small max_len
    let config = HttpConfig::DEFAULT.with_received_body_max_len(100);
    let rb = new_h3_body(framed, None, &config);
    assert!(rb.read_string().await.is_err());
}

#[test(harness)]
async fn async_empty_body() {
    // No DATA frames at all — just an empty stream
    let framed = vec![];
    let rb = new_h3_body(framed, None, &HttpConfig::DEFAULT);
    let output = rb.read_string().await.unwrap();
    assert_eq!(output, "");
}

#[test(harness)]
async fn async_empty_data_frame() {
    let framed = data_frame(b"");
    for size in 1..20 {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, "", "size: {size}");
    }
}

#[test(harness)]
async fn async_large_body_various_frame_and_buffer_sizes() {
    let body = "abcdefghij".repeat(100); // 1000 bytes
    for chunk_size in [1, 7, 50, 100, 999, 1000] {
        let framed = frame_body_chunked(&body, chunk_size);
        for buf_size in [3, 10, 64, 256, 1024] {
            let output = h3_decode(framed.clone(), buf_size).await.unwrap();
            assert_eq!(
                output, body,
                "chunk_size: {chunk_size}, buf_size: {buf_size}"
            );
        }
    }
}

// --- GREASE frame tests (8-byte varint frame types, like curl sends) ---

#[test]
fn grease_frame_skipped() {
    let mut input = grease_frame(1_000_000, b"GREASE is the word");
    input.extend_from_slice(&data_frame(b"hello"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"hello");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 5, .. }));
}

#[test]
fn grease_frame_between_data_frames() {
    let mut input = data_frame(b"aaa");
    input.extend_from_slice(&grease_frame(999_999, b"grease payload"));
    input.extend_from_slice(&data_frame(b"bbb"));
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"aaabbb");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 6, .. }));
}

#[test]
fn grease_frame_spans_buffer_boundary() {
    // GREASE frame with 20 bytes payload, but only 5 bytes available
    let grease = grease_frame(500_000, &[0xAA; 20]);
    // Take just the header + 5 bytes of payload
    let header_end = grease.len() - 20;
    let input = grease[..header_end + 5].to_vec();
    // This should leave us mid-unknown-frame
    let (state, body) = decode(0, 0, H3BodyFrameType::Start, &input, None).unwrap();
    assert_eq!(body, b"");
    assert_eq!(
        state,
        ReceivedBodyState::H3Data {
            remaining_in_frame: 15,
            total: 0,
            frame_type: H3BodyFrameType::Unknown,
            partial_frame_header: false,
        }
    );

    // Now continue with remaining 15 bytes of GREASE payload + a DATA frame
    let mut input2 = vec![0xAA; 15];
    input2.extend_from_slice(&data_frame(b"after grease"));
    let (state, body) = decode(15, 0, H3BodyFrameType::Unknown, &input2, None).unwrap();
    assert_eq!(body, b"after grease");
    assert!(matches!(state, ReceivedBodyState::H3Data { total: 12, .. }));
}

#[test(harness)]
async fn async_grease_interspersed_various_buffer_sizes() {
    let mut framed = vec![];
    framed.extend_from_slice(&grease_frame(1_000_000, b"GREASE is the word"));
    framed.extend_from_slice(&data_frame(b"hello"));
    framed.extend_from_slice(&grease_frame(2_000_000, b""));
    framed.extend_from_slice(&data_frame(b" "));
    framed.extend_from_slice(&grease_frame(3_000_000, b"more grease"));
    framed.extend_from_slice(&data_frame(b"world"));

    for size in 1..60 {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, "hello world", "buf_size: {size}");
    }
}

#[test(harness)]
async fn async_grease_only_buffer() {
    // A buffer where the entire read is GREASE — no DATA bytes at all in
    // the first several reads, then DATA follows.
    let mut framed = vec![];
    // Several GREASE frames totaling ~100 bytes
    for i in 0..5 {
        framed.extend_from_slice(&grease_frame(1_000_000 + i, b"grease padding!"));
    }
    framed.extend_from_slice(&data_frame(b"finally data"));

    for size in [1, 3, 10, 16, 32, 64, 128] {
        let output = h3_decode(framed.clone(), size).await.unwrap();
        assert_eq!(output, "finally data", "buf_size: {size}");
    }
}