ntex 4.9.3

Framework for composable network services
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
//! `permessage-deflate` extension support (RFC 7692).
use std::{cell::Cell, cell::RefCell, fmt, fmt::Write};

use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status};

use crate::http::header::{HeaderMap, HeaderValue, SEC_WEBSOCKET_EXTENSIONS};
use crate::util::{BufMut, BytesMut};

use super::error::{ProtocolError, WsClientError};

const EXTENSION: &str = "permessage-deflate";
const CLIENT_NO_CONTEXT_TAKEOVER: &str = "client_no_context_takeover";
const SERVER_NO_CONTEXT_TAKEOVER: &str = "server_no_context_takeover";
const CLIENT_MAX_WINDOW_BITS: &str = "client_max_window_bits";
const SERVER_MAX_WINDOW_BITS: &str = "server_max_window_bits";

/// Trailer of a sync flush, removed from the end of each compressed message.
const TAIL: [u8; 4] = [0x00, 0x00, 0xff, 0xff];
const MIN_WINDOW_BITS: u8 = 8;
const MAX_WINDOW_BITS: u8 = 15;
/// Without context takeover, a compressed message of up to this size is
/// usually not smaller than the message, it is sent uncompressed.
const NO_CONTEXT_MAX_SKIPPED: usize = 32;

/// Parameters of the `permessage-deflate` extension (RFC 7692).
///
/// On the client, this value is the extension offer, set it with
/// [`WsClientConfig::set_deflate()`](super::WsClientConfig::set_deflate). The
/// parameters accepted by the server are available from
/// [`Codec::deflate()`](super::Codec::deflate) of the established connection.
///
/// On the server, this value holds the parameters the server accepts, see
/// [`DeflateConfig::negotiate()`]. The server uses at most the configured
/// window sizes, and asks the client to use the configured context takeover
/// and the client window size, if the client allows it.
///
/// A [`Codec`](super::Codec) applies the agreed parameters with
/// [`Codec::set_deflate()`](super::Codec::set_deflate).
///
/// Each connection allocates its own compressor and decompressor. With the
/// default window size and compression level the compressor uses about
/// 370KiB, and the decompressor about 46KiB.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DeflateConfig {
    level: u32,
    client_no_context_takeover: bool,
    server_no_context_takeover: bool,
    client_max_window_bits: Option<u8>,
    server_max_window_bits: Option<u8>,
}

impl Default for DeflateConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl DeflateConfig {
    #[must_use]
    /// Creates a configuration with the default compression level, 32KiB
    /// windows and context takeover in both directions.
    pub fn new() -> Self {
        Self {
            level: Compression::default().level(),
            client_no_context_takeover: false,
            server_no_context_takeover: false,
            client_max_window_bits: None,
            server_max_window_bits: None,
        }
    }

    #[must_use]
    /// Sets the compression level of outgoing messages, from 0 (no
    /// compression) to 9 (best compression).
    ///
    /// The default level is 6. Larger values are capped at 9.
    pub fn set_compression_level(mut self, level: u32) -> Self {
        self.level = level.min(9);
        self
    }

    #[must_use]
    /// Sets the `client_no_context_takeover` parameter.
    ///
    /// The client resets its compressor after each message. It uses less
    /// memory between messages, but repeated content compresses worse.
    pub fn set_client_no_context_takeover(mut self, value: bool) -> Self {
        self.client_no_context_takeover = value;
        self
    }

    #[must_use]
    /// Sets the `server_no_context_takeover` parameter.
    ///
    /// The client asks the server to reset its compressor after each
    /// message. A server that does not agree fails the connection.
    pub fn set_server_no_context_takeover(mut self, value: bool) -> Self {
        self.server_no_context_takeover = value;
        self
    }

    #[must_use]
    /// Sets the `client_max_window_bits` parameter, the base-2 logarithm of
    /// the client's LZ77 window size.
    ///
    /// Values are clamped to the 8 to 15 range, the default window is 15
    /// bits (32KiB). Smaller windows use less memory and compress worse.
    /// A client offers this parameter without a value by default, so the
    /// server can choose a smaller window.
    pub fn set_client_max_window_bits(mut self, bits: u8) -> Self {
        self.client_max_window_bits = Some(bits.clamp(MIN_WINDOW_BITS, MAX_WINDOW_BITS));
        self
    }

    #[must_use]
    /// Sets the `server_max_window_bits` parameter, the base-2 logarithm of
    /// the server's LZ77 window size.
    ///
    /// Values are clamped to the 8 to 15 range. The client asks the server to
    /// use at most this window size, a server that does not agree fails the
    /// connection. By default, the server chooses.
    pub fn set_server_max_window_bits(mut self, bits: u8) -> Self {
        self.server_max_window_bits = Some(bits.clamp(MIN_WINDOW_BITS, MAX_WINDOW_BITS));
        self
    }

    /// Returns the compression level of outgoing messages.
    pub fn compression_level(&self) -> u32 {
        self.level
    }

    /// Returns `true` if the client resets its compressor after each message.
    pub fn client_no_context_takeover(&self) -> bool {
        self.client_no_context_takeover
    }

    /// Returns `true` if the server resets its compressor after each message.
    pub fn server_no_context_takeover(&self) -> bool {
        self.server_no_context_takeover
    }

    /// Returns the client's LZ77 window size, if it is limited.
    pub fn client_max_window_bits(&self) -> Option<u8> {
        self.client_max_window_bits
    }

    /// Returns the server's LZ77 window size, if it is limited.
    pub fn server_max_window_bits(&self) -> Option<u8> {
        self.server_max_window_bits
    }

    /// Creates the `Sec-WebSocket-Extensions` value of a client offer.
    pub(super) fn offer(&self) -> HeaderValue {
        let mut offer = String::from(EXTENSION);
        if self.client_no_context_takeover {
            offer.push_str("; ");
            offer.push_str(CLIENT_NO_CONTEXT_TAKEOVER);
        }
        if self.server_no_context_takeover {
            offer.push_str("; ");
            offer.push_str(SERVER_NO_CONTEXT_TAKEOVER);
        }
        // offered without a value, the server may limit the client's window
        offer.push_str("; ");
        offer.push_str(CLIENT_MAX_WINDOW_BITS);
        if let Some(bits) = self.client_max_window_bits {
            let _ = write!(offer, "={bits}");
        }
        if let Some(bits) = self.server_max_window_bits {
            let _ = write!(offer, "; {SERVER_MAX_WINDOW_BITS}={bits}");
        }
        HeaderValue::try_from(offer).unwrap()
    }

    /// Validates the server's `Sec-WebSocket-Extensions` response to the
    /// offer, returns the agreed parameters.
    ///
    /// The server declines the offer by not including the extension.
    pub(super) fn accept(&self, headers: &HeaderMap) -> Result<Option<Self>, WsClientError> {
        let mut values = headers.get_all(SEC_WEBSOCKET_EXTENSIONS);
        let Some(value) = values.next() else {
            return Ok(None);
        };
        let invalid = || WsClientError::InvalidWebSocketExtensions(value.clone());

        // the client offers one extension, the server accepts it once
        if values.next().is_some() {
            return Err(invalid());
        }
        let value_str = value.to_str().map_err(|_| invalid())?;
        if value_str.contains(',') {
            return Err(invalid());
        }

        let mut params = value_str.split(';').map(str::trim);
        if !params
            .next()
            .is_some_and(|name| name.eq_ignore_ascii_case(EXTENSION))
        {
            return Err(WsClientError::UnexpectedWebSocketExtensions(value.clone()));
        }

        let mut agreed = DeflateConfig {
            level: self.level,
            // the client may skip context takeover even if the server allows it
            client_no_context_takeover: self.client_no_context_takeover,
            server_no_context_takeover: false,
            client_max_window_bits: self.client_max_window_bits,
            server_max_window_bits: None,
        };
        let (mut client_ctx, mut client_bits) = (false, false);
        for param in params {
            let (name, val) = match param.split_once('=') {
                Some((name, val)) => (name.trim(), Some(unquote(val.trim()).ok_or_else(invalid)?)),
                None => (param, None),
            };

            if name.eq_ignore_ascii_case(CLIENT_NO_CONTEXT_TAKEOVER) {
                if client_ctx || val.is_some() {
                    return Err(invalid());
                }
                client_ctx = true;
                agreed.client_no_context_takeover = true;
            } else if name.eq_ignore_ascii_case(SERVER_NO_CONTEXT_TAKEOVER) {
                if agreed.server_no_context_takeover || val.is_some() {
                    return Err(invalid());
                }
                agreed.server_no_context_takeover = true;
            } else if name.eq_ignore_ascii_case(CLIENT_MAX_WINDOW_BITS) {
                // always offered, the response must carry a value
                let bits = val.and_then(window_bits).ok_or_else(invalid)?;
                if client_bits {
                    return Err(invalid());
                }
                client_bits = true;
                agreed.client_max_window_bits =
                    Some(self.client_max_window_bits.map_or(bits, |b| b.min(bits)));
            } else if name.eq_ignore_ascii_case(SERVER_MAX_WINDOW_BITS) {
                let bits = val.and_then(window_bits).ok_or_else(invalid)?;
                if agreed.server_max_window_bits.is_some()
                    || self.server_max_window_bits.is_some_and(|max| bits > max)
                {
                    return Err(invalid());
                }
                agreed.server_max_window_bits = Some(bits);
            } else {
                return Err(invalid());
            }
        }

        // the server must accept the limits the client asked for
        if (self.server_no_context_takeover && !agreed.server_no_context_takeover)
            || (self.server_max_window_bits.is_some() && agreed.server_max_window_bits.is_none())
        {
            return Err(invalid());
        }
        Ok(Some(agreed))
    }

    #[must_use]
    /// Selects the client's offer of the extension for a server.
    ///
    /// The offers of the request's `Sec-WebSocket-Extensions` headers are
    /// checked in the client's order of preference, the first valid offer is
    /// accepted. Returns the agreed parameters and the
    /// `Sec-WebSocket-Extensions` value of the handshake response. Apply the
    /// parameters to the server's codec with
    /// [`Codec::set_deflate()`](super::Codec::set_deflate).
    ///
    /// Returns `None` if the client does not offer the extension, or all
    /// offers are invalid, the server then declines the extension.
    ///
    /// ```rust
    /// use ntex::http::header::{HeaderMap, HeaderValue, SEC_WEBSOCKET_EXTENSIONS};
    /// use ntex::ws::{self, DeflateConfig};
    ///
    /// let mut headers = HeaderMap::new();
    /// headers.insert(
    ///     SEC_WEBSOCKET_EXTENSIONS,
    ///     HeaderValue::from_static("permessage-deflate; client_max_window_bits"),
    /// );
    ///
    /// let mut codec = ws::Codec::new();
    /// let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
    /// if let Some((agreed, response)) = cfg.negotiate(&headers) {
    ///     assert_eq!(response, "permessage-deflate; server_no_context_takeover");
    ///     codec = codec.set_deflate(agreed);
    /// }
    /// ```
    pub fn negotiate(&self, headers: &HeaderMap) -> Option<(Self, HeaderValue)> {
        let agreed = headers
            .get_all(SEC_WEBSOCKET_EXTENSIONS)
            .filter_map(|value| value.to_str().ok())
            .flat_map(|value| value.split(','))
            .find_map(|offer| self.negotiate_offer(offer))?;
        let response = agreed.response();
        Some((agreed, response))
    }

    /// Returns the agreed parameters of an offer, `None` if the offer is
    /// declined.
    ///
    /// An offer with unknown, duplicated or invalid parameters is declined
    /// (RFC 7692 §7).
    fn negotiate_offer(&self, offer: &str) -> Option<Self> {
        let mut params = offer.split(';').map(str::trim);
        if !params
            .next()
            .is_some_and(|name| name.eq_ignore_ascii_case(EXTENSION))
        {
            return None;
        }

        let mut agreed = DeflateConfig {
            level: self.level,
            client_no_context_takeover: self.client_no_context_takeover,
            server_no_context_takeover: self.server_no_context_takeover,
            // the client's window is limited only if the client allows it
            client_max_window_bits: None,
            server_max_window_bits: self.server_max_window_bits,
        };
        let (mut client_ctx, mut server_ctx) = (false, false);
        let (mut client_bits, mut server_bits) = (false, false);
        for param in params {
            let (name, val) = match param.split_once('=') {
                Some((name, val)) => (name.trim(), Some(unquote(val.trim())?)),
                None => (param, None),
            };

            if name.eq_ignore_ascii_case(CLIENT_NO_CONTEXT_TAKEOVER) {
                if client_ctx || val.is_some() {
                    return None;
                }
                client_ctx = true;
                agreed.client_no_context_takeover = true;
            } else if name.eq_ignore_ascii_case(SERVER_NO_CONTEXT_TAKEOVER) {
                if server_ctx || val.is_some() {
                    return None;
                }
                server_ctx = true;
                agreed.server_no_context_takeover = true;
            } else if name.eq_ignore_ascii_case(CLIENT_MAX_WINDOW_BITS) {
                if client_bits {
                    return None;
                }
                client_bits = true;
                // the value is optional in an offer
                agreed.client_max_window_bits = match val {
                    Some(val) => {
                        let bits = window_bits(val)?;
                        Some(
                            self.client_max_window_bits
                                .map_or(bits, |max| max.min(bits)),
                        )
                    }
                    None => self.client_max_window_bits,
                };
            } else if name.eq_ignore_ascii_case(SERVER_MAX_WINDOW_BITS) {
                let bits = val.and_then(window_bits)?;
                if server_bits {
                    return None;
                }
                server_bits = true;
                agreed.server_max_window_bits = Some(
                    self.server_max_window_bits
                        .map_or(bits, |max| max.min(bits)),
                );
            } else {
                return None;
            }
        }
        Some(agreed)
    }

    /// Creates the `Sec-WebSocket-Extensions` value of a server response
    /// with the agreed parameters.
    fn response(&self) -> HeaderValue {
        let mut response = String::from(EXTENSION);
        if self.client_no_context_takeover {
            response.push_str("; ");
            response.push_str(CLIENT_NO_CONTEXT_TAKEOVER);
        }
        if self.server_no_context_takeover {
            response.push_str("; ");
            response.push_str(SERVER_NO_CONTEXT_TAKEOVER);
        }
        if let Some(bits) = self.client_max_window_bits {
            let _ = write!(response, "; {CLIENT_MAX_WINDOW_BITS}={bits}");
        }
        if let Some(bits) = self.server_max_window_bits {
            let _ = write!(response, "; {SERVER_MAX_WINDOW_BITS}={bits}");
        }
        HeaderValue::try_from(response).unwrap()
    }
}

/// Removes the quotes of a quoted-string parameter value.
fn unquote(val: &str) -> Option<&str> {
    match val.strip_prefix('"') {
        Some(val) => val
            .strip_suffix('"')
            .filter(|val| !val.contains(['"', '\\'])),
        None => Some(val),
    }
}

/// Parses a window size, an integer from 8 to 15 without leading zeros.
fn window_bits(val: &str) -> Option<u8> {
    if val.starts_with('0') || !val.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    val.parse::<u8>()
        .ok()
        .filter(|bits| (MIN_WINDOW_BITS..=MAX_WINDOW_BITS).contains(bits))
}

/// Compression state of a connection, shared by the clones of a codec.
pub(super) struct Deflate {
    cfg: DeflateConfig,
    compress: RefCell<Option<Compress>>,
    decompress: RefCell<Option<Decompress>>,
    /// The incoming message has compressed data.
    has_data: Cell<bool>,
}

impl fmt::Debug for Deflate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Deflate").field("cfg", &self.cfg).finish()
    }
}

impl Deflate {
    pub(super) fn new(cfg: DeflateConfig) -> Self {
        Self {
            cfg,
            compress: RefCell::new(None),
            decompress: RefCell::new(None),
            has_data: Cell::new(false),
        }
    }

    pub(super) fn config(&self) -> &DeflateConfig {
        &self.cfg
    }

    /// Returns `true` if an unfragmented message of `len` bytes is sent
    /// uncompressed.
    ///
    /// Without context takeover, the compressor is reset after each message,
    /// which costs more than compressing a small message, and the result is
    /// not smaller.
    pub(super) fn is_skipped(&self, len: usize, server: bool) -> bool {
        len <= NO_CONTEXT_MAX_SKIPPED && self.no_context_takeover(server)
    }

    /// Compresses a fragment of an outgoing message.
    ///
    /// The trailer of the last fragment is removed, the compressor is reset
    /// after it if this side does not use context takeover.
    pub(super) fn compress(&self, data: &[u8], fin: bool, server: bool) -> BytesMut {
        let mut compress = self.compress.borrow_mut();
        let compress = compress.get_or_insert_with(|| {
            let bits = if server {
                self.cfg.server_max_window_bits
            } else {
                self.cfg.client_max_window_bits
            }
            .unwrap_or(MAX_WINDOW_BITS);

            // The 8-bit window is not supported by zlib, stored blocks do
            // not refer to previous data and fit any window.
            let level = if bits == MIN_WINDOW_BITS {
                Compression::none()
            } else {
                Compression::new(self.cfg.level)
            };
            Compress::new_with_window_bits(level, false, bits.max(MIN_WINDOW_BITS + 1))
        });

        let mut out = BytesMut::with_capacity(data.len() / 2 + 64);
        let mut data = data;
        loop {
            let (total_in, total_out) = (compress.total_in(), compress.total_out());
            // SAFETY: the compressor only writes to the slice, and
            // `advance_mut` covers just the bytes it has written
            unsafe {
                compress
                    .compress_uninit(
                        data,
                        out.chunk_mut().as_uninit_slice_mut(),
                        FlushCompress::Sync,
                    )
                    .expect("deflate stream is valid");
                out.advance_mut(usize::try_from(compress.total_out() - total_out).unwrap());
            }
            data = &data[usize::try_from(compress.total_in() - total_in).unwrap()..];

            // the flush is complete once it leaves space in the buffer
            if data.is_empty() && out.remaining_mut() > 0 {
                break;
            }
            out.reserve(out.capacity().max(64));
        }

        if fin {
            if out.ends_with(&TAIL) {
                out.truncate(out.len() - TAIL.len());
            } else if out.is_empty() {
                // Nothing is written after a previous flush. With the
                // trailer, a single zero byte is an empty stored block.
                out.put_u8(0x00);
            }
            if self.no_context_takeover(server) {
                compress.reset();
            }
        }
        out
    }

    /// Decompresses a fragment of an incoming message, the output is limited
    /// to `max_size` bytes.
    pub(super) fn decompress(
        &self,
        data: &[u8],
        fin: bool,
        server: bool,
        max_size: usize,
    ) -> Result<BytesMut, ProtocolError> {
        let mut decompress = self.decompress.borrow_mut();
        // a smaller window of the peer fits the maximum window
        let decompress = decompress.get_or_insert_with(|| Decompress::new(false));

        // The trailer is the length of an empty stored block, the block
        // header ends the compressed data. A message without compressed data
        // has no block header, the peer did not write the empty block.
        let has_data = self.has_data.get() || !data.is_empty();
        self.has_data.set(has_data && !fin);

        let mut out =
            BytesMut::with_capacity((data.len() * 2 + 64).min(max_size.saturating_add(1)));
        let result = inflate(decompress, data, &mut out, max_size).and_then(|()| {
            if fin && has_data {
                inflate(decompress, &TAIL, &mut out, max_size)
            } else {
                Ok(())
            }
        });
        if result.is_err() {
            self.has_data.set(false);
            decompress.reset(false);
            return result.map(|()| out);
        }

        if fin && self.no_context_takeover(!server) {
            decompress.reset(false);
        }
        Ok(out)
    }

    fn no_context_takeover(&self, server: bool) -> bool {
        if server {
            self.cfg.server_no_context_takeover
        } else {
            self.cfg.client_no_context_takeover
        }
    }
}

fn inflate(
    decompress: &mut Decompress,
    mut data: &[u8],
    out: &mut BytesMut,
    max_size: usize,
) -> Result<(), ProtocolError> {
    loop {
        if out.remaining_mut() == 0 {
            if out.len() > max_size {
                return Err(ProtocolError::Overflow);
            }
            out.reserve_exact(out.capacity().max(64).min(max_size + 1 - out.len()));
        }

        let (total_in, total_out) = (decompress.total_in(), decompress.total_out());
        // SAFETY: the decompressor only writes to the slice, and
        // `advance_mut` covers just the bytes it has written
        let status = unsafe {
            let status = decompress
                .decompress_uninit(
                    data,
                    out.chunk_mut().as_uninit_slice_mut(),
                    FlushDecompress::Sync,
                )
                .map_err(|_| ProtocolError::InvalidCompressedData)?;
            out.advance_mut(usize::try_from(decompress.total_out() - total_out).unwrap());
            status
        };
        let read = usize::try_from(decompress.total_in() - total_in).unwrap();
        let written = decompress.total_out() - total_out;
        data = &data[read..];

        if out.len() > max_size {
            return Err(ProtocolError::Overflow);
        }
        if status == Status::StreamEnd {
            // a block with BFINAL set ends the stream, the peer starts a new
            // one with an empty window
            decompress.reset(false);
            if data.is_empty() {
                return Ok(());
            }
        } else if out.remaining_mut() > 0 {
            // all output is written once it leaves space in the buffer
            if data.is_empty() {
                return Ok(());
            } else if read == 0 && written == 0 {
                return Err(ProtocolError::InvalidCompressedData);
            }
        }
    }
}

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

    fn response(values: &[&'static str]) -> HeaderMap {
        let mut headers = HeaderMap::new();
        for value in values {
            headers.append(SEC_WEBSOCKET_EXTENSIONS, HeaderValue::from_static(value));
        }
        headers
    }

    fn accept(
        offer: &DeflateConfig,
        value: &'static str,
    ) -> Result<Option<DeflateConfig>, WsClientError> {
        offer.accept(&response(&[value]))
    }

    fn invalid(offer: &DeflateConfig, value: &'static str) -> bool {
        matches!(
            accept(offer, value),
            Err(WsClientError::InvalidWebSocketExtensions(val)) if val == value
        )
    }

    /// STATEMENT: Deflate configuration exposes defaults and clamps compression/window settings to supported ranges.
    ///
    /// HOW:
    /// - Inspect defaults, apply out-of-range levels/windows and takeover flags, then compare normalized values and debug output.
    #[test]
    fn config() {
        let cfg = DeflateConfig::default();
        assert_eq!(cfg, DeflateConfig::new());
        assert_eq!(cfg.compression_level(), 6);
        assert!(!cfg.client_no_context_takeover());
        assert!(!cfg.server_no_context_takeover());
        assert_eq!(cfg.client_max_window_bits(), None);
        assert_eq!(cfg.server_max_window_bits(), None);

        let cfg = cfg
            .set_compression_level(10)
            .set_client_no_context_takeover(true)
            .set_server_no_context_takeover(true)
            .set_client_max_window_bits(7)
            .set_server_max_window_bits(16);
        assert_eq!(cfg.compression_level(), 9);
        assert!(cfg.client_no_context_takeover());
        assert!(cfg.server_no_context_takeover());
        assert_eq!(cfg.client_max_window_bits(), Some(8));
        assert_eq!(cfg.server_max_window_bits(), Some(15));
        assert!(format!("{:?}", Deflate::new(cfg)).contains("Deflate"));
    }

    /// STATEMENT: Deflate offers serialize default capabilities and explicit takeover/window constraints.
    ///
    /// HOW:
    /// - Compare complete extension header strings for default and fully configured offers.
    #[test]
    fn offer() {
        assert_eq!(
            DeflateConfig::new().offer(),
            "permessage-deflate; client_max_window_bits"
        );
        assert_eq!(
            DeflateConfig::new()
                .set_client_no_context_takeover(true)
                .set_server_no_context_takeover(true)
                .set_client_max_window_bits(10)
                .set_server_max_window_bits(12)
                .offer(),
            "permessage-deflate; client_no_context_takeover; server_no_context_takeover; \
             client_max_window_bits=10; server_max_window_bits=12"
        );
    }

    /// STATEMENT: An absent extension response declines a deflate offer without error.
    ///
    /// HOW:
    /// - Accept an empty response header map and verify no compression configuration is negotiated.
    #[test]
    fn accept_declined() {
        let offer = DeflateConfig::new();
        assert_eq!(offer.accept(&HeaderMap::new()).unwrap(), None);
    }

    /// STATEMENT: Deflate negotiation parses permitted syntax while preserving stricter local limits.
    ///
    /// HOW:
    /// - Accept case/spacing/quoting variants and compare takeover flags, windows, and retained compression level.
    /// - Negotiate relaxed client and constrained server windows and verify the resulting limits.
    #[test]
    fn accept_params() {
        let offer = DeflateConfig::new().set_compression_level(1);
        let agreed = accept(&offer, "permessage-deflate").unwrap().unwrap();
        assert_eq!(agreed, offer);

        let agreed = accept(
            &offer,
            "Permessage-Deflate ; Client_No_Context_Takeover;server_no_context_takeover ; \
             client_max_window_bits = 10; server_max_window_bits=\"9\"",
        )
        .unwrap()
        .unwrap();
        assert_eq!(agreed.compression_level(), 1);
        assert!(agreed.client_no_context_takeover());
        assert!(agreed.server_no_context_takeover());
        assert_eq!(agreed.client_max_window_bits(), Some(10));
        assert_eq!(agreed.server_max_window_bits(), Some(9));

        // the client keeps its own limits
        let offer = DeflateConfig::new()
            .set_client_no_context_takeover(true)
            .set_client_max_window_bits(9);
        let agreed = accept(&offer, "permessage-deflate; client_max_window_bits=12")
            .unwrap()
            .unwrap();
        assert!(agreed.client_no_context_takeover());
        assert_eq!(agreed.client_max_window_bits(), Some(9));
        let agreed = accept(&offer, "permessage-deflate").unwrap().unwrap();
        assert_eq!(agreed.client_max_window_bits(), Some(9));

        // the server accepts the client's limits
        let offer = DeflateConfig::new()
            .set_server_no_context_takeover(true)
            .set_server_max_window_bits(10);
        let agreed = accept(
            &offer,
            "permessage-deflate; server_no_context_takeover; server_max_window_bits=8",
        )
        .unwrap()
        .unwrap();
        assert!(agreed.server_no_context_takeover());
        assert_eq!(agreed.server_max_window_bits(), Some(8));
        let agreed = accept(
            &offer,
            "permessage-deflate; server_no_context_takeover; server_max_window_bits=10",
        )
        .unwrap()
        .unwrap();
        assert_eq!(agreed.server_max_window_bits(), Some(10));
    }

    /// STATEMENT: Deflate negotiation rejects unoffered extensions, malformed or repeated parameters, and unmet server constraints.
    ///
    /// HOW:
    /// - Exercise invalid extension names, duplicate offers, parameter syntax/window bounds, and missing requested limits.
    /// - Check unexpected/invalid extension errors, including repeated and non-text headers.
    #[test]
    fn accept_errors() {
        let offer = DeflateConfig::new();

        // other extensions are not offered
        for value in ["x-webkit-deflate-frame", "permessage-deflate-x", ""] {
            assert!(matches!(
                accept(&offer, value),
                Err(WsClientError::UnexpectedWebSocketExtensions(val)) if val == value
            ));
        }

        for value in [
            // more than one extension
            "permessage-deflate, permessage-deflate",
            "permessage-deflate, x-ext",
            // unknown or malformed parameters
            "permessage-deflate; unknown",
            "permessage-deflate; unknown=1",
            "permessage-deflate;",
            "permessage-deflate; client_no_context_takeover=1",
            "permessage-deflate; server_no_context_takeover=\"\"",
            // duplicated parameters
            "permessage-deflate; client_no_context_takeover; client_no_context_takeover",
            "permessage-deflate; server_no_context_takeover; server_no_context_takeover",
            "permessage-deflate; client_max_window_bits=10; client_max_window_bits=10",
            "permessage-deflate; server_max_window_bits=10; server_max_window_bits=10",
            // invalid window sizes
            "permessage-deflate; client_max_window_bits",
            "permessage-deflate; server_max_window_bits",
            "permessage-deflate; client_max_window_bits=7",
            "permessage-deflate; client_max_window_bits=16",
            "permessage-deflate; server_max_window_bits=09",
            "permessage-deflate; server_max_window_bits=+9",
            "permessage-deflate; server_max_window_bits=1x",
            "permessage-deflate; server_max_window_bits=256",
            "permessage-deflate; server_max_window_bits=\"10",
            "permessage-deflate; server_max_window_bits=\"1\\0\"",
        ] {
            assert!(invalid(&offer, value), "{value}");
        }

        // the server must accept the requested limits
        let offer = DeflateConfig::new()
            .set_server_no_context_takeover(true)
            .set_server_max_window_bits(10);
        for value in [
            "permessage-deflate; server_max_window_bits=10",
            "permessage-deflate; server_no_context_takeover",
            "permessage-deflate; server_no_context_takeover; server_max_window_bits=11",
        ] {
            assert!(invalid(&offer, value), "{value}");
        }

        // the extension is accepted once
        let headers = response(&["permessage-deflate", "permessage-deflate"]);
        assert!(matches!(
            offer.accept(&headers),
            Err(WsClientError::InvalidWebSocketExtensions(_))
        ));
        let mut headers = HeaderMap::new();
        headers.insert(
            SEC_WEBSOCKET_EXTENSIONS,
            HeaderValue::from_bytes(b"permessage-deflate; \xff").unwrap(),
        );
        assert!(matches!(
            offer.accept(&headers),
            Err(WsClientError::InvalidWebSocketExtensions(_))
        ));
    }

    fn negotiate(cfg: &DeflateConfig, values: &[&'static str]) -> Option<(DeflateConfig, String)> {
        cfg.negotiate(&response(values))
            .map(|(agreed, res)| (agreed, res.to_str().unwrap().to_owned()))
    }

    /// STATEMENT: A server declines the extension when no valid deflate offer is present.
    ///
    /// HOW:
    /// - Negotiate without an extension header, with other extensions, and with non-text headers.
    /// - Negotiate offers with unknown, malformed, duplicated, or out-of-range parameters and assert each is declined.
    #[test]
    fn negotiate_declined() {
        let cfg = DeflateConfig::new();
        assert_eq!(cfg.negotiate(&HeaderMap::new()), None);
        assert_eq!(negotiate(&cfg, &["x-webkit-deflate-frame"]), None);
        assert_eq!(negotiate(&cfg, &["permessage-deflate-x, x-ext"]), None);
        assert_eq!(negotiate(&cfg, &[""]), None);

        let mut headers = HeaderMap::new();
        headers.insert(
            SEC_WEBSOCKET_EXTENSIONS,
            HeaderValue::from_bytes(b"permessage-deflate; \xff").unwrap(),
        );
        assert_eq!(cfg.negotiate(&headers), None);

        for value in [
            // unknown or malformed parameters
            "permessage-deflate; unknown",
            "permessage-deflate; unknown=1",
            "permessage-deflate;",
            "permessage-deflate; client_no_context_takeover=1",
            "permessage-deflate; server_no_context_takeover=\"\"",
            // duplicated parameters
            "permessage-deflate; client_no_context_takeover; client_no_context_takeover",
            "permessage-deflate; server_no_context_takeover; server_no_context_takeover",
            "permessage-deflate; client_max_window_bits; client_max_window_bits",
            "permessage-deflate; client_max_window_bits=10; client_max_window_bits=10",
            "permessage-deflate; server_max_window_bits=10; server_max_window_bits=10",
            // invalid window sizes
            "permessage-deflate; server_max_window_bits",
            "permessage-deflate; client_max_window_bits=7",
            "permessage-deflate; client_max_window_bits=16",
            "permessage-deflate; server_max_window_bits=09",
            "permessage-deflate; server_max_window_bits=+9",
            "permessage-deflate; server_max_window_bits=256",
            "permessage-deflate; server_max_window_bits=\"10",
        ] {
            assert_eq!(negotiate(&cfg, &[value]), None, "{value}");
        }
    }

    /// STATEMENT: A server accepts the client's limits, applies its own limits, and answers with the agreed parameters.
    ///
    /// HOW:
    /// - Negotiate plain, case/spacing/quoting variants and requested limits; compare agreed configs and response headers.
    /// - Negotiate with server limits, with and without client window offers, and check the smaller window wins.
    #[test]
    fn negotiate_params() {
        let cfg = DeflateConfig::new().set_compression_level(1);
        assert_eq!(
            negotiate(&cfg, &["permessage-deflate"]),
            Some((cfg.clone(), "permessage-deflate".to_owned()))
        );
        // the client's window is not limited without a value
        assert_eq!(
            negotiate(&cfg, &["permessage-deflate; client_max_window_bits"]),
            Some((cfg.clone(), "permessage-deflate".to_owned()))
        );

        let (agreed, res) = negotiate(
            &cfg,
            &[
                "Permessage-Deflate ; Client_No_Context_Takeover;server_no_context_takeover ; \
               client_max_window_bits = 10; server_max_window_bits=\"9\"",
            ],
        )
        .unwrap();
        assert_eq!(agreed.compression_level(), 1);
        assert!(agreed.client_no_context_takeover());
        assert!(agreed.server_no_context_takeover());
        assert_eq!(agreed.client_max_window_bits(), Some(10));
        assert_eq!(agreed.server_max_window_bits(), Some(9));
        assert_eq!(
            res,
            "permessage-deflate; client_no_context_takeover; server_no_context_takeover; \
             client_max_window_bits=10; server_max_window_bits=9"
        );

        // the server applies its own limits
        let cfg = DeflateConfig::new()
            .set_client_no_context_takeover(true)
            .set_server_no_context_takeover(true)
            .set_client_max_window_bits(10)
            .set_server_max_window_bits(11);
        let (agreed, res) = negotiate(&cfg, &["permessage-deflate"]).unwrap();
        assert_eq!(agreed.client_max_window_bits(), None);
        assert_eq!(agreed.server_max_window_bits(), Some(11));
        assert_eq!(
            res,
            "permessage-deflate; client_no_context_takeover; server_no_context_takeover; \
             server_max_window_bits=11"
        );
        let (agreed, _) = negotiate(&cfg, &["permessage-deflate; client_max_window_bits"]).unwrap();
        assert_eq!(agreed.client_max_window_bits(), Some(10));
        let (agreed, _) = negotiate(
            &cfg,
            &["permessage-deflate; client_max_window_bits=12; server_max_window_bits=12"],
        )
        .unwrap();
        assert_eq!(agreed.client_max_window_bits(), Some(10));
        assert_eq!(agreed.server_max_window_bits(), Some(11));
        let (agreed, _) = negotiate(
            &cfg,
            &["permessage-deflate; client_max_window_bits=9; server_max_window_bits=8"],
        )
        .unwrap();
        assert_eq!(agreed.client_max_window_bits(), Some(9));
        assert_eq!(agreed.server_max_window_bits(), Some(8));
    }

    /// STATEMENT: A server accepts the first valid deflate offer in the client's order of preference.
    ///
    /// HOW:
    /// - Negotiate comma-separated and repeated headers where earlier offers are invalid or other extensions.
    /// - Assert the first valid deflate offer is the agreed one.
    #[test]
    fn negotiate_offers() {
        let cfg = DeflateConfig::new();
        let (agreed, res) = negotiate(
            &cfg,
            &["x-ext, permessage-deflate; unknown, permessage-deflate; server_max_window_bits=10, \
               permessage-deflate"],
        )
        .unwrap();
        assert_eq!(agreed.server_max_window_bits(), Some(10));
        assert_eq!(res, "permessage-deflate; server_max_window_bits=10");

        let (agreed, _) = negotiate(
            &cfg,
            &[
                "permessage-deflate; client_max_window_bits=7",
                "permessage-deflate; server_no_context_takeover",
            ],
        )
        .unwrap();
        assert!(agreed.server_no_context_takeover());
    }

    /// STATEMENT: A client accepts the server's response to its offer with the same agreed parameters.
    ///
    /// HOW:
    /// - Negotiate client offers with server configs and pass the response to the client's `accept`.
    /// - Compare the agreed parameters of both sides, apart from the local compression level.
    #[test]
    fn negotiate_accept() {
        let offers = [
            DeflateConfig::new(),
            DeflateConfig::new()
                .set_client_no_context_takeover(true)
                .set_client_max_window_bits(9),
            DeflateConfig::new()
                .set_server_no_context_takeover(true)
                .set_server_max_window_bits(12),
        ];
        let servers = [
            DeflateConfig::new(),
            DeflateConfig::new()
                .set_client_no_context_takeover(true)
                .set_server_no_context_takeover(true)
                .set_client_max_window_bits(10)
                .set_server_max_window_bits(10),
        ];
        for offer in &offers {
            for server in &servers {
                let mut headers = HeaderMap::new();
                headers.insert(SEC_WEBSOCKET_EXTENSIONS, offer.offer());
                let (agreed, res) = server.negotiate(&headers).unwrap();

                let mut headers = HeaderMap::new();
                headers.insert(SEC_WEBSOCKET_EXTENSIONS, res);
                let client = offer.accept(&headers).unwrap().unwrap();
                assert_eq!(
                    client,
                    agreed.set_compression_level(offer.compression_level()),
                    "{offer:?} {server:?}"
                );
            }
        }
    }

    /// STATEMENT: Deflate round trips preserve payloads, reuse history, omit final trailers, and enforce expanded-size bounds.
    ///
    /// HOW:
    /// - Compress repeated, empty, and large incompressible messages and compare decoded bytes.
    /// - Inspect compression/trailer behavior and reject a limit one byte below the expanded payload.
    #[test]
    fn compress_roundtrip() {
        let server = Deflate::new(DeflateConfig::new());
        let client = Deflate::new(DeflateConfig::new());

        let msg = b"Hello, Hello, Hello, Hello";
        let first = server.compress(msg, true, true);
        assert!(first.len() < msg.len());
        assert!(!first.ends_with(&TAIL));
        assert_eq!(client.decompress(&first, true, false, 1024).unwrap(), msg);

        // the second message refers to the first one
        let second = server.compress(msg, true, true);
        assert!(second.len() < first.len());
        assert_eq!(client.decompress(&second, true, false, 1024).unwrap(), msg);

        // empty and incompressible messages
        let empty = server.compress(b"", true, true);
        assert_eq!(client.decompress(&empty, true, false, 1024).unwrap(), b"");
        let data: Vec<u8> = (0..200_000u32)
            .map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8)
            .collect();
        let compressed = server.compress(&data, true, true);
        assert_eq!(
            client
                .decompress(&compressed, true, false, data.len())
                .unwrap(),
            data
        );
        assert!(matches!(
            client.decompress(
                &server.compress(&data, true, true),
                true,
                false,
                data.len() - 1
            ),
            Err(ProtocolError::Overflow)
        ));
    }

    /// STATEMENT: Fragment compression retains intermediate flush trailers and supports empty intermediate or final fragments.
    ///
    /// HOW:
    /// - Compress/decompress fragment sequences with empty pieces and inspect trailer presence.
    /// - Compare reassembled messages and verify the next message still decodes correctly.
    #[test]
    fn compress_fragments() {
        let server = Deflate::new(DeflateConfig::new());
        let client = Deflate::new(DeflateConfig::new());

        let mut out = Vec::new();
        for (data, fin) in [(&b"Hello, "[..], false), (b"", false), (b"Hello", true)] {
            let compressed = server.compress(data, fin, true);
            // only the end of the message drops the trailer, an empty
            // fragment is empty after a flush
            assert_eq!(compressed.ends_with(&TAIL), !fin && !data.is_empty());
            assert_eq!(compressed.is_empty(), data.is_empty());
            out.extend(client.decompress(&compressed, fin, false, 1024).unwrap());
        }
        assert_eq!(out, b"Hello, Hello");

        // the last fragment is empty
        let mut out = Vec::new();
        for (data, fin) in [(&b"Hello"[..], false), (b"", true)] {
            let compressed = server.compress(data, fin, true);
            out.extend(client.decompress(&compressed, fin, false, 1024).unwrap());
        }
        assert_eq!(out, b"Hello");
        let compressed = server.compress(b"Hello", true, true);
        assert_eq!(
            client.decompress(&compressed, true, false, 1024).unwrap(),
            b"Hello"
        );
    }

    /// STATEMENT: Empty last fragments finalize compressed messages without disturbing subsequent context reuse.
    ///
    /// HOW:
    /// - Decode repeated payloads split into seven-byte pieces plus empty finals.
    /// - Decode a wholly empty fragmented message and then a nonempty message, comparing all output.
    #[test]
    fn empty_last_fragment() {
        // a compressed payload split into fragments, the last one is empty
        let server = Deflate::new(DeflateConfig::new());
        let client = Deflate::new(DeflateConfig::new());
        for _ in 0..3 {
            let compressed = server.compress(&b"Hello, Hello, Hello".repeat(50), true, true);
            let mut out = Vec::new();
            for chunk in compressed.chunks(7) {
                out.extend(client.decompress(chunk, false, false, 4096).unwrap());
            }
            out.extend(client.decompress(&[], true, false, 4096).unwrap());
            assert_eq!(out, b"Hello, Hello, Hello".repeat(50));
        }

        // a message without compressed data
        assert_eq!(client.decompress(&[], false, false, 4096).unwrap(), b"");
        assert_eq!(client.decompress(&[], true, false, 4096).unwrap(), b"");
        let compressed = server.compress(b"Hello", true, true);
        assert_eq!(
            client.decompress(&compressed, true, false, 4096).unwrap(),
            b"Hello"
        );
    }

    /// STATEMENT: Empty compressed messages use the RFC representation and do not consume following messages.
    ///
    /// HOW:
    /// - Compare repeated empty encodings with a zero byte and interleave empty/nonempty decoding.
    /// - Accept both encoded-empty and zero-length peer payloads without losing later data.
    #[test]
    fn empty_messages() {
        let server = Deflate::new(DeflateConfig::new());
        let client = Deflate::new(DeflateConfig::new());

        // RFC 7692 7.2.3.6, an empty message is a single zero byte
        assert_eq!(server.compress(b"", true, true), [0x00]);
        assert_eq!(server.compress(b"", true, true), [0x00]);
        let compressed = server.compress(b"Hello", true, true);
        assert_eq!(server.compress(b"", true, true), [0x00]);
        assert_eq!(server.compress(b"", true, true), [0x00]);

        for _ in 0..2 {
            assert_eq!(client.decompress(&[0x00], true, false, 1024).unwrap(), b"");
        }
        assert_eq!(
            client.decompress(&compressed, true, false, 1024).unwrap(),
            b"Hello"
        );
        // an empty payload from the peer does not consume the next message
        for _ in 0..2 {
            assert_eq!(client.decompress(&[], true, false, 1024).unwrap(), b"");
        }
        let compressed = server.compress(b"Hello", true, true);
        assert_eq!(
            client.decompress(&compressed, true, false, 1024).unwrap(),
            b"Hello"
        );
    }

    /// STATEMENT: Disabling server context takeover resets server compression and peer decompression, but not client compression.
    ///
    /// HOW:
    /// - Compare repeated server encodings and decode both, then verify repeated client encodings differ through history reuse.
    #[test]
    fn no_context_takeover() {
        let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
        let server = Deflate::new(cfg.clone());
        let client = Deflate::new(cfg);

        // the server resets its compressor, and the client its decompressor
        let first = server.compress(b"Hello", true, true);
        assert_eq!(server.compress(b"Hello", true, true), first);
        assert_eq!(
            client.decompress(&first, true, false, 1024).unwrap(),
            b"Hello"
        );
        assert_eq!(
            client.decompress(&first, true, false, 1024).unwrap(),
            b"Hello"
        );

        // the client keeps its context
        let first = client.compress(b"Hello", true, false);
        assert_ne!(client.compress(b"Hello", true, false), first);
    }

    /// STATEMENT: Negotiated window sizes round-trip data, including stored-block fallback for the smallest window.
    ///
    /// HOW:
    /// - Compress and decompress repeated large payloads for every supported window size.
    /// - Verify only the eight-bit-window encoding expands beyond the input length.
    #[test]
    fn window_bits() {
        let data: Vec<u8> = b"0123456789abcdef".repeat(4096);
        for bits in 8..=15 {
            let cfg = DeflateConfig::new()
                .set_client_max_window_bits(bits)
                .set_server_max_window_bits(bits);
            let server = Deflate::new(cfg.clone());
            let client = Deflate::new(cfg);
            for _ in 0..2 {
                let compressed = client.compress(&data, true, false);
                // stored blocks only, they fit the 8-bit window
                assert_eq!(compressed.len() > data.len(), bits == 8, "{bits}");
                assert_eq!(
                    server
                        .decompress(&compressed, true, true, data.len())
                        .unwrap(),
                    data
                );
            }
        }
    }

    /// STATEMENT: Invalid deflate blocks and impossible back-references fail, and a failed decoder can accept a fresh stream.
    ///
    /// HOW:
    /// - Reject a reserved block type, decode a valid message afterward, and separately reject a reference before stream start.
    #[test]
    fn invalid_data() {
        let client = Deflate::new(DeflateConfig::new());
        // a reserved block type
        assert!(matches!(
            client.decompress(&[0xff, 0xff], true, false, 1024),
            Err(ProtocolError::InvalidCompressedData)
        ));
        // the decompressor is reset after an error
        assert_eq!(
            client
                .decompress(
                    &[0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00],
                    true,
                    false,
                    1024
                )
                .unwrap(),
            b"Hello"
        );
        // a distance beyond the start of the stream
        let client = Deflate::new(DeflateConfig::new());
        assert!(matches!(
            client.decompress(&[0xf2, 0x00, 0x11, 0x00, 0x00], true, false, 1024),
            Err(ProtocolError::InvalidCompressedData)
        ));
    }
}