ntex 4.7.1

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
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
use std::cell::Cell;
#[cfg(feature = "compress")]
use std::rc::Rc;

use crate::codec::{Decoder, Encoder};
use crate::util::{BytePage, BytePages, ByteString, Bytes, BytesMut};

#[cfg(feature = "compress")]
use super::deflate::{Deflate, DeflateConfig};
use super::error::ProtocolError;
use super::frame::Parser;
use super::proto::{CloseCode, CloseReason, OpCode};

/// An outgoing WebSocket message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Message {
    /// UTF-8 text message.
    Text(ByteString),
    /// Binary message.
    Binary(Bytes),
    /// Fragment of a text or binary message.
    Continuation(Item),
    /// Ping control message.
    Ping(Bytes),
    /// Pong control message.
    Pong(Bytes),
    /// Close control message with an optional reason.
    Close(Option<CloseReason>),
}

/// A decoded WebSocket frame.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Frame {
    /// Text frame.
    ///
    /// The payload is valid UTF-8 unless validation is disabled with
    /// [`Codec::validate_utf8()`].
    Text(Bytes),
    /// Binary frame.
    Binary(Bytes),
    /// Fragmented text or binary frame.
    Continuation(Item),
    /// Ping control frame.
    Ping(Bytes),
    /// Pong control frame.
    Pong(Bytes),
    /// Close control frame with an optional reason.
    Close(Option<CloseReason>),
}

/// A fragment in a WebSocket continuation sequence.
///
/// When decoding, a single fragment of a text message is not necessarily
/// valid UTF-8 on its own, a character can be split between fragments. The
/// codec validates the text of the whole message, see
/// [`Codec::validate_utf8()`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Item {
    /// First fragment of a text message.
    FirstText(Bytes),
    /// First fragment of a binary message.
    FirstBinary(Bytes),
    /// Intermediate fragment.
    Continue(Bytes),
    /// Final fragment.
    Last(Bytes),
}

#[derive(Debug, Clone)]
/// Encoder and decoder for WebSocket frames.
///
/// With the `compress` feature, the codec can use the `permessage-deflate`
/// extension, see [`Codec::set_deflate()`]. Clones of a codec share the
/// compression state.
///
/// The decoder limits the payload of each frame, see [`Codec::max_size()`],
/// and the total payload of a message, see [`Codec::max_message_size()`].
/// It also checks that text messages are valid UTF-8, see
/// [`Codec::validate_utf8()`].
pub struct Codec {
    flags: Cell<Flags>,
    max_size: usize,
    max_message_size: usize,
    validate_utf8: bool,
    /// Payload size of the incoming fragmented message.
    msg_size: Cell<usize>,
    /// Incomplete UTF-8 character at the end of the last text fragment.
    utf8_tail: Cell<Utf8Tail>,
    #[cfg(feature = "compress")]
    deflate: Option<Rc<Deflate>>,
}

bitflags::bitflags! {
    #[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
    struct Flags: u8 {
        const SERVER         = 0b0000_0001;
        const R_CONTINUATION = 0b0000_0010;
        const W_CONTINUATION = 0b0000_0100;
        const CLOSED         = 0b0000_1000;
        const R_CLOSED       = 0b0001_0000;
        const R_COMPRESSED   = 0b0010_0000;
        const R_TEXT         = 0b0100_0000;
        /// A pong was encoded since the last `auto_reply()` for a ping.
        const W_PONG         = 0b1000_0000;
    }
}

#[derive(Copy, Clone, Debug, Default)]
struct Utf8Tail {
    buf: [u8; 3],
    len: u8,
}

/// Validates the next fragment of a UTF-8 text message.
///
/// `tail` is the incomplete character at the end of the previous fragment,
/// the result is the incomplete character at the end of `data`. A message
/// must not end with an incomplete character.
fn validate_utf8(tail: Utf8Tail, mut data: &[u8], fin: bool) -> Result<Utf8Tail, ProtocolError> {
    if tail.len > 0 {
        // complete the character started by the previous fragment
        let mut ch = [0; 4];
        let mut len = usize::from(tail.len);
        ch[..len].copy_from_slice(&tail.buf[..len]);
        loop {
            let Some((&b, rest)) = data.split_first() else {
                return if fin {
                    Err(ProtocolError::InvalidUtf8)
                } else {
                    Ok(Utf8Tail {
                        buf: [ch[0], ch[1], ch[2]],
                        len: len as u8,
                    })
                };
            };
            // a prefix of three bytes is the longest incomplete character
            ch[len] = b;
            len += 1;
            data = rest;
            match simdutf8::compat::from_utf8(&ch[..len]) {
                Ok(_) => break,
                Err(e) if e.error_len().is_some() => return Err(ProtocolError::InvalidUtf8),
                Err(_) => {}
            }
        }
    }

    if simdutf8::basic::from_utf8(data).is_ok() {
        return Ok(Utf8Tail::default());
    }
    match simdutf8::compat::from_utf8(data) {
        Err(e) if e.error_len().is_none() && !fin => {
            let rest = &data[e.valid_up_to()..];
            let mut tail = Utf8Tail {
                len: rest.len() as u8,
                ..Utf8Tail::default()
            };
            tail.buf[..rest.len()].copy_from_slice(rest);
            Ok(tail)
        }
        _ => Err(ProtocolError::InvalidUtf8),
    }
}

impl Codec {
    /// Creates a codec in server mode.
    ///
    /// The codec limits frames to 64 KiB and messages to 4 MiB of payload,
    /// and validates incoming text messages.
    #[must_use]
    pub fn new() -> Codec {
        Codec {
            max_size: 65_536,
            max_message_size: 4 * 1024 * 1024,
            validate_utf8: true,
            msg_size: Cell::new(0),
            utf8_tail: Cell::new(Utf8Tail::default()),
            flags: Cell::new(Flags::SERVER),
            #[cfg(feature = "compress")]
            deflate: None,
        }
    }

    /// Sets the maximum accepted frame payload size.
    ///
    /// The default is 64 KiB. With the `permessage-deflate` extension, the
    /// limit applies to both the compressed and the decompressed payload of
    /// a frame.
    ///
    /// A fragmented message can consist of many frames, its total size is
    /// limited by [`Codec::max_message_size()`].
    #[must_use]
    pub fn max_size(mut self, size: usize) -> Self {
        self.max_size = size;
        self
    }

    /// Sets the maximum accepted payload size of an incoming message.
    ///
    /// The limit applies to the total payload of all frames of a fragmented
    /// message, and to single-frame messages. With the `permessage-deflate`
    /// extension, it applies to the decompressed payload. Control frames are
    /// not counted. A message that exceeds the limit fails with
    /// [`ProtocolError::Overflow`].
    ///
    /// The default is 4 MiB. Raise it together with [`Codec::max_size()`]
    /// to accept larger single-frame messages, use `usize::MAX` to only
    /// limit frames, for example to stream data with
    /// [`WsTransport`](super::WsTransport).
    #[must_use]
    pub fn max_message_size(mut self, size: usize) -> Self {
        self.max_message_size = size;
        self
    }

    /// Enables or disables UTF-8 validation of incoming text messages.
    ///
    /// When enabled, the payload of [`Frame::Text`] is valid UTF-8 and the
    /// fragments of a text message form valid UTF-8 when joined. A single
    /// fragment can end or start in the middle of a character. Invalid text
    /// fails with [`ProtocolError::InvalidUtf8`] as soon as it is detected,
    /// as RFC 6455 requires.
    ///
    /// Validation is enabled by default.
    #[must_use]
    pub fn validate_utf8(mut self, enabled: bool) -> Self {
        self.validate_utf8 = enabled;
        self
    }

    /// Configures the codec for client-side masking rules.
    ///
    /// Client mode masks encoded frames and rejects masked incoming frames.
    /// By default, the codec uses server-side masking rules.
    #[must_use]
    pub fn set_client_mode(self) -> Self {
        self.remove_flags(Flags::SERVER);
        self
    }

    #[cfg(feature = "compress")]
    /// Enables the `permessage-deflate` extension with the agreed parameters.
    ///
    /// Outgoing text and binary messages are compressed, incoming messages
    /// with the RSV1 bit set are decompressed. The parameters must be the
    /// result of the extension negotiation, the client and server roles of
    /// the parameters follow the codec mode.
    #[must_use]
    pub fn set_deflate(mut self, cfg: DeflateConfig) -> Self {
        self.deflate = Some(Rc::new(Deflate::new(cfg)));
        self
    }

    #[cfg(feature = "compress")]
    /// Returns the `permessage-deflate` parameters, if the extension is used.
    pub fn deflate(&self) -> Option<&DeflateConfig> {
        self.deflate.as_deref().map(Deflate::config)
    }

    /// Returns `true` after this codec has encoded a close message.
    pub fn is_closed(&self) -> bool {
        self.flags().contains(Flags::CLOSED)
    }

    fn flags(&self) -> Flags {
        self.flags.get()
    }

    fn insert_flags(&self, f: Flags) {
        self.flags.set(self.flags() | f);
    }

    fn remove_flags(&self, f: Flags) {
        self.flags.set(self.flags() - f);
    }

    fn is_server(&self) -> bool {
        self.flags().contains(Flags::SERVER)
    }

    /// Returns the reply to `frame` that is sent when a frame service
    /// returns no response, pass it to [`Codec::unanswered()`] after the
    /// service call.
    ///
    /// A ping is answered with a pong carrying the same payload, and a close
    /// with a close echoing the peer's code. A server cannot send the
    /// extension code, it answers it with a normal close.
    pub(crate) fn auto_reply(&self, frame: &Frame) -> Option<Message> {
        match frame {
            Frame::Ping(data) => {
                self.remove_flags(Flags::W_PONG);
                Some(Message::Pong(data.clone()))
            }
            Frame::Close(reason) => Some(Message::Close(reason.as_ref().map(|r| {
                if self.is_server() && r.code == CloseCode::Extension {
                    CloseCode::Normal.into()
                } else {
                    r.code.into()
                }
            }))),
            _ => None,
        }
    }

    /// Returns the service response, or the automatic `reply` if the service
    /// returned none.
    ///
    /// The automatic reply is dropped once a close message has been sent,
    /// and a pong is dropped if one was sent while the service handled
    /// the ping, e.g. through a sink.
    pub(crate) fn unanswered(
        &self,
        res: Option<Message>,
        reply: Option<Message>,
    ) -> Option<Message> {
        res.or_else(|| match reply {
            _ if self.is_closed() => None,
            Some(Message::Pong(_)) if self.flags().contains(Flags::W_PONG) => None,
            reply => reply,
        })
    }

    #[cfg_attr(not(feature = "compress"), allow(clippy::unused_self))]
    fn is_compressed(&self) -> bool {
        #[cfg(feature = "compress")]
        {
            self.deflate.is_some()
        }
        #[cfg(not(feature = "compress"))]
        {
            false
        }
    }

    /// Writes a data frame, compressed if the extension is used.
    ///
    /// `first` marks the first frame of a message, it carries the RSV1 bit.
    fn write_data<B>(
        &self,
        dst: &mut BytePages,
        payload: B,
        op: OpCode,
        first: bool,
        fin: bool,
    ) -> Result<(), ProtocolError>
    where
        BytePage: From<B>,
    {
        let payload = BytePage::from(payload);
        #[cfg(feature = "compress")]
        if let Some(deflate) = &self.deflate
            && !(first && fin && deflate.is_skipped(payload.len(), self.is_server()))
        {
            let payload = deflate.compress(payload.as_ref(), fin, self.is_server());
            return Parser::write_frame(dst, payload.into(), op, fin, first, !self.is_server());
        }
        let _ = first;
        Parser::write_frame(dst, payload, op, fin, false, !self.is_server())
    }

    /// Decompresses the payload of a data frame, if the message is
    /// compressed.
    #[cfg_attr(
        not(feature = "compress"),
        allow(clippy::unused_self, clippy::unnecessary_wraps)
    )]
    #[inline]
    fn read_data(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
        // only set if the extension is used
        #[cfg(feature = "compress")]
        if self.flags().contains(Flags::R_COMPRESSED) {
            return self.decompress(payload, fin);
        }
        let _ = fin;
        Ok(payload.unwrap_or_default())
    }

    #[cfg(feature = "compress")]
    #[inline(never)]
    fn decompress(&self, payload: Option<Bytes>, fin: bool) -> Result<Bytes, ProtocolError> {
        let payload = payload.unwrap_or_default();
        if fin {
            self.remove_flags(Flags::R_COMPRESSED);
        }
        self.deflate
            .as_ref()
            .expect("compressed messages require the extension")
            .decompress(&payload, fin, self.is_server(), self.max_size)
            .map(BytesMut::freeze)
    }

    /// Checks the payload of an incoming data frame against the message size
    /// limit and, for a text message, validates its UTF-8 encoding.
    ///
    /// `first` is `Some(is_text)` for the first frame of a message.
    fn check_data(
        &self,
        data: Bytes,
        first: Option<bool>,
        fin: bool,
    ) -> Result<Bytes, ProtocolError> {
        let (size, text) = match first {
            Some(text) => (data.len(), text),
            None => (
                self.msg_size.get().saturating_add(data.len()),
                self.flags().contains(Flags::R_TEXT),
            ),
        };
        if size > self.max_message_size {
            return Err(ProtocolError::Overflow);
        }
        if text && self.validate_utf8 {
            let tail = if first.is_some() {
                Utf8Tail::default()
            } else {
                self.utf8_tail.get()
            };
            self.utf8_tail.set(validate_utf8(tail, &data, fin)?);
        }

        if !fin {
            self.msg_size.set(size);
            if text {
                self.insert_flags(Flags::R_TEXT);
            } else {
                self.remove_flags(Flags::R_TEXT);
            }
        }
        Ok(data)
    }

    /// Encodes `page` as a final binary frame.
    ///
    /// # Errors
    ///
    /// Returns [`ProtocolError::Closed`] if a close message has already been
    /// encoded, or [`ProtocolError::ContinuationStarted`] if a fragmented
    /// message is in progress.
    pub fn encode_page(&self, page: BytePage, dst: &mut BytePages) -> Result<(), ProtocolError> {
        if self.is_closed() {
            return Err(ProtocolError::Closed);
        }
        if self.flags().contains(Flags::W_CONTINUATION) {
            return Err(ProtocolError::ContinuationStarted);
        }
        self.write_data(dst, page, OpCode::Binary, true, true)
            .expect("binary frames are always valid");
        Ok(())
    }
}

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

impl Encoder for Codec {
    type Item = Message;
    type Error = ProtocolError;

    fn encode(&self, item: Message, dst: &mut BytePages) -> Result<(), Self::Error> {
        if self.is_closed() {
            return Err(ProtocolError::Closed);
        }

        match item {
            Message::Text(txt) => {
                if self.flags().contains(Flags::W_CONTINUATION) {
                    return Err(ProtocolError::ContinuationStarted);
                }
                self.write_data(dst, txt, OpCode::Text, true, true)?;
            }
            Message::Binary(bin) => {
                if self.flags().contains(Flags::W_CONTINUATION) {
                    return Err(ProtocolError::ContinuationStarted);
                }
                self.write_data(dst, bin, OpCode::Binary, true, true)?;
            }
            Message::Ping(txt) => {
                Parser::write_message(dst, txt, OpCode::Ping, true, !self.is_server())?;
            }
            Message::Pong(txt) => {
                Parser::write_message(dst, txt, OpCode::Pong, true, !self.is_server())?;
                self.insert_flags(Flags::W_PONG);
            }
            Message::Close(reason) => {
                Parser::write_close(dst, reason, !self.is_server())?;
                self.insert_flags(Flags::CLOSED);
            }
            Message::Continuation(cont) => match cont {
                Item::FirstText(data) => {
                    if self.flags().contains(Flags::W_CONTINUATION) {
                        return Err(ProtocolError::ContinuationStarted);
                    }
                    self.insert_flags(Flags::W_CONTINUATION);
                    self.write_data(dst, data, OpCode::Text, true, false)?;
                }
                Item::FirstBinary(data) => {
                    if self.flags().contains(Flags::W_CONTINUATION) {
                        return Err(ProtocolError::ContinuationStarted);
                    }
                    self.insert_flags(Flags::W_CONTINUATION);
                    self.write_data(dst, data, OpCode::Binary, true, false)?;
                }
                Item::Continue(data) => {
                    if self.flags().contains(Flags::W_CONTINUATION) {
                        self.write_data(dst, data, OpCode::Continue, false, false)?;
                    } else {
                        return Err(ProtocolError::ContinuationNotStarted);
                    }
                }
                Item::Last(data) => {
                    if self.flags().contains(Flags::W_CONTINUATION) {
                        self.remove_flags(Flags::W_CONTINUATION);
                        self.write_data(dst, data, OpCode::Continue, false, true)?;
                    } else {
                        return Err(ProtocolError::ContinuationNotStarted);
                    }
                }
            },
        }
        Ok(())
    }
}

impl Decoder for Codec {
    type Item = Frame;
    type Error = ProtocolError;

    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        // the peer must not send anything after its close frame, discard it
        if self.flags().contains(Flags::R_CLOSED) {
            src.clear();
            return Ok(None);
        }

        let Some((finished, rsv1, opcode, payload)) =
            Parser::parse_frame(src, self.is_server(), self.max_size, self.is_compressed())?
        else {
            return Ok(None);
        };

        // only the first frame of a data message can be compressed
        if rsv1 {
            if !matches!(opcode, OpCode::Text | OpCode::Binary) {
                return Err(ProtocolError::ReservedBits(0b100));
            }
            if !self.flags().contains(Flags::R_CONTINUATION) {
                self.insert_flags(Flags::R_COMPRESSED);
            }
        }

        // handle continuation
        if finished {
            match opcode {
                OpCode::Continue => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        self.remove_flags(Flags::R_CONTINUATION);
                        let data = self.read_data(payload, true)?;
                        Ok(Some(Frame::Continuation(Item::Last(
                            self.check_data(data, None, true)?,
                        ))))
                    } else {
                        Err(ProtocolError::ContinuationNotStarted)
                    }
                }
                OpCode::Close => {
                    let reason = if let Some(pl) = payload {
                        Parser::parse_close_payload(&pl)?
                    } else {
                        None
                    };
                    self.insert_flags(Flags::R_CLOSED);
                    Ok(Some(Frame::Close(reason)))
                }
                OpCode::Ping => Ok(Some(Frame::Ping(payload.unwrap_or_default()))),
                OpCode::Pong => Ok(Some(Frame::Pong(payload.unwrap_or_default()))),
                OpCode::Binary => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        let data = self.read_data(payload, true)?;
                        Ok(Some(Frame::Binary(self.check_data(
                            data,
                            Some(false),
                            true,
                        )?)))
                    }
                }
                OpCode::Text => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        let data = self.read_data(payload, true)?;
                        Ok(Some(Frame::Text(self.check_data(
                            data,
                            Some(true),
                            true,
                        )?)))
                    }
                }
            }
        } else {
            match opcode {
                OpCode::Continue => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        let data = self.read_data(payload, false)?;
                        Ok(Some(Frame::Continuation(Item::Continue(
                            self.check_data(data, None, false)?,
                        ))))
                    } else {
                        Err(ProtocolError::ContinuationNotStarted)
                    }
                }
                OpCode::Binary => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        self.insert_flags(Flags::R_CONTINUATION);
                        let data = self.read_data(payload, false)?;
                        Ok(Some(Frame::Continuation(Item::FirstBinary(
                            self.check_data(data, Some(false), false)?,
                        ))))
                    }
                }
                OpCode::Text => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        self.insert_flags(Flags::R_CONTINUATION);
                        let data = self.read_data(payload, false)?;
                        Ok(Some(Frame::Continuation(Item::FirstText(
                            self.check_data(data, Some(true), false)?,
                        ))))
                    }
                }
                // rejected by the parser, kept for exhaustiveness
                OpCode::Ping | OpCode::Pong | OpCode::Close => {
                    Err(ProtocolError::FragmentedControlFrame(opcode))
                }
            }
        }
    }
}

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

    /// STATEMENT: Text frames are UTF-8 validated by default, and disabling validation returns the payload unchanged.
    ///
    /// HOW:
    /// - Decode a text frame containing `0xff` with a default codec and expect `InvalidUtf8`.
    /// - Expect `InvalidUtf8` for a text frame that ends inside a multi-byte character.
    /// - Decode valid multi-byte text with a default codec and expect it unchanged.
    /// - Decode the invalid frame with `validate_utf8(false)` and expect the raw byte back.
    #[test]
    fn text_payload_is_validated() {
        let codec = Codec::new().set_client_mode();
        assert!(matches!(
            decode(&codec, &[0x81, 0x01, 0xff]),
            Err(ProtocolError::InvalidUtf8)
        ));
        assert!(matches!(
            decode(&Codec::new().set_client_mode(), b"\x81\x02a\xe2"),
            Err(ProtocolError::InvalidUtf8)
        ));
        assert!(matches!(
            decode(&Codec::new().set_client_mode(), b"\x81\x03a\xc3\xa9"),
            Ok(Some(Frame::Text(data))) if data == "a\u{e9}".as_bytes()
        ));

        let codec = Codec::new().set_client_mode().validate_utf8(false);
        assert!(matches!(
            decode(&codec, &[0x81, 0x01, 0xff]),
            Ok(Some(Frame::Text(data))) if data == Bytes::from_static(&[0xff])
        ));
    }

    /// STATEMENT: Fragmented text is validated as a whole message, so characters may span fragments but the message must be valid UTF-8.
    ///
    /// HOW:
    /// - Split `\u{20ac}` (`e2 82 ac`) over first, continue, and last fragments with an empty fragment in between and expect all to decode.
    /// - Expect `InvalidUtf8` when a split character is completed with a non-continuation byte, when a message ends inside a character, and for an invalid byte in a later fragment.
    /// - Decode binary fragments with `0xff` and confirm binary data is not validated.
    #[test]
    fn fragmented_text_is_validated() {
        let codec = Codec::new().set_client_mode();
        for frame in [
            &b"\x01\x02a\xe2"[..],
            b"\x00\x00",
            b"\x00\x01\x82",
            b"\x80\x02\xacb",
        ] {
            assert!(matches!(
                decode(&codec, frame),
                Ok(Some(Frame::Continuation(_)))
            ));
        }

        let codec = Codec::new().set_client_mode();
        assert!(decode(&codec, b"\x01\x01\xe2").is_ok());
        assert!(matches!(
            decode(&codec, b"\x80\x01a"),
            Err(ProtocolError::InvalidUtf8)
        ));

        let codec = Codec::new().set_client_mode();
        assert!(decode(&codec, b"\x01\x02a\xe2").is_ok());
        assert!(decode(&codec, b"\x00\x01\x82").is_ok());
        assert!(matches!(
            decode(&codec, b"\x80\x00"),
            Err(ProtocolError::InvalidUtf8)
        ));

        let codec = Codec::new().set_client_mode();
        assert!(decode(&codec, b"\x01\x01a").is_ok());
        assert!(matches!(
            decode(&codec, b"\x00\x02b\xff"),
            Err(ProtocolError::InvalidUtf8)
        ));

        let codec = Codec::new().set_client_mode();
        assert!(decode(&codec, b"\x02\x01\xe2").is_ok());
        assert!(matches!(
            decode(&codec, b"\x80\x01\xff"),
            Ok(Some(Frame::Continuation(Item::Last(_))))
        ));
    }

    /// STATEMENT: The message size limit bounds the total payload of a fragmented message, applies to single frames, ignores control frames, and resets per message.
    ///
    /// HOW:
    /// - With `max_message_size(3)`, decode a 3-byte message split by a ping and expect success, then a second message of the same size.
    /// - Expect `Overflow` for a fragment that takes the total to 4 bytes and for a 4-byte single frame.
    #[test]
    fn message_size_limit() {
        let codec = Codec::new().set_client_mode().max_message_size(3);
        for _ in 0..2 {
            assert!(decode(&codec, b"\x02\x02ab").is_ok());
            assert!(matches!(
                decode(&codec, b"\x89\x04ping"),
                Ok(Some(Frame::Ping(_)))
            ));
            assert!(matches!(
                decode(&codec, b"\x80\x01c"),
                Ok(Some(Frame::Continuation(Item::Last(_))))
            ));
        }

        assert!(decode(&codec, b"\x01\x02ab").is_ok());
        assert!(decode(&codec, b"\x00\x01c").is_ok());
        assert!(matches!(
            decode(&codec, b"\x80\x01d"),
            Err(ProtocolError::Overflow)
        ));

        let codec = Codec::new().set_client_mode().max_message_size(3);
        assert!(matches!(
            decode(&codec, b"\x82\x04abcd"),
            Err(ProtocolError::Overflow)
        ));
    }

    /// STATEMENT: Receiving close discards both buffered and subsequently received frames.
    ///
    /// HOW:
    /// - Decode close followed by text, then add another text frame and verify both later decodes clear input without output.
    #[test]
    fn input_after_close_is_discarded() {
        let codec = Codec::new().set_client_mode();
        // close frame, followed by a text frame
        let mut src = BytesMut::from(&[0x88, 0x00, 0x81, 0x01, b'a'][..]);
        assert!(matches!(
            codec.decode(&mut src),
            Ok(Some(Frame::Close(None)))
        ));
        assert!(matches!(codec.decode(&mut src), Ok(None)));
        assert!(src.is_empty());

        src.extend_from_slice(&[0x81, 0x01, b'b']);
        assert!(matches!(codec.decode(&mut src), Ok(None)));
        assert!(src.is_empty());
    }

    /// STATEMENT: Receivers accept extension close code 1010 even though server-side encoders reject sending it.
    ///
    /// HOW:
    /// - Decode a peer close with code 1010 and attempt to encode the same reason in server mode.
    #[test]
    fn accepts_extension_close_code() {
        // servers should not send 1010, but receivers accept it
        let codec = Codec::new().set_client_mode();
        let mut close = BytesMut::from(&[0x88, 0x02, 0x03, 0xf2][..]);
        assert!(matches!(
            codec.decode(&mut close),
            Ok(Some(Frame::Close(Some(CloseReason {
                code: CloseCode::Extension,
                ..
            }))))
        ));

        // servers still cannot send it
        let codec = Codec::new();
        let mut dst = BytePages::default();
        assert!(matches!(
            codec.encode(Message::Close(Some(CloseCode::Extension.into())), &mut dst),
            Err(ProtocolError::InvalidCloseCode(1010))
        ));
    }

    /// STATEMENT: An active fragmented message prevents unrelated text or page messages until its last fragment.
    ///
    /// HOW:
    /// - Start a binary continuation, reject text/page sends, end it, and verify a page can then be encoded.
    #[test]
    fn validates_outgoing_continuations() {
        let codec = Codec::new();
        let mut dst = BytePages::default();
        codec
            .encode(
                Message::Continuation(Item::FirstBinary(Bytes::new())),
                &mut dst,
            )
            .unwrap();
        assert!(matches!(
            codec.encode(Message::Text("text".into()), &mut dst),
            Err(ProtocolError::ContinuationStarted)
        ));
        assert!(matches!(
            codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
            Err(ProtocolError::ContinuationStarted)
        ));

        codec
            .encode(Message::Continuation(Item::Last(Bytes::new())), &mut dst)
            .unwrap();
        codec
            .encode_page(BytePage::from(Bytes::new()), &mut dst)
            .unwrap();
    }

    /// STATEMENT: Sending close prevents later text and page messages.
    ///
    /// HOW:
    /// - Encode close, then check both outgoing data APIs return the closed-protocol error.
    #[test]
    fn rejects_messages_after_close() {
        let codec = Codec::new();
        let mut dst = BytePages::default();
        codec.encode(Message::Close(None), &mut dst).unwrap();

        assert!(matches!(
            codec.encode(Message::Text("text".into()), &mut dst),
            Err(ProtocolError::Closed)
        ));
        assert!(matches!(
            codec.encode_page(BytePage::from(Bytes::new()), &mut dst),
            Err(ProtocolError::Closed)
        ));
    }

    /// STATEMENT: Encoding rejects oversized controls and invalid continuation transitions.
    ///
    /// HOW:
    /// - Reject oversized ping/pong, new data during a text continuation, and continuation after its last fragment.
    #[test]
    fn encode_errors() {
        let codec = Codec::new();
        let mut dst = BytePages::default();
        let big = Bytes::from(vec![0; 126]);
        assert!(matches!(
            codec.encode(Message::Ping(big.clone()), &mut dst),
            Err(ProtocolError::InvalidLength(126))
        ));
        assert!(matches!(
            codec.encode(Message::Pong(big), &mut dst),
            Err(ProtocolError::InvalidLength(126))
        ));

        codec
            .encode(Message::Continuation(Item::FirstText("a".into())), &mut dst)
            .unwrap();
        assert!(matches!(
            codec.encode(Message::Binary("b".into()), &mut dst),
            Err(ProtocolError::ContinuationStarted)
        ));
        assert!(matches!(
            codec.encode(
                Message::Continuation(Item::FirstBinary("b".into())),
                &mut dst
            ),
            Err(ProtocolError::ContinuationStarted)
        ));
        codec
            .encode(Message::Continuation(Item::Last("c".into())), &mut dst)
            .unwrap();
        assert!(matches!(
            codec.encode(Message::Continuation(Item::Continue("d".into())), &mut dst),
            Err(ProtocolError::ContinuationNotStarted)
        ));
    }

    fn decode(codec: &Codec, frame: &[u8]) -> Result<Option<Frame>, ProtocolError> {
        codec.decode(&mut BytesMut::from(frame))
    }

    /// STATEMENT: Decoding enforces fragmented-message ordering without preventing valid later continuation frames.
    ///
    /// HOW:
    /// - Reject orphan continuations and new data while a binary message is open.
    /// - Continue that message and verify an empty final fragment completes it.
    #[test]
    fn decode_continuation_errors() {
        let codec = Codec::new().set_client_mode();
        // continuation without a first frame
        assert!(matches!(
            decode(&codec, &[0x80, 0x01, b'a']),
            Err(ProtocolError::ContinuationNotStarted)
        ));
        assert!(matches!(
            decode(&codec, &[0x00, 0x01, b'a']),
            Err(ProtocolError::ContinuationNotStarted)
        ));

        // new data frames while a fragmented message is in progress
        assert!(matches!(
            decode(&codec, &[0x02, 0x01, b'a']),
            Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
        ));
        for frame in [
            &[0x82, 0x01, b'a'],
            &[0x81, 0x01, b'a'],
            &[0x02, 0x01, b'a'],
            &[0x01, 0x01, b'a'],
        ] {
            assert!(matches!(
                decode(&codec, frame),
                Err(ProtocolError::ContinuationStarted)
            ));
        }
        assert!(matches!(
            decode(&codec, &[0x00, 0x01, b'b']),
            Ok(Some(Frame::Continuation(Item::Continue(_))))
        ));
        assert!(matches!(
            decode(&codec, &[0x80, 0x00]),
            Ok(Some(Frame::Continuation(Item::Last(data)))) if data.is_empty()
        ));
    }

    #[cfg(feature = "compress")]
    mod deflate {
        use super::*;
        use crate::ws::DeflateConfig;

        fn client() -> Codec {
            Codec::new()
                .set_client_mode()
                .set_deflate(DeflateConfig::new())
        }

        fn server() -> Codec {
            Codec::new().set_deflate(DeflateConfig::new())
        }

        fn encode(codec: &Codec, msg: Message) -> BytesMut {
            let mut dst = BytePages::default();
            codec.encode(msg, &mut dst).unwrap();
            BytesMut::from(&Bytes::from(dst)[..])
        }

        fn decode_all(codec: &Codec, mut src: BytesMut) -> Vec<Frame> {
            let mut frames = Vec::new();
            while let Some(frame) = codec.decode(&mut src).unwrap() {
                frames.push(frame);
            }
            assert!(src.is_empty());
            frames
        }

        fn text(data: &'static str) -> Frame {
            Frame::Text(Bytes::from_static(data.as_bytes()))
        }

        /// STATEMENT: Deflate frame decoding matches RFC 7692 examples across fragmentation, context reuse, and block forms.
        ///
        /// HOW:
        /// - Decode published single/fragmented, context-dependent, stored, final-block, multi-block, and empty messages.
        /// - Compare their text and continuation outputs.
        #[test]
        fn rfc7692_examples() {
            // 7.2.3.1, a message in one frame and in two fragments
            let frames = decode_all(
                &client(),
                BytesMut::from(&[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00][..]),
            );
            assert_eq!(frames, [text("Hello")]);
            let frames = decode_all(
                &client(),
                BytesMut::from(
                    &[
                        0x41, 0x03, 0xf2, 0x48, 0xcd, 0x80, 0x04, 0xc9, 0xc9, 0x07, 0x00,
                    ][..],
                ),
            );
            assert_eq!(
                frames,
                [
                    Frame::Continuation(Item::FirstText(Bytes::from_static(b"He"))),
                    Frame::Continuation(Item::Last(Bytes::from_static(b"llo"))),
                ]
            );

            // 7.2.3.2, the second message refers to the first one
            let frames = decode_all(
                &client(),
                BytesMut::from(
                    &[
                        0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x05, 0xf2,
                        0x00, 0x11, 0x00, 0x00,
                    ][..],
                ),
            );
            assert_eq!(frames, [text("Hello"), text("Hello")]);

            // 7.2.3.3, a stored block
            // 7.2.3.4, a block with BFINAL set, followed by a new stream
            // 7.2.3.5, two blocks in one message
            // 7.2.3.6, an empty message
            let frames = decode_all(
                &client(),
                BytesMut::from(
                    &[
                        0xc1, 0x0b, 0x00, 0x05, 0x00, 0xfa, 0xff, 0x48, 0x65, 0x6c, 0x6c, 0x6f,
                        0x00, 0xc1, 0x08, 0xf3, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0x00, 0xc1,
                        0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00, 0xc1, 0x0d, 0xf2, 0x48,
                        0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0xca, 0xc9, 0xc9, 0x07, 0x00, 0xc1,
                        0x01, 0x00, 0xc1, 0x00,
                    ][..],
                ),
            );
            assert_eq!(
                frames,
                [
                    text("Hello"),
                    text("Hello"),
                    text("Hello"),
                    text("Hello"),
                    text(""),
                    text("")
                ]
            );
        }

        /// STATEMENT: No-context-takeover servers skip small whole messages but still compress fragments.
        ///
        /// HOW:
        /// - Inspect frame flags and round trips around the small-message threshold, then encode a fragment.
        /// - Verify the client still compresses small messages when its context remains enabled.
        #[test]
        fn small_messages_without_context_takeover() {
            let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
            let server = Codec::new().set_deflate(cfg.clone());
            let client = Codec::new().set_client_mode().set_deflate(cfg);

            // small unfragmented messages are not compressed
            for (len, first) in [(0, 0x82), (32, 0x82), (33, 0xc2)] {
                let data = Bytes::from("a".repeat(len));
                let frame = encode(&server, Message::Binary(data.clone()));
                assert_eq!(frame[0], first);
                assert_eq!(decode_all(&client, frame), [Frame::Binary(data)]);
            }

            // fragmented messages are compressed
            let frame = encode(
                &server,
                Message::Continuation(Item::FirstText(Bytes::from_static(b"a"))),
            );
            assert_eq!(frame[0], 0x41);

            // the client keeps its context
            let frame = encode(&client, Message::Text("Hello".into()));
            assert_eq!(frame[0], 0xc1);
        }

        /// STATEMENT: Deflate text encoding reproduces the RFC 7692 Hello example.
        ///
        /// HOW:
        /// - Encode the example message and compare every compressed frame byte.
        #[test]
        fn encode_rfc7692_example() {
            let codec = Codec::new().set_deflate(DeflateConfig::new());
            assert_eq!(
                &encode(&codec, Message::Text("Hello".into()))[..],
                &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
            );
        }

        /// STATEMENT: Deflate codecs round-trip mixed messages and interleaved controls in both client/server directions.
        ///
        /// HOW:
        /// - Repeatedly encode text, large/empty binary data, controls, and text/binary continuations.
        /// - Decode each combined buffer and compare the complete frame sequence.
        #[test]
        fn roundtrip() {
            let (client, server) = (client(), server());
            let data: Vec<u8> = (0..60_000u32)
                .map(|i| if i % 7 == 0 { (i >> 3) as u8 } else { b'a' })
                .collect();
            let data = Bytes::from(data);

            for _ in 0..3 {
                for (from, to) in [(&client, &server), (&server, &client)] {
                    let msgs = [
                        Message::Text("text message".into()),
                        Message::Binary(data.clone()),
                        Message::Binary(Bytes::new()),
                        Message::Ping("ping".into()),
                        Message::Continuation(Item::FirstBinary(data.slice(..1000))),
                        Message::Pong("pong".into()),
                        Message::Continuation(Item::Continue(Bytes::new())),
                        Message::Continuation(Item::Continue(data.slice(1000..30_000))),
                        Message::Continuation(Item::Last(data.slice(30_000..))),
                        Message::Continuation(Item::FirstText("a".into())),
                        Message::Continuation(Item::Last("b".into())),
                    ];
                    let mut src = BytesMut::new();
                    for msg in msgs {
                        src.extend_from_slice(&encode(from, msg));
                    }
                    assert_eq!(
                        decode_all(to, src),
                        [
                            text("text message"),
                            Frame::Binary(data.clone()),
                            Frame::Binary(Bytes::new()),
                            Frame::Ping("ping".into()),
                            Frame::Continuation(Item::FirstBinary(data.slice(..1000))),
                            Frame::Pong("pong".into()),
                            Frame::Continuation(Item::Continue(Bytes::new())),
                            Frame::Continuation(Item::Continue(data.slice(1000..30_000))),
                            Frame::Continuation(Item::Last(data.slice(30_000..))),
                            Frame::Continuation(Item::FirstText("a".into())),
                            Frame::Continuation(Item::Last("b".into())),
                        ]
                    );
                }
            }
        }

        /// STATEMENT: Compressed payloads remain decodable when reframed into small fragments with an empty final fragment.
        ///
        /// HOW:
        /// - Split compressed binary messages into 16-byte frames, append an empty last frame, and repeat with reused contexts.
        /// - Reassemble decoded continuation data and compare the original payload.
        #[test]
        fn fragmented_compressed_payload() {
            // a compressed message split into frames of 16 bytes, like the
            // auto-fragmentation of autobahn, the last frame can be empty
            let sender = server();
            let codec = client();
            let data = Bytes::from(b"Hello, Hello, Hello".repeat(40));
            for _ in 0..3 {
                let mut frame = encode(&sender, Message::Binary(data.clone()));
                frame.advance_to(2);
                let len = frame.len();
                frame.advance_to(if len < 126 { 0 } else { 2 });
                let payload = frame.freeze();
                let chunks: Vec<_> = payload.chunks(16).chain([&[][..]]).collect();

                let mut src = BytesMut::new();
                for (i, chunk) in chunks.iter().enumerate() {
                    let mut first = if i == 0 { 0x42 } else { 0x00 };
                    if i == chunks.len() - 1 {
                        first |= 0x80;
                    }
                    src.extend_from_slice(&[first, chunk.len() as u8]);
                    src.extend_from_slice(chunk);
                }
                let mut out = BytesMut::new();
                for frame in decode_all(&codec, src) {
                    match frame {
                        Frame::Continuation(
                            Item::FirstBinary(b) | Item::Continue(b) | Item::Last(b),
                        ) => out.extend_from_slice(&b),
                        f => panic!("{f:?}"),
                    }
                }
                assert_eq!(out, data);
            }
        }

        /// STATEMENT: Deflate sets RSV1 only on initial data frames and leaves controls uncompressed.
        ///
        /// HOW:
        /// - Inspect whole-message, continuation, ping, and close wire flags and bytes.
        /// - Encode a binary page and verify its compressed flag and decoded payload.
        #[test]
        fn rsv1_only_on_first_data_frame() {
            let codec = server();
            let data = Bytes::from(vec![b'x'; 1000]);
            let frame = encode(&codec, Message::Binary(data.clone()));
            assert_eq!(frame[0], 0xc2);
            assert!(frame.len() < 100);

            let frame = encode(&codec, Message::Continuation(Item::FirstText("a".into())));
            assert_eq!(frame[0], 0x41);
            let frame = encode(&codec, Message::Continuation(Item::Continue("b".into())));
            assert_eq!(frame[0], 0x00);
            let frame = encode(&codec, Message::Continuation(Item::Last("c".into())));
            assert_eq!(frame[0], 0x80);

            // control frames are not compressed
            let frame = encode(&codec, Message::Ping("ping".into()));
            assert_eq!(&frame[..], b"\x89\x04ping");
            let frame = encode(&codec, Message::Close(None));
            assert_eq!(&frame[..], &[0x88, 0x00]);

            // binary pages are compressed
            let mut dst = BytePages::default();
            server()
                .encode_page(BytePage::from(data.clone()), &mut dst)
                .unwrap();
            let mut src = BytesMut::from(&Bytes::from(dst)[..]);
            assert_eq!(src[0], 0xc2);
            assert_eq!(
                client().decode(&mut src).unwrap(),
                Some(Frame::Binary(data))
            );
        }

        /// STATEMENT: Negotiating deflate still permits uncompressed whole and fragmented messages.
        ///
        /// HOW:
        /// - Decode a buffer mixing uncompressed text/fragments/binary and an empty compressed message.
        /// - Compare the complete expected frame sequence.
        #[test]
        fn uncompressed_messages() {
            // the peer may send uncompressed messages
            let codec = client();
            let frames = decode_all(
                &codec,
                BytesMut::from(&b"\x81\x05Hello\x01\x01a\x80\x01b\xc1\x01\x00\x82\x01c"[..]),
            );
            assert_eq!(
                frames,
                [
                    text("Hello"),
                    Frame::Continuation(Item::FirstText("a".into())),
                    Frame::Continuation(Item::Last("b".into())),
                    text(""),
                    Frame::Binary("c".into()),
                ]
            );
        }

        /// STATEMENT: Deflate does not permit RSV1 on controls/continuations or any use of RSV2/RSV3.
        ///
        /// HOW:
        /// - Decode illegal flag combinations and inspect reserved-bit errors.
        /// - Verify RSV1 is also rejected when compression was not negotiated.
        #[test]
        fn reserved_bits() {
            for frame in [
                // RSV1 on control frames and continuation frames
                &b"\xc9\x00"[..],
                b"\xca\x00",
                b"\xc8\x00",
                // RSV2 and RSV3 are not used by the extension
                b"\xa1\x00",
                b"\x91\x00",
                b"\xe1\x00",
            ] {
                assert!(
                    matches!(
                        decode(&client(), frame),
                        Err(ProtocolError::ReservedBits(_))
                    ),
                    "{frame:?}"
                );
            }

            let codec = client();
            assert!(matches!(
                decode(&codec, b"\x01\x01a"),
                Ok(Some(Frame::Continuation(Item::FirstText(_))))
            ));
            assert!(matches!(
                decode(&codec, b"\xc0\x01\x00"),
                Err(ProtocolError::ReservedBits(0b100))
            ));

            // RSV1 is reserved without the extension
            assert!(matches!(
                decode(
                    &Codec::new().set_client_mode(),
                    &[0xc1, 0x07, 0xf2, 0x48, 0xcd, 0xc9, 0xc9, 0x07, 0x00]
                ),
                Err(ProtocolError::ReservedBits(0b100))
            ));
        }

        /// STATEMENT: Invalid compressed data is rejected in both complete and initial-fragment frames.
        ///
        /// HOW:
        /// - Decode malformed deflate bytes with final and nonfinal text headers and compare protocol errors.
        #[test]
        fn invalid_data() {
            assert!(matches!(
                decode(&client(), b"\xc1\x02\xff\xff"),
                Err(ProtocolError::InvalidCompressedData)
            ));
            assert!(matches!(
                decode(&client(), b"\x41\x02\xff\xff"),
                Err(ProtocolError::InvalidCompressedData)
            ));
        }

        /// STATEMENT: Frame-size limits apply to decompressed bytes, independently for each fragment.
        ///
        /// HOW:
        /// - Decode a highly compressed payload at and below its expanded-size limit.
        /// - Accept a boundary-sized first fragment and reject an oversized last fragment.
        #[test]
        fn decompressed_size_limit() {
            let data = Bytes::from(vec![0; 1024 * 1024]);
            let frame = encode(&server(), Message::Binary(data.clone()));
            assert!(frame.len() < 2048);

            let codec = Codec::new()
                .set_client_mode()
                .max_size(data.len() - 1)
                .set_deflate(DeflateConfig::new());
            assert!(matches!(
                codec.decode(&mut frame.clone()),
                Err(ProtocolError::Overflow)
            ));

            let codec = Codec::new()
                .set_client_mode()
                .max_size(data.len())
                .set_deflate(DeflateConfig::new());
            assert_eq!(
                codec.decode(&mut frame.clone()).unwrap(),
                Some(Frame::Binary(data))
            );

            // the limit applies to each fragment
            let codec = Codec::new()
                .set_client_mode()
                .max_size(1000)
                .set_deflate(DeflateConfig::new());
            let sender = server();
            let mut src = encode(
                &sender,
                Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
            );
            src.extend_from_slice(&encode(
                &sender,
                Message::Continuation(Item::Last(vec![0; 1001].into())),
            ));
            assert!(matches!(
                codec.decode(&mut src),
                Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
            ));
            assert!(matches!(
                codec.decode(&mut src),
                Err(ProtocolError::Overflow)
            ));
        }

        /// STATEMENT: Message size limits and UTF-8 validation apply to decompressed payloads.
        ///
        /// HOW:
        /// - Send two compressed 1000-byte fragments to a codec with `max_message_size(1500)` and expect `Overflow` on the second.
        /// - Send a compressed text fragment holding `0xff` and expect `InvalidUtf8`.
        #[test]
        fn message_limits_after_decompression() {
            let sender = server();
            let codec = client().max_message_size(1500);
            let mut src = encode(
                &sender,
                Message::Continuation(Item::FirstBinary(vec![0; 1000].into())),
            );
            src.extend_from_slice(&encode(
                &sender,
                Message::Continuation(Item::Last(vec![0; 1000].into())),
            ));
            assert!(src.len() < 1500);
            assert!(matches!(
                codec.decode(&mut src),
                Ok(Some(Frame::Continuation(Item::FirstBinary(_))))
            ));
            assert!(matches!(
                codec.decode(&mut src),
                Err(ProtocolError::Overflow)
            ));

            let src = encode(
                &server(),
                Message::Continuation(Item::FirstText(Bytes::from_static(&[0xff]))),
            );
            assert!(matches!(
                client().decode(&mut src.clone()),
                Err(ProtocolError::InvalidUtf8)
            ));
        }

        /// STATEMENT: Negotiated server context resets reject cross-message references without resetting the client's compressor.
        ///
        /// HOW:
        /// - Compare repeated server frames and decode them with fresh contexts, then reject a back-reference-only message.
        /// - Verify repeated client messages shrink through retained compression history.
        #[test]
        fn context_takeover() {
            // the server resets its context, the client reads each message
            // with a new context
            let cfg = DeflateConfig::new().set_server_no_context_takeover(true);
            let server = Codec::new().set_deflate(cfg.clone());
            let client = Codec::new().set_client_mode().set_deflate(cfg);
            let first = encode(&server, Message::Text("Hello".into()));
            assert_eq!(encode(&server, Message::Text("Hello".into())), first);
            let mut src = first.clone();
            src.extend_from_slice(&first);
            assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);

            // a message that refers to the previous one
            assert!(matches!(
                decode(&client, &[0xc1, 0x05, 0xf2, 0x00, 0x11, 0x00, 0x00]),
                Err(ProtocolError::InvalidCompressedData)
            ));

            // the client keeps its context
            let first = encode(&client, Message::Text("Hello".into()));
            assert!(encode(&client, Message::Text("Hello".into())).len() < first.len());
        }

        /// STATEMENT: Cloned WebSocket codecs share negotiated compression configuration and history.
        ///
        /// HOW:
        /// - Inspect clone/default configuration, encode consecutive messages through separate clones, and decode both together.
        #[test]
        fn clones_share_state() {
            let (client, server) = (client(), server());
            let server2 = server.clone();
            assert_eq!(server2.deflate(), Some(&DeflateConfig::new()));
            assert_eq!(Codec::new().deflate(), None);

            let mut src = encode(&server, Message::Text("Hello".into()));
            src.extend_from_slice(&encode(&server2, Message::Text("Hello".into())));
            assert_eq!(decode_all(&client, src), [text("Hello"), text("Hello")]);
        }
    }
}