h3x 0.6.1

Peer-to-peer DHTTP/3 transport over QUIC
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
use bytes::Bytes;

use crate::qpack::{
    encoder::EncoderState,
    field::{EncodedFieldSectionPrefix, FieldLine, FieldLineRepresentation},
    r#static,
};

pub trait HuffmanStrategize {
    fn should_encode_name_with_huffman(&self, name: &Bytes) -> bool;
    fn should_encode_value_with_huffman(&self, value: &Bytes) -> bool;
}

pub struct HuffmanAlways;

impl HuffmanStrategize for HuffmanAlways {
    fn should_encode_name_with_huffman(&self, _name: &Bytes) -> bool {
        true
    }
    fn should_encode_value_with_huffman(&self, _value: &Bytes) -> bool {
        true
    }
}

pub struct HuffmanNever;

impl HuffmanStrategize for HuffmanNever {
    fn should_encode_name_with_huffman(&self, _name: &Bytes) -> bool {
        false
    }
    fn should_encode_value_with_huffman(&self, _value: &Bytes) -> bool {
        false
    }
}

/// Output of a compression algorithm.
pub struct CompressOutput {
    pub prefix: EncodedFieldSectionPrefix,
    pub representations: Vec<FieldLineRepresentation>,
    /// Maximum absolute index of a dynamic table entry referenced by this field section.
    /// Used for blocked stream tracking. `None` if no dynamic table entries are referenced.
    pub max_referenced_index: Option<u64>,
}

/// Compresses HTTP field lines into QPACK representations.
///
/// This trait defines the interface for field line compression algorithms that convert
/// HTTP field lines into QPACK-encoded representations suitable for transmission.
///
/// # The `never_dynamic` Contract
///
/// Implementations **MUST** respect the `never_dynamic` (N-bit) constraint per RFC 9204 §7.1.
/// When compressing a field line, if the resulting representation has `never_dynamic: true`,
/// the field **MUST NOT** be inserted into the dynamic table. Fields marked with the N-bit
/// are intended for protecting field values that should not be put at risk by compression.
///
/// The `never_dynamic` flag appears in these representation types:
/// - [`FieldLineRepresentation::LiteralFieldLineWithNameReference`]: `never_dynamic: bool`
/// - [`FieldLineRepresentation::LiteralFieldLineWithPostBaseNameReference`]: `never_dynamic: bool`
/// - [`FieldLineRepresentation::LiteralFieldLineWithLiteralName`]: `never_dynamic: bool`
///
/// # The `may_block` Parameter
///
/// When `may_block` is `true`, the algorithm may reference unacknowledged dynamic table entries,
/// which would block the stream at the decoder until those entries are received.
/// When `false`, only acknowledged entries (absolute index < known_received_count) and the
/// static table may be referenced. The caller (`Encoder::encode`) computes this based on
/// SETTINGS_QPACK_BLOCKED_STREAMS.
pub trait Algorithm {
    fn compress(
        &self,
        state: &mut EncoderState,
        entries: impl IntoIterator<Item = FieldLine> + Send,
        may_block: bool,
    ) -> impl Future<Output = CompressOutput> + Send;
}

pub struct StaticCompressAlgo<HS> {
    huffman_strategize: HS,
}

impl<HS> StaticCompressAlgo<HS> {
    pub const fn new(huffman_strategize: HS) -> Self {
        Self { huffman_strategize }
    }
}

impl<HS> Algorithm for StaticCompressAlgo<HS>
where
    HS: HuffmanStrategize + Send + Sync,
{
    /// Compresses field lines using only the static table and literal representations.
    ///
    /// Never uses the dynamic table. Always sets `never_dynamic: true`.
    async fn compress(
        &self,
        _state: &mut EncoderState,
        entries: impl IntoIterator<Item = FieldLine> + Send,
        _may_block: bool,
    ) -> CompressOutput {
        let prefix = EncodedFieldSectionPrefix {
            encoded_insert_count: 0,
            sign: false,
            delta_base: 0,
        };
        let mut representations = Vec::new();
        for FieldLine { name, value } in entries {
            if let (Some(name_index), value_index) = r#static::find(&name, &value) {
                if value_index == Some(name_index) {
                    representations.push(FieldLineRepresentation::IndexedFieldLine {
                        is_static: true,
                        index: name_index as u64,
                    })
                } else {
                    representations.push(
                        FieldLineRepresentation::LiteralFieldLineWithNameReference {
                            never_dynamic: true,
                            is_static: true,
                            name_index: name_index as u64,
                            huffman: self
                                .huffman_strategize
                                .should_encode_value_with_huffman(&value),
                            value: value.clone(),
                        },
                    )
                }
            } else {
                representations.push(FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                    never_dynamic: true,
                    name_huffman: self
                        .huffman_strategize
                        .should_encode_name_with_huffman(&name),
                    name: name.clone(),
                    value_huffman: self
                        .huffman_strategize
                        .should_encode_value_with_huffman(&value),
                    value: value.clone(),
                })
            }
        }
        CompressOutput {
            prefix,
            representations,
            max_referenced_index: None,
        }
    }
}

/// RFC 9204 §7.1: Headers whose values MUST NOT be inserted into the dynamic table.
const SENSITIVE_HEADER_NAMES: &[&[u8]] = &[
    b"authorization",
    b"proxy-authorization",
    b"cookie",
    b"set-cookie",
];

fn is_sensitive(name: &[u8]) -> bool {
    SENSITIVE_HEADER_NAMES
        .iter()
        .any(|s| name.eq_ignore_ascii_case(s))
}

/// Compression algorithm that utilizes the QPACK dynamic table.
///
/// Implements the single-pass encoding algorithm from RFC 9204 Appendix C.
/// For each field line, the decision tree is:
///
/// 1. Static table exact match → indexed field line (static)
/// 2. Dynamic table exact match → indexed field line (dynamic or post-base)
/// 3. No exact match → attempt insertion with best name reference, then post-base index
/// 4. Insertion failed or not allowed → literal with name reference or literal name
pub struct DynamicCompressAlgo<HS> {
    huffman_strategize: HS,
}

impl<HS> DynamicCompressAlgo<HS> {
    pub const fn new(huffman_strategize: HS) -> Self {
        Self { huffman_strategize }
    }
}

impl<HS> Algorithm for DynamicCompressAlgo<HS>
where
    HS: HuffmanStrategize + Send + Sync,
{
    async fn compress(
        &self,
        state: &mut EncoderState,
        entries: impl IntoIterator<Item = FieldLine> + Send,
        may_block: bool,
    ) -> CompressOutput {
        // RFC 9204 Appendix C: base = dynamicTable.getInsertCount()
        let base = state.table_inserted_count();
        let max_table_capacity = state.table_capacity();
        let known_received_count = state.table_known_received_count();

        let mut representations = Vec::new();
        let mut max_ref: Option<u64> = None;

        for FieldLine { name, value } in entries {
            let never_dynamic = is_sensitive(&name);

            // Step 1: Static table exact match
            let (static_name_idx, static_value_idx) = r#static::find(&name, &value);
            if let Some(val_idx) = static_value_idx
                && static_name_idx == Some(val_idx)
            {
                representations.push(FieldLineRepresentation::IndexedFieldLine {
                    is_static: true,
                    index: val_idx as u64,
                });
                continue;
            }

            // Step 2: Dynamic table exact match (name + value)
            if let Some(abs) = find_dynamic_exact(state, &name, &value)
                && can_reference(abs, known_received_count, may_block)
            {
                track_ref(&mut max_ref, abs);
                push_dynamic_index(&mut representations, abs, base);
                continue;
            }

            // Step 3: Try insertion (if not sensitive and entry fits)
            // When may_block=false, we still insert speculatively to populate the table
            // for future field sections, but don't reference the new entry.
            let dynamic_name_abs = find_dynamic_name(state, &name);

            if !never_dynamic && entry_fits_capacity(state, &name, &value) {
                let insert_result = if let Some(static_idx) = static_name_idx {
                    state.insert_with_name_reference(
                        true,
                        static_idx as u64,
                        self.huffman_strategize
                            .should_encode_value_with_huffman(&value),
                        value.clone(),
                    )
                } else if let Some(dyn_abs) = dynamic_name_abs {
                    state.insert_with_name_reference(
                        false,
                        dyn_abs,
                        self.huffman_strategize
                            .should_encode_value_with_huffman(&value),
                        value.clone(),
                    )
                } else {
                    state.insert_with_literal_name(
                        self.huffman_strategize
                            .should_encode_name_with_huffman(&name),
                        name.clone(),
                        self.huffman_strategize
                            .should_encode_value_with_huffman(&value),
                        value.clone(),
                    )
                };

                if let Ok(new_abs) = insert_result {
                    // Only reference the new post-base entry if blocking is allowed
                    if may_block {
                        track_ref(&mut max_ref, new_abs);
                        representations.push(
                            FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex {
                                index: new_abs - base,
                            },
                        );
                        continue;
                    }
                    // may_block=false: entry inserted but not referenced — fall through
                }
                // Insert failed (CannotEvict) — fall through to literal encoding
            }

            // Step 4: Literal encoding with best available name reference
            if let Some(static_idx) = static_name_idx {
                representations.push(FieldLineRepresentation::LiteralFieldLineWithNameReference {
                    never_dynamic,
                    is_static: true,
                    name_index: static_idx as u64,
                    huffman: self
                        .huffman_strategize
                        .should_encode_value_with_huffman(&value),
                    value: value.clone(),
                });
            } else if let Some(dyn_abs) = dynamic_name_abs {
                if can_reference(dyn_abs, known_received_count, may_block) {
                    track_ref(&mut max_ref, dyn_abs);
                    push_dynamic_name_ref(
                        &mut representations,
                        dyn_abs,
                        base,
                        never_dynamic,
                        self.huffman_strategize
                            .should_encode_value_with_huffman(&value),
                        value.clone(),
                    );
                } else {
                    push_literal_name(
                        &mut representations,
                        &self.huffman_strategize,
                        never_dynamic,
                        name.clone(),
                        value.clone(),
                    );
                }
            } else {
                push_literal_name(
                    &mut representations,
                    &self.huffman_strategize,
                    never_dynamic,
                    name.clone(),
                    value.clone(),
                );
            }
        }

        // Compute prefix per RFC 9204 Appendix C
        let prefix = compute_prefix(max_ref, base, max_table_capacity);

        CompressOutput {
            prefix,
            representations,
            max_referenced_index: max_ref,
        }
    }
}

fn find_dynamic_exact(state: &EncoderState, name: &Bytes, value: &Bytes) -> Option<u64> {
    let name_indices = state.find_name(name)?;
    let value_indices = state.find_value(value)?;
    // Most recent entry matching both name and value (highest absolute index)
    name_indices.intersection(value_indices).last().copied()
}

fn find_dynamic_name(state: &EncoderState, name: &Bytes) -> Option<u64> {
    // Most recent entry matching this name (highest absolute index)
    state.find_name(name)?.iter().next_back().copied()
}

/// Quick pre-check: entry size must not exceed table capacity.
/// The actual insert methods handle eviction and return `Err(CannotEvict)` if needed.
fn entry_fits_capacity(state: &EncoderState, name: &Bytes, value: &Bytes) -> bool {
    let entry_size = name.len() as u64 + value.len() as u64 + 32;
    entry_size <= state.table_capacity()
}

/// Whether an entry at the given absolute index can be referenced.
/// Acknowledged entries (index < known_received_count) are always safe.
/// Unacknowledged entries require `may_block` to be true.
fn can_reference(abs_index: u64, known_received_count: u64, may_block: bool) -> bool {
    abs_index < known_received_count || may_block
}

fn track_ref(max_ref: &mut Option<u64>, index: u64) {
    *max_ref = Some(max_ref.map_or(index, |m| m.max(index)));
}

/// Emit an indexed dynamic reference — pre-base (relative) or post-base.
fn push_dynamic_index(representations: &mut Vec<FieldLineRepresentation>, abs: u64, base: u64) {
    if abs >= base {
        representations
            .push(FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index: abs - base });
    } else {
        representations.push(FieldLineRepresentation::IndexedFieldLine {
            is_static: false,
            index: base - abs - 1,
        });
    }
}

/// Emit a literal with dynamic name reference — pre-base or post-base.
fn push_dynamic_name_ref(
    representations: &mut Vec<FieldLineRepresentation>,
    dyn_abs: u64,
    base: u64,
    never_dynamic: bool,
    huffman: bool,
    value: Bytes,
) {
    if dyn_abs >= base {
        representations.push(
            FieldLineRepresentation::LiteralFieldLineWithPostBaseNameReference {
                never_dynamic,
                name_index: dyn_abs - base,
                huffman,
                value,
            },
        );
    } else {
        representations.push(FieldLineRepresentation::LiteralFieldLineWithNameReference {
            never_dynamic,
            is_static: false,
            name_index: base - dyn_abs - 1,
            huffman,
            value,
        });
    }
}

fn push_literal_name(
    representations: &mut Vec<FieldLineRepresentation>,
    hs: &impl HuffmanStrategize,
    never_dynamic: bool,
    name: Bytes,
    value: Bytes,
) {
    representations.push(FieldLineRepresentation::LiteralFieldLineWithLiteralName {
        never_dynamic,
        name_huffman: hs.should_encode_name_with_huffman(&name),
        name,
        value_huffman: hs.should_encode_value_with_huffman(&value),
        value,
    });
}

fn compute_prefix(
    max_ref: Option<u64>,
    base: u64,
    max_table_capacity: u64,
) -> EncodedFieldSectionPrefix {
    match max_ref {
        Some(max) => {
            let required_insert_count = max + 1;
            let encoded_insert_count =
                EncodedFieldSectionPrefix::encode_ric(required_insert_count, max_table_capacity);
            if base >= required_insert_count {
                EncodedFieldSectionPrefix {
                    encoded_insert_count,
                    sign: false,
                    delta_base: base - required_insert_count,
                }
            } else {
                EncodedFieldSectionPrefix {
                    encoded_insert_count,
                    sign: true,
                    delta_base: required_insert_count - base - 1,
                }
            }
        }
        None => EncodedFieldSectionPrefix {
            encoded_insert_count: 0,
            sign: false,
            delta_base: 0,
        },
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use bytes::Bytes;

    use crate::{
        dhttp::settings::Settings,
        qpack::{
            algorithm::{
                Algorithm, CompressOutput, DynamicCompressAlgo, HuffmanAlways, HuffmanNever,
                StaticCompressAlgo,
            },
            encoder::EncoderState,
            field::{EncodedFieldSectionPrefix, FieldLine, FieldLineRepresentation},
        },
        varint::VarInt,
    };

    fn state_with_capacity(table_capacity: u32) -> EncoderState {
        let mut settings = Settings::default();
        settings.set(crate::qpack::settings::QpackMaxTableCapacity::setting(
            VarInt::from_u32(table_capacity),
        ));
        settings.set(crate::qpack::settings::QpackBlockedStreams::setting(
            VarInt::from_u32(100),
        ));
        let mut state = EncoderState::new(Arc::new(settings));
        if table_capacity > 0 {
            state
                .set_max_table_capacity(table_capacity as u64)
                .expect("set capacity failed");
        }
        state
    }

    fn field_line(name: &str, value: &str) -> FieldLine {
        FieldLine {
            name: Bytes::from(name.to_owned()),
            value: Bytes::from(value.to_owned()),
        }
    }

    fn algo() -> DynamicCompressAlgo<HuffmanNever> {
        DynamicCompressAlgo::new(HuffmanNever)
    }

    fn huffman_algo() -> DynamicCompressAlgo<HuffmanAlways> {
        DynamicCompressAlgo::new(HuffmanAlways)
    }

    async fn do_compress(
        state: &mut EncoderState,
        entries: Vec<FieldLine>,
        may_block: bool,
    ) -> CompressOutput {
        algo().compress(state, entries, may_block).await
    }

    // --- Static table tests ---

    #[tokio::test]
    async fn static_exact_match() {
        let mut state = state_with_capacity(256);
        // ":method GET" is static table entry 17
        let output = do_compress(&mut state, vec![field_line(":method", "GET")], true).await;
        assert_eq!(output.representations.len(), 1);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLine {
                is_static: true,
                index: 17
            }
        ));
        assert!(output.max_referenced_index.is_none());
        assert_eq!(output.prefix.encoded_insert_count, 0);
    }

    // --- Dynamic table insertion ---

    #[tokio::test]
    async fn insert_and_post_base_reference() {
        let mut state = state_with_capacity(256);
        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;

        assert_eq!(output.representations.len(), 1);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index: 0 }
        ));
        assert_eq!(output.max_referenced_index, Some(0));
        assert_ne!(output.prefix.encoded_insert_count, 0);
        // New insertion: base(0) < RIC(1), so sign=true
        assert!(output.prefix.sign);
    }

    #[tokio::test]
    async fn insert_without_blocking_populates_table_but_emits_literal() {
        let mut state = state_with_capacity(256);

        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], false).await;

        assert_eq!(state.table_inserted_count(), 1);
        assert!(output.max_referenced_index.is_none());
        assert_eq!(output.prefix.encoded_insert_count, 0);
        assert!(matches!(
            &output.representations[..],
            [FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                never_dynamic: false,
                name_huffman: false,
                name,
                value_huffman: false,
                value,
            }] if name.as_ref() == b"x-custom" && value.as_ref() == b"hello"
        ));
    }

    #[tokio::test]
    async fn second_request_uses_pre_base_dynamic_ref() {
        let mut state = state_with_capacity(256);

        // First request: insert entry
        let _ = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;
        // Simulate decoder acknowledging the entry
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        // Second request: same header should use pre-base indexed reference
        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;

        assert_eq!(output.representations.len(), 1);
        // base = 1, absolute = 0, wire index = base - abs - 1 = 0
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLine {
                is_static: false,
                index: 0
            }
        ));
        assert_eq!(output.max_referenced_index, Some(0));
        // base(1) >= RIC(1), so sign=false
        assert!(!output.prefix.sign);
    }

    // --- Sensitive headers ---

    #[tokio::test]
    async fn sensitive_headers_never_inserted() {
        let mut state = state_with_capacity(256);
        let output = do_compress(
            &mut state,
            vec![field_line("authorization", "Bearer secret")],
            true,
        )
        .await;

        assert_eq!(output.representations.len(), 1);
        // "authorization" exists in static table as name — uses static name ref with N-bit
        match &output.representations[0] {
            FieldLineRepresentation::LiteralFieldLineWithNameReference {
                never_dynamic,
                is_static,
                ..
            } => {
                assert!(
                    never_dynamic,
                    "sensitive header should have never_dynamic=true"
                );
                assert!(is_static, "should use static name reference");
            }
            FieldLineRepresentation::LiteralFieldLineWithLiteralName { never_dynamic, .. } => {
                assert!(
                    never_dynamic,
                    "sensitive header should have never_dynamic=true"
                );
            }
            other => panic!("expected literal representation, got {other:?}"),
        }
        assert!(output.max_referenced_index.is_none());
        assert_eq!(state.table_inserted_count(), 0);
    }

    #[tokio::test]
    async fn cookie_header_never_inserted() {
        let mut state = state_with_capacity(256);
        let output = do_compress(&mut state, vec![field_line("cookie", "session=abc")], true).await;

        // "cookie" is static table entry 5 — should use name reference, never_dynamic=true
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithNameReference {
                never_dynamic: true,
                is_static: true,
                ..
            }
        ));
        assert_eq!(state.table_inserted_count(), 0);
    }

    // --- may_block=false ---

    #[tokio::test]
    async fn may_block_false_inserts_speculatively_without_reference() {
        let mut state = state_with_capacity(256);
        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], false).await;

        // may_block=false: entry IS inserted speculatively but NOT referenced
        assert!(output.max_referenced_index.is_none());
        assert_eq!(state.table_inserted_count(), 1);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithLiteralName { .. }
        ));
    }

    #[tokio::test]
    async fn may_block_false_can_reference_acknowledged() {
        let mut state = state_with_capacity(256);

        // Insert with may_block=true, then acknowledge
        let _ = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        // may_block=false should still reference the acknowledged entry
        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], false).await;

        assert_eq!(output.representations.len(), 1);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLine {
                is_static: false,
                ..
            }
        ));
        assert!(output.max_referenced_index.is_some());
    }

    // --- Name reference fallback ---

    #[tokio::test]
    async fn static_name_reference_with_literal_value() {
        let mut state = state_with_capacity(0);
        let output = do_compress(
            &mut state,
            vec![field_line(":path", "/my/custom/path")],
            true,
        )
        .await;

        assert_eq!(output.representations.len(), 1);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithNameReference {
                is_static: true,
                ..
            }
        ));
    }

    #[tokio::test]
    async fn static_algorithm_emits_all_three_representation_forms() {
        let mut state = state_with_capacity(256);
        let algo = StaticCompressAlgo::new(HuffmanAlways);
        let output = algo
            .compress(
                &mut state,
                vec![
                    field_line(":method", "GET"),
                    field_line(":path", "/custom"),
                    field_line("x-literal", "value"),
                ],
                false,
            )
            .await;

        assert_eq!(output.representations.len(), 3);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLine {
                is_static: true,
                index: 17
            }
        ));
        assert!(matches!(
            &output.representations[1],
            FieldLineRepresentation::LiteralFieldLineWithNameReference {
                never_dynamic: true,
                is_static: true,
                huffman: true,
                value,
                ..
            } if value == b"/custom".as_slice()
        ));
        assert!(matches!(
            &output.representations[2],
            FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                never_dynamic: true,
                name_huffman: true,
                name,
                value_huffman: true,
                value,
            } if name == b"x-literal".as_slice() && value == b"value".as_slice()
        ));
        assert_eq!(state.table_inserted_count(), 0);
        assert!(output.max_referenced_index.is_none());
        assert_eq!(
            output.prefix,
            EncodedFieldSectionPrefix {
                encoded_insert_count: 0,
                sign: false,
                delta_base: 0,
            }
        );
    }

    #[tokio::test]
    async fn dynamic_literal_name_uses_huffman_flags_from_strategy() {
        let mut state = state_with_capacity(0);
        let output = huffman_algo()
            .compress(&mut state, vec![field_line("x-huffman", "value")], true)
            .await;

        assert!(matches!(
            &output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                never_dynamic: false,
                name_huffman: true,
                name,
                value_huffman: true,
                value,
            } if name == b"x-huffman".as_slice() && value == b"value".as_slice()
        ));
    }

    #[tokio::test]
    async fn all_sensitive_header_names_are_case_insensitive_and_never_inserted() {
        let sensitive_names = [
            "authorization",
            "AUTHORIZATION",
            "proxy-authorization",
            "Proxy-Authorization",
            "cookie",
            "COOKIE",
            "set-cookie",
            "Set-Cookie",
        ];

        for name in sensitive_names {
            let mut state = state_with_capacity(256);
            let output = do_compress(&mut state, vec![field_line(name, "secret")], true).await;

            assert_eq!(state.table_inserted_count(), 0, "{name} was inserted");
            assert!(
                output.max_referenced_index.is_none(),
                "{name} referenced dynamic table"
            );
            match &output.representations[0] {
                FieldLineRepresentation::LiteralFieldLineWithNameReference {
                    never_dynamic,
                    ..
                }
                | FieldLineRepresentation::LiteralFieldLineWithPostBaseNameReference {
                    never_dynamic,
                    ..
                }
                | FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                    never_dynamic, ..
                } => assert!(*never_dynamic, "{name} did not set never_dynamic"),
                other => panic!("expected literal representation for {name}, got {other:?}"),
            }
        }
    }

    #[tokio::test]
    async fn dynamic_exact_match_can_use_post_base_reference() {
        let mut state = state_with_capacity(256);
        let output = do_compress(
            &mut state,
            vec![
                field_line("x-repeat", "same"),
                field_line("x-repeat", "same"),
            ],
            true,
        )
        .await;

        assert_eq!(state.table_inserted_count(), 1);
        assert_eq!(output.max_referenced_index, Some(0));
        assert!(matches!(
            output.representations.as_slice(),
            [
                FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index: 0 },
                FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index: 0 },
            ]
        ));
    }

    #[tokio::test]
    async fn dynamic_name_reference_uses_pre_base_when_name_is_acknowledged() {
        let mut state = state_with_capacity(48);

        let _ = do_compress(&mut state, vec![field_line("x-ref", "a")], true).await;
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        let output = do_compress(&mut state, vec![field_line("x-ref", "longer-value")], true).await;

        assert_eq!(state.table_inserted_count(), 1);
        assert_eq!(output.max_referenced_index, Some(0));
        assert!(matches!(
            &output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithNameReference {
                never_dynamic: false,
                is_static: false,
                name_index: 0,
                huffman: false,
                value,
            } if value == b"longer-value".as_slice()
        ));
    }

    #[tokio::test]
    async fn dynamic_name_reference_uses_post_base_when_name_is_new_in_section() {
        let mut state = state_with_capacity(48);
        let output = do_compress(
            &mut state,
            vec![
                field_line("x-ref", "a"),
                field_line("x-ref", "longer-value"),
            ],
            true,
        )
        .await;

        assert_eq!(state.table_inserted_count(), 1);
        assert_eq!(output.max_referenced_index, Some(0));
        assert!(matches!(
            &output.representations[1],
            FieldLineRepresentation::LiteralFieldLineWithPostBaseNameReference {
                never_dynamic: false,
                name_index: 0,
                huffman: false,
                value,
            } if value == b"longer-value".as_slice()
        ));
    }

    #[tokio::test]
    async fn may_block_false_falls_back_when_dynamic_name_is_unacknowledged() {
        let mut state = state_with_capacity(48);

        let _ = do_compress(&mut state, vec![field_line("x-ref", "a")], true).await;
        assert_eq!(state.table_known_received_count(), 0);

        let output =
            do_compress(&mut state, vec![field_line("x-ref", "longer-value")], false).await;

        assert_eq!(state.table_inserted_count(), 1);
        assert!(output.max_referenced_index.is_none());
        assert!(matches!(
            &output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithLiteralName {
                never_dynamic: false,
                name_huffman: false,
                name,
                value_huffman: false,
                value,
            } if name == b"x-ref".as_slice() && value == b"longer-value".as_slice()
        ));
    }

    #[tokio::test]
    async fn prefix_required_insert_count_uses_largest_dynamic_reference() {
        let mut state = state_with_capacity(256);

        let _ = do_compress(
            &mut state,
            vec![field_line("x-a", "one"), field_line("x-b", "two")],
            true,
        )
        .await;
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        let output = do_compress(
            &mut state,
            vec![field_line("x-a", "one"), field_line("x-b", "two")],
            true,
        )
        .await;

        assert_eq!(output.max_referenced_index, Some(1));
        assert_eq!(
            output.prefix,
            EncodedFieldSectionPrefix {
                encoded_insert_count: EncodedFieldSectionPrefix::encode_ric(2, 256),
                sign: false,
                delta_base: 0,
            }
        );
    }

    // --- Multiple entries ---

    #[tokio::test]
    async fn multiple_insertions_correct_post_base_indices() {
        let mut state = state_with_capacity(4096);
        let output = do_compress(
            &mut state,
            vec![
                field_line("x-header-a", "value-a"),
                field_line("x-header-b", "value-b"),
                field_line("x-header-c", "value-c"),
            ],
            true,
        )
        .await;

        assert_eq!(output.representations.len(), 3);
        for (i, repr) in output.representations.iter().enumerate() {
            assert!(
                matches!(
                    repr,
                    FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index }
                    if *index == i as u64
                ),
                "entry {i}: expected PostBaseIndex({i}), got {repr:?}"
            );
        }
        assert_eq!(state.table_inserted_count(), 3);
        assert_eq!(output.max_referenced_index, Some(2));
    }

    // --- Duplicate name with different value ---

    #[tokio::test]
    async fn same_name_different_value_inserts_new_entry() {
        let mut state = state_with_capacity(4096);

        let _ = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        // Same name, different value — should insert new entry
        let output = do_compress(&mut state, vec![field_line("x-custom", "world")], true).await;

        assert_eq!(state.table_inserted_count(), 2);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::IndexedFieldLineWithPostBaseIndex { index: 0 }
        ));
    }

    // --- Prefix computation ---

    #[tokio::test]
    async fn prefix_no_dynamic_refs() {
        let mut state = state_with_capacity(0);
        let output = do_compress(&mut state, vec![field_line(":method", "GET")], true).await;

        assert_eq!(
            output.prefix,
            EncodedFieldSectionPrefix {
                encoded_insert_count: 0,
                sign: false,
                delta_base: 0,
            }
        );
    }

    #[tokio::test]
    async fn prefix_with_post_base_sign_true() {
        let mut state = state_with_capacity(256);
        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;

        // base=0, RIC=1, sign=true (base < RIC), delta_base = RIC - base - 1 = 0
        assert!(output.prefix.sign);
        assert_eq!(output.prefix.delta_base, 0);
    }

    #[tokio::test]
    async fn prefix_with_pre_base_sign_false() {
        let mut state = state_with_capacity(256);

        let _ = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;
        state.dynamic_table.known_received_count = state.dynamic_table.inserted_count;

        let output = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;

        // base=1, RIC=1, sign=false (base >= RIC), delta_base = base - RIC = 0
        assert!(!output.prefix.sign);
        assert_eq!(output.prefix.delta_base, 0);
    }

    // --- Encoder instructions ---

    #[tokio::test]
    async fn insert_emits_encoder_instructions() {
        let mut state = state_with_capacity(256);
        let _ = do_compress(&mut state, vec![field_line("x-custom", "hello")], true).await;

        // SetDynamicTableCapacity (from state_with_capacity) + InsertWithLiteralName
        assert_eq!(state.pending_instructions.len(), 2);
    }

    #[tokio::test]
    async fn insert_with_static_name_emits_name_reference() {
        let mut state = state_with_capacity(256);
        let _ = do_compress(
            &mut state,
            vec![field_line(":path", "/my/custom/path")],
            true,
        )
        .await;

        assert_eq!(state.table_inserted_count(), 1);
        assert!(state.pending_instructions.iter().any(|inst| matches!(
            inst,
            crate::qpack::encoder::EncoderInstruction::InsertWithNameReference {
                is_static: true,
                ..
            }
        )));
    }

    // --- Capacity edge case ---

    #[tokio::test]
    async fn entry_too_large_for_table_falls_to_literal() {
        let mut state = state_with_capacity(64);
        // entry size = 8 + 32 + 32 = 72 > 64
        let output = do_compress(
            &mut state,
            vec![field_line("x-custom", "a-very-long-value-that-wont-fit-")],
            true,
        )
        .await;

        assert_eq!(state.table_inserted_count(), 0);
        assert!(matches!(
            output.representations[0],
            FieldLineRepresentation::LiteralFieldLineWithLiteralName { .. }
        ));
    }

    mod proptest_roundtrip {
        use std::sync::Arc;

        use bytes::Bytes;
        use proptest::prelude::*;

        use crate::{
            dhttp::settings::Settings,
            qpack::{
                algorithm::{Algorithm, DynamicCompressAlgo, HuffmanNever},
                decoder::DecoderState,
                encoder::{EncoderInstruction, EncoderState},
                field::{EncodedFieldSectionPrefix, FieldLine},
            },
            varint::VarInt,
        };

        fn settings_pair(capacity: u32) -> Arc<Settings> {
            let mut settings = Settings::default();
            settings.set(crate::qpack::settings::QpackMaxTableCapacity::setting(
                VarInt::from_u32(capacity),
            ));
            settings.set(crate::qpack::settings::QpackBlockedStreams::setting(
                VarInt::from_u32(100),
            ));
            Arc::new(settings)
        }

        fn apply_instructions(encoder: &mut EncoderState, decoder: &mut DecoderState) {
            for instruction in encoder.pending_instructions() {
                match instruction {
                    EncoderInstruction::SetDynamicTableCapacity { capacity } => {
                        let _ = decoder.set_dynamic_table_capacity(*capacity);
                    }
                    EncoderInstruction::InsertWithNameReference {
                        is_static,
                        name_index,
                        value,
                        ..
                    } => {
                        let abs_index = if *is_static {
                            *name_index
                        } else {
                            decoder.table_inserted_count().wrapping_sub(name_index + 1)
                        };
                        let _ = decoder.insert_with_name_reference(
                            *is_static,
                            abs_index,
                            value.clone(),
                        );
                    }
                    EncoderInstruction::InsertWithLiteralName { name, value, .. } => {
                        let _ = decoder.insert_with_literal_name(name.clone(), value.clone());
                    }
                    EncoderInstruction::Duplicate { index } => {
                        let abs_index = decoder.table_inserted_count().wrapping_sub(index + 1);
                        let _ = decoder.duplicate(abs_index);
                    }
                }
            }
            // Simulate flush: clear processed instructions
            encoder.pending_instructions.clear();
        }

        #[test]
        fn apply_instructions_replays_all_encoder_instruction_variants() {
            let settings = settings_pair(4096);
            let mut encoder = EncoderState::new(settings.clone());
            encoder.set_max_table_capacity(4096).unwrap();
            encoder
                .insert_with_literal_name(
                    false,
                    Bytes::from_static(b"x-first"),
                    false,
                    Bytes::from_static(b"one"),
                )
                .unwrap();
            encoder
                .insert_with_name_reference(true, 1, false, Bytes::from_static(b"/custom"))
                .unwrap();
            encoder
                .insert_with_name_reference(false, 0, false, Bytes::from_static(b"two"))
                .unwrap();
            encoder.duplicate(0).unwrap();

            let mut decoder = DecoderState::new(settings);
            apply_instructions(&mut encoder, &mut decoder);

            assert_eq!(decoder.table_inserted_count(), 4);
            assert!(encoder.pending_instructions().is_empty());
        }

        fn verify_roundtrip(
            settings: &Settings,
            decoder: &DecoderState,
            output: &super::CompressOutput,
            original: &[FieldLine],
        ) {
            let max_table_capacity = settings.qpack_max_table_capacity().into_inner();
            let total_inserts = decoder.table_inserted_count();

            let required_insert_count = EncodedFieldSectionPrefix::decode_ric(
                output.prefix.encoded_insert_count,
                max_table_capacity,
                total_inserts,
            )
            .expect("decode_ric failed");

            let base = EncodedFieldSectionPrefix::resolve_base(
                required_insert_count,
                output.prefix.sign,
                output.prefix.delta_base,
            )
            .expect("resolve_base failed");

            let decoded: Vec<FieldLine> = output
                .representations
                .iter()
                .map(|repr| decoder.decompress(repr, base).expect("decompress failed"))
                .collect();

            assert_eq!(decoded.len(), original.len());
            for (orig, dec) in original.iter().zip(decoded.iter()) {
                assert_eq!(orig.name, dec.name);
                assert_eq!(orig.value, dec.value);
            }
        }

        fn arb_field_line() -> impl Strategy<Value = FieldLine> {
            (
                prop::collection::vec(prop::num::u8::ANY, 1..32),
                prop::collection::vec(prop::num::u8::ANY, 0..64),
            )
                .prop_map(|(name, value)| FieldLine {
                    name: Bytes::from(name),
                    value: Bytes::from(value),
                })
        }

        fn arb_field_section() -> impl Strategy<Value = Vec<FieldLine>> {
            prop::collection::vec(arb_field_line(), 1..8)
        }

        proptest! {
            #[test]
            fn single_section_roundtrip(field_lines in arb_field_section()) {
                let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
                rt.block_on(async {
                    let settings = settings_pair(4096);
                    let mut encoder = EncoderState::new(settings.clone());
                    encoder.set_max_table_capacity(4096).unwrap();
                    let mut decoder = DecoderState::new(settings.clone());
                    decoder.set_dynamic_table_capacity(4096).unwrap();

                    let algo = DynamicCompressAlgo::new(HuffmanNever);
                    let output = algo.compress(&mut encoder, field_lines.clone(), true).await;
                    apply_instructions(&mut encoder, &mut decoder);
                    verify_roundtrip(&settings, &decoder, &output, &field_lines);
                });
            }

            #[test]
            fn multi_section_roundtrip(
                sections in prop::collection::vec(arb_field_section(), 2..5),
            ) {
                let rt = tokio::runtime::Builder::new_current_thread().build().unwrap();
                rt.block_on(async {
                    let settings = settings_pair(4096);
                    let mut encoder = EncoderState::new(settings.clone());
                    encoder.set_max_table_capacity(4096).unwrap();
                    let mut decoder = DecoderState::new(settings.clone());
                    decoder.set_dynamic_table_capacity(4096).unwrap();

                    let algo = DynamicCompressAlgo::new(HuffmanNever);

                    for section in &sections {
                        let output = algo.compress(&mut encoder, section.clone(), true).await;
                        apply_instructions(&mut encoder, &mut decoder);
                        verify_roundtrip(&settings, &decoder, &output, section);
                    }
                });
            }
        }
    }
}