ntex 4.6.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
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::{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 codec does not validate that the payload is UTF-8.
    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.
#[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.
pub struct Codec {
    flags: Cell<Flags>,
    max_size: usize,
    #[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;
    }
}

impl Codec {
    /// Creates a codec in server mode with a 64 KiB frame-size limit.
    #[must_use]
    pub fn new() -> Codec {
        Codec {
            max_size: 65_536,
            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.
    #[must_use]
    pub fn max_size(mut self, size: usize) -> Self {
        self.max_size = size;
        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)
    }

    #[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)
    }

    /// 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())?;
            }
            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);
                        Ok(Some(Frame::Continuation(Item::Last(
                            self.read_data(payload, 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 {
                        Ok(Some(Frame::Binary(self.read_data(payload, true)?)))
                    }
                }
                OpCode::Text => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        Ok(Some(Frame::Text(self.read_data(payload, true)?)))
                    }
                }
            }
        } else {
            match opcode {
                OpCode::Continue => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Ok(Some(Frame::Continuation(Item::Continue(
                            self.read_data(payload, false)?,
                        ))))
                    } else {
                        Err(ProtocolError::ContinuationNotStarted)
                    }
                }
                OpCode::Binary => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        self.insert_flags(Flags::R_CONTINUATION);
                        Ok(Some(Frame::Continuation(Item::FirstBinary(
                            self.read_data(payload, false)?,
                        ))))
                    }
                }
                OpCode::Text => {
                    if self.flags().contains(Flags::R_CONTINUATION) {
                        Err(ProtocolError::ContinuationStarted)
                    } else {
                        self.insert_flags(Flags::R_CONTINUATION);
                        Ok(Some(Frame::Continuation(Item::FirstText(
                            self.read_data(payload, 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-frame decoding leaves UTF-8 validation to consumers.
    ///
    /// HOW:
    /// - Decode a text frame containing an invalid UTF-8 byte and verify it is returned unchanged.
    #[test]
    fn text_payload_is_not_validated() {
        let codec = Codec::new().set_client_mode();
        let mut frame = BytesMut::from(&[0x81, 0x01, 0xff][..]);
        assert!(matches!(
            codec.decode(&mut frame),
            Ok(Some(Frame::Text(data))) if data == Bytes::from_static(&[0xff])
        ));
    }

    /// 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: 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")]);
        }
    }
}