Skip to main content

ntex/ws/
frame.rs

1use super::proto::{CloseCode, CloseReason, OpCode};
2use super::{error::ProtocolError, mask::apply_mask};
3use crate::util::{BufMut, BytePage, BytePages, Bytes, BytesMut};
4
5/// WebSocket frame parser.
6#[derive(Debug)]
7pub struct Parser;
8
9impl Parser {
10    #[inline]
11    fn parse_metadata(
12        src: &[u8],
13        server: bool,
14        max_size: usize,
15        allow_rsv1: bool,
16    ) -> Result<Option<(usize, bool, bool, OpCode, usize, Option<u32>)>, ProtocolError> {
17        let chunk_len = src.len();
18
19        let mut idx = 2;
20        if chunk_len < 2 {
21            return Ok(None);
22        }
23
24        let first = src[0];
25        let second = src[1];
26        let finished = first & 0x80 != 0;
27        let rsv1 = allow_rsv1 && first & 0x40 != 0;
28        let reserved = first & if allow_rsv1 { 0x30 } else { 0x70 };
29        if reserved != 0 {
30            return Err(ProtocolError::ReservedBits(reserved >> 4));
31        }
32
33        // check masking
34        let masked = second & 0x80 != 0;
35        if !masked && server {
36            return Err(ProtocolError::UnmaskedFrame);
37        } else if masked && !server {
38            return Err(ProtocolError::MaskedFrame);
39        }
40
41        // Op code
42        let raw_opcode = first & 0x0F;
43        let opcode =
44            OpCode::try_from(raw_opcode).map_err(|()| ProtocolError::InvalidOpcode(raw_opcode))?;
45        if opcode.is_control() && !finished {
46            return Err(ProtocolError::FragmentedControlFrame(opcode));
47        }
48
49        let len = second & 0x7F;
50        let length = if len == 126 {
51            if chunk_len < 4 {
52                return Ok(None);
53            }
54            let len = usize::from(u16::from_be_bytes(
55                TryFrom::try_from(&src[idx..idx + 2]).unwrap(),
56            ));
57            if len < 126 {
58                return Err(ProtocolError::InvalidLengthEncoding);
59            }
60            idx += 2;
61            len
62        } else if len == 127 {
63            if chunk_len < 10 {
64                return Ok(None);
65            }
66            if src[idx] & 0x80 != 0 {
67                return Err(ProtocolError::InvalidLengthEncoding);
68            }
69            let len = u64::from_be_bytes(TryFrom::try_from(&src[idx..idx + 8]).unwrap());
70            if len < 65_536 {
71                return Err(ProtocolError::InvalidLengthEncoding);
72            }
73            if len > max_size as u64 {
74                return Err(ProtocolError::Overflow);
75            }
76            idx += 8;
77            len as usize
78        } else {
79            len as usize
80        };
81
82        if opcode.is_control() && length > 125 {
83            return Err(ProtocolError::InvalidLength(length));
84        }
85
86        // check for max allowed size
87        if length > max_size {
88            return Err(ProtocolError::Overflow);
89        }
90
91        let mask = if server {
92            if chunk_len < idx + 4 {
93                return Ok(None);
94            }
95
96            let mask = u32::from_ne_bytes(TryFrom::try_from(&src[idx..idx + 4]).unwrap());
97            idx += 4;
98            Some(mask)
99        } else {
100            None
101        };
102
103        Ok(Some((idx, finished, rsv1, opcode, length, mask)))
104    }
105
106    /// Parses one WebSocket frame from `src`.
107    ///
108    /// `server` selects the expected masking direction: server-side parsing
109    /// requires masked frames, while client-side parsing rejects them.
110    /// `max_size` limits the frame payload size.
111    ///
112    /// Returns the final-fragment flag, opcode, and optional payload when a
113    /// complete frame is available. Returns [`None`] without consuming a
114    /// partial frame.
115    pub fn parse(
116        src: &mut BytesMut,
117        server: bool,
118        max_size: usize,
119    ) -> Result<Option<(bool, OpCode, Option<Bytes>)>, ProtocolError> {
120        Ok(Parser::parse_frame(src, server, max_size, false)?
121            .map(|(finished, _, opcode, payload)| (finished, opcode, payload)))
122    }
123
124    /// Parses one WebSocket frame from `src`, like [`Parser::parse`].
125    ///
126    /// If `allow_rsv1` is set, the RSV1 bit is accepted and returned after
127    /// the final-fragment flag.
128    // inlined into the decoder, the frame tuple is not moved
129    #[allow(clippy::inline_always)]
130    #[inline(always)]
131    pub(super) fn parse_frame(
132        src: &mut BytesMut,
133        server: bool,
134        max_size: usize,
135        allow_rsv1: bool,
136    ) -> Result<Option<(bool, bool, OpCode, Option<Bytes>)>, ProtocolError> {
137        // try to parse ws frame metadata
138        let Some((idx, finished, rsv1, opcode, length, mask)) =
139            Parser::parse_metadata(src, server, max_size, allow_rsv1)?
140        else {
141            return Ok(None);
142        };
143
144        // not enough data
145        if src.len() < idx + length {
146            return Ok(None);
147        }
148
149        // remove prefix
150        src.advance_to(idx);
151
152        // no need for body
153        if length == 0 {
154            return Ok(Some((finished, rsv1, opcode, None)));
155        }
156
157        // unmask
158        if let Some(mask) = mask {
159            apply_mask(&mut src[..length], mask);
160        }
161
162        Ok(Some((finished, rsv1, opcode, Some(src.split_to(length)))))
163    }
164
165    /// Parses a close-frame payload.
166    ///
167    /// Returns [`None`] for an empty payload.
168    ///
169    /// # Errors
170    ///
171    /// Returns an error for a one-byte payload, an invalid close status code,
172    /// or a description that is not valid UTF-8.
173    pub fn parse_close_payload(payload: &[u8]) -> Result<Option<CloseReason>, ProtocolError> {
174        if payload.is_empty() {
175            return Ok(None);
176        }
177
178        if payload.len() == 1 {
179            return Err(ProtocolError::InvalidClosePayload);
180        }
181
182        let raw_code = u16::from_be_bytes(TryFrom::try_from(&payload[..2]).unwrap());
183        let code = CloseCode::from(raw_code);
184        if !code.is_valid() {
185            return Err(ProtocolError::InvalidCloseCode(raw_code));
186        }
187        let description = if payload.len() > 2 {
188            Some(
189                std::str::from_utf8(&payload[2..])
190                    .map_err(|_| ProtocolError::InvalidUtf8)?
191                    .to_owned(),
192            )
193        } else {
194            None
195        };
196        Ok(Some(CloseReason { code, description }))
197    }
198
199    /// Encodes a WebSocket frame into `dst`.
200    ///
201    /// `fin` controls the final-fragment bit and `mask` controls whether a new
202    /// random masking key is applied.
203    ///
204    /// # Errors
205    ///
206    /// Returns an error if a control frame is fragmented or has a payload
207    /// larger than 125 bytes.
208    pub fn write_message<B>(
209        dst: &mut BytePages,
210        pl: B,
211        op: OpCode,
212        fin: bool,
213        mask: bool,
214    ) -> Result<(), ProtocolError>
215    where
216        BytePage: From<B>,
217    {
218        Parser::write_frame(dst, BytePage::from(pl), op, fin, false, mask)
219    }
220
221    /// Encodes a WebSocket frame into `dst`, like [`Parser::write_message`],
222    /// `rsv1` sets the RSV1 bit.
223    pub(super) fn write_frame(
224        dst: &mut BytePages,
225        payload: BytePage,
226        op: OpCode,
227        fin: bool,
228        rsv1: bool,
229        mask: bool,
230    ) -> Result<(), ProtocolError> {
231        if op.is_control() {
232            if !fin {
233                return Err(ProtocolError::FragmentedControlFrame(op));
234            }
235            if payload.len() > 125 {
236                return Err(ProtocolError::InvalidLength(payload.len()));
237            }
238        }
239
240        let mut one: u8 = op.into();
241        if fin {
242            one |= 0x80;
243        }
244        if rsv1 {
245            one |= 0x40;
246        }
247        let payload_len = payload.len();
248        let two = if mask { 0x80 } else { 0 };
249
250        // the extended length is 2 or 8 big-endian bytes
251        let ext_len = (payload_len as u64).to_be_bytes();
252        let (len, ext): (u8, &[u8]) = if payload_len < 126 {
253            (payload_len as u8, &[])
254        } else if payload_len <= 65_535 {
255            (126, &ext_len[6..])
256        } else {
257            (127, &ext_len)
258        };
259        let header = [one, two | len];
260
261        if mask {
262            let mask = fastrand::u32(..);
263            let mut buf = BytesMut::from(payload);
264            apply_mask(&mut buf, mask);
265            dst.put_slices(&[&header, ext, &mask.to_ne_bytes()]);
266            dst.append::<BytesMut>(buf);
267        } else {
268            dst.put_slices(&[&header, ext]);
269            dst.append::<BytePage>(payload);
270        }
271        Ok(())
272    }
273
274    /// Encodes a final close control frame into `dst`.
275    ///
276    /// # Errors
277    ///
278    /// Returns an error if the close code cannot be sent or the encoded close
279    /// payload would exceed 125 bytes.
280    #[inline]
281    pub fn write_close(
282        dst: &mut BytePages,
283        reason: Option<CloseReason>,
284        mask: bool,
285    ) -> Result<(), ProtocolError> {
286        let payload = match reason {
287            None => Bytes::new(),
288            Some(reason) => {
289                if !reason.code.is_valid() || (!mask && matches!(reason.code, CloseCode::Extension))
290                {
291                    return Err(ProtocolError::InvalidCloseCode(reason.code.into()));
292                }
293                let mut payload =
294                    BytesMut::with_capacity(reason.description.as_ref().map_or(0, String::len) + 2);
295                payload.put_u16(u16::from(reason.code));
296                if let Some(description) = reason.description {
297                    payload.extend_from_slice(description.as_bytes());
298                }
299                payload.freeze()
300            }
301        };
302
303        Parser::write_message(dst, payload, OpCode::Close, true, mask)
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310
311    struct F {
312        finished: bool,
313        opcode: OpCode,
314        payload: Bytes,
315    }
316
317    fn is_none(frm: &Result<Option<(bool, OpCode, Option<Bytes>)>, ProtocolError>) -> bool {
318        matches!(*frm, Ok(None))
319    }
320
321    fn extract(frm: Result<Option<(bool, OpCode, Option<Bytes>)>, ProtocolError>) -> F {
322        match frm {
323            Ok(Some((finished, opcode, payload))) => F {
324                finished,
325                opcode,
326                payload: payload.unwrap_or_else(Bytes::new),
327            },
328            _ => unreachable!("error"),
329        }
330    }
331
332    /// STATEMENT: Frame parsing waits for payload bytes and preserves text opcode and fragmentation state.
333    ///
334    /// HOW:
335    /// - Parse an incomplete one-byte frame, append its payload, and inspect the decoded frame.
336    #[test]
337    fn test_parse() {
338        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]);
339        assert!(is_none(&Parser::parse(&mut buf, false, 1024)));
340
341        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]);
342        buf.extend(b"1");
343
344        let frame = extract(Parser::parse(&mut buf, false, 1024));
345        assert!(!frame.finished);
346        assert_eq!(frame.opcode, OpCode::Text);
347        assert_eq!(frame.payload.as_ref(), &b"1"[..]);
348    }
349
350    /// STATEMENT: Empty text fragments decode without requiring payload bytes.
351    ///
352    /// HOW:
353    /// - Parse a zero-length nonfinal text frame and check opcode, finality, and empty payload.
354    #[test]
355    fn test_parse_length0() {
356        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0000u8][..]);
357        let frame = extract(Parser::parse(&mut buf, false, 1024));
358        assert!(!frame.finished);
359        assert_eq!(frame.opcode, OpCode::Text);
360        assert!(frame.payload.is_empty());
361    }
362
363    /// STATEMENT: Unnegotiated reserved frame bits are rejected.
364    ///
365    /// HOW:
366    /// - Set each reserved bit and their combination on a text frame and inspect the reserved-bits error.
367    #[test]
368    fn test_reserved_bits() {
369        for reserved in [0x10, 0x20, 0x40, 0x70] {
370            let mut buf = BytesMut::from(&[0x81 | reserved, 0][..]);
371            assert!(matches!(
372                Parser::parse(&mut buf, false, 1024),
373                Err(ProtocolError::ReservedBits(_))
374            ));
375        }
376    }
377
378    /// STATEMENT: Control frames cannot be fragmented or exceed their payload limit.
379    ///
380    /// HOW:
381    /// - Parse a nonfinal ping and an oversized close header and compare specific protocol errors.
382    #[test]
383    fn test_invalid_control_frames() {
384        let mut fragmented = BytesMut::from(&[0x09, 0][..]);
385        assert!(matches!(
386            Parser::parse(&mut fragmented, false, 1024),
387            Err(ProtocolError::FragmentedControlFrame(OpCode::Ping))
388        ));
389
390        let mut oversized = BytesMut::from(&[0x88, 126, 0, 126][..]);
391        assert!(matches!(
392            Parser::parse(&mut oversized, false, 1024),
393            Err(ProtocolError::InvalidLength(126))
394        ));
395    }
396
397    /// STATEMENT: Two-byte extended frame lengths wait for complete input and decode the declared payload.
398    ///
399    /// HOW:
400    /// - Parse an incomplete extended header, then supply a 126-byte text payload and inspect the frame.
401    #[test]
402    fn test_parse_length2() {
403        let mut buf = BytesMut::from(&[0b0000_0001u8, 126u8][..]);
404        assert!(is_none(&Parser::parse(&mut buf, false, 1024)));
405
406        let mut buf = BytesMut::from(&[0b0000_0001u8, 126u8][..]);
407        buf.extend(&[0u8, 126u8][..]);
408        buf.extend(vec![1; 126]);
409
410        let frame = extract(Parser::parse(&mut buf, false, 1024));
411        assert!(!frame.finished);
412        assert_eq!(frame.opcode, OpCode::Text);
413        assert_eq!(frame.payload.len(), 126);
414    }
415
416    /// STATEMENT: Eight-byte extended frame lengths support payloads at the 64 KiB boundary.
417    ///
418    /// HOW:
419    /// - Check incomplete-length input returns no frame, then decode a complete 65,536-byte text fragment.
420    #[test]
421    fn test_parse_length4() {
422        let mut buf = BytesMut::from(&[0b0000_0001u8, 127u8][..]);
423        assert!(is_none(&Parser::parse(&mut buf, false, 1024)));
424
425        let mut buf = BytesMut::from(&[0b0000_0001u8, 127u8][..]);
426        buf.extend(&[0u8, 0u8, 0u8, 0u8, 0u8, 1u8, 0u8, 0u8][..]);
427        buf.extend(vec![1; 65_536]);
428
429        let frame = extract(Parser::parse(&mut buf, false, 65_536));
430        assert!(!frame.finished);
431        assert_eq!(frame.opcode, OpCode::Text);
432        assert_eq!(frame.payload.len(), 65_536);
433    }
434
435    /// STATEMENT: Frame length encodings must use the shortest legal representation and keep the high bit clear.
436    ///
437    /// HOW:
438    /// - Parse overlong short/medium lengths and a high-bit-set length and expect invalid-length-encoding errors.
439    #[test]
440    fn test_noncanonical_lengths() {
441        let mut short = BytesMut::from(&[0x82, 126, 0, 125][..]);
442        assert!(matches!(
443            Parser::parse(&mut short, false, usize::MAX),
444            Err(ProtocolError::InvalidLengthEncoding)
445        ));
446
447        let mut medium = BytesMut::from(&[0x82, 127, 0, 0, 0, 0, 0, 0, 0xff, 0xff][..]);
448        assert!(matches!(
449            Parser::parse(&mut medium, false, usize::MAX),
450            Err(ProtocolError::InvalidLengthEncoding)
451        ));
452
453        let mut high_bit = BytesMut::from(&[0x82, 127, 0x80, 0, 0, 0, 0, 1, 0, 0][..]);
454        assert!(matches!(
455            Parser::parse(&mut high_bit, false, usize::MAX),
456            Err(ProtocolError::InvalidLengthEncoding)
457        ));
458    }
459
460    /// STATEMENT: Masked frames are accepted only from clients and their payload is unmasked correctly.
461    ///
462    /// HOW:
463    /// - Reject a masked frame in client mode, then parse the unchanged buffer in server mode and inspect payload metadata.
464    #[test]
465    fn test_parse_frame_mask() {
466        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b1000_0001u8][..]);
467        buf.extend(b"0001");
468        buf.extend(b"1");
469
470        assert!(Parser::parse(&mut buf, false, 1024).is_err());
471
472        let frame = extract(Parser::parse(&mut buf, true, 1024));
473        assert!(!frame.finished);
474        assert_eq!(frame.opcode, OpCode::Text);
475        assert_eq!(frame.payload, Bytes::from(vec![1u8]));
476    }
477
478    /// STATEMENT: Unmasked frames are accepted only from servers.
479    ///
480    /// HOW:
481    /// - Reject an unmasked frame in server mode, then decode it in client mode and compare the text fragment.
482    #[test]
483    fn test_parse_frame_no_mask() {
484        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0001u8][..]);
485        buf.extend([1u8]);
486
487        assert!(Parser::parse(&mut buf, true, 1024).is_err());
488
489        let frame = extract(Parser::parse(&mut buf, false, 1024));
490        assert!(!frame.finished);
491        assert_eq!(frame.opcode, OpCode::Text);
492        assert_eq!(frame.payload, Bytes::from(vec![1u8]));
493    }
494
495    /// STATEMENT: Frame parsing rejects invalid masking and payload lengths above the configured maximum.
496    ///
497    /// HOW:
498    /// - Parse an unmasked payload under server rules, then enforce a zero-size client limit and inspect overflow.
499    #[test]
500    fn test_parse_frame_max_size() {
501        let mut buf = BytesMut::from(&[0b0000_0001u8, 0b0000_0010u8][..]);
502        buf.extend([1u8, 1u8]);
503
504        assert!(Parser::parse(&mut buf, true, 1).is_err());
505
506        if let Err(ProtocolError::Overflow) = Parser::parse(&mut buf, false, 0) {
507        } else {
508            unreachable!("error");
509        }
510    }
511
512    /// STATEMENT: Masked frame generation round-trips data and varies generated masking keys.
513    ///
514    /// HOW:
515    /// - Encode and decode the same binary payload several times, checking finality, opcode, and bytes.
516    /// - Compare captured mask keys and verify they are not all identical.
517    #[test]
518    fn test_masked_frames_roundtrip_with_distinct_masks() {
519        let mut masks = Vec::new();
520        for _ in 0..4 {
521            let mut pages = BytePages::default();
522            Parser::write_message(&mut pages, Bytes::from("data"), OpCode::Binary, true, true)
523                .unwrap();
524            let mut buf = BytesMut::from(&Bytes::from(pages)[..]);
525            masks.push(buf[2..6].to_vec());
526
527            let frame = extract(Parser::parse(&mut buf, true, 1024));
528            assert!(frame.finished);
529            assert_eq!(frame.opcode, OpCode::Binary);
530            assert_eq!(frame.payload, Bytes::from("data"));
531        }
532        masks.dedup();
533        assert!(masks.len() > 1);
534    }
535
536    /// STATEMENT: Ping encoding produces the final control opcode and exact payload length.
537    ///
538    /// HOW:
539    /// - Encode an unmasked ping and compare its entire wire frame.
540    #[test]
541    fn test_ping_frame() {
542        let mut buf = BytePages::default();
543        Parser::write_message(&mut buf, Bytes::from("data"), OpCode::Ping, true, false).unwrap();
544
545        let mut v = vec![137u8, 4u8];
546        v.extend(b"data");
547        assert_eq!(&Bytes::from(buf)[..], &v[..]);
548    }
549
550    /// STATEMENT: Pong encoding produces the final control opcode and exact payload length.
551    ///
552    /// HOW:
553    /// - Encode an unmasked pong and compare its entire wire frame.
554    #[test]
555    fn test_pong_frame() {
556        let mut buf = BytePages::default();
557        Parser::write_message(&mut buf, Bytes::from("data"), OpCode::Pong, true, false).unwrap();
558
559        let mut v = vec![138u8, 4u8];
560        v.extend(b"data");
561        assert_eq!(&Bytes::from(buf)[..], &v[..]);
562    }
563
564    /// STATEMENT: Close encoding includes a network-order status code followed by the reason text.
565    ///
566    /// HOW:
567    /// - Encode a normal close with a description and compare all header and payload bytes.
568    #[test]
569    fn test_close_frame() {
570        let mut buf = BytePages::default();
571        let reason = (CloseCode::Normal, "data");
572        Parser::write_close(&mut buf, Some(reason.into()), false).unwrap();
573
574        let mut v = vec![136u8, 6u8, 3u8, 232u8];
575        v.extend(b"data");
576        assert_eq!(&Bytes::from(buf)[..], &v[..]);
577    }
578
579    /// STATEMENT: A close without a reason encodes as an empty final control frame.
580    ///
581    /// HOW:
582    /// - Encode a reasonless close and compare its two wire bytes.
583    #[test]
584    fn test_empty_close_frame() {
585        let mut buf = BytePages::default();
586        Parser::write_close(&mut buf, None, false).unwrap();
587        assert_eq!(&Bytes::from(buf)[..], &[0x88, 0x00]);
588    }
589
590    /// STATEMENT: Close parsing and control-frame encoding reject malformed payloads, invalid codes, and illegal framing.
591    ///
592    /// HOW:
593    /// - Reject one-byte close data, reserved status, invalid UTF-8, oversized ping, and fragmented pong.
594    /// - Reject invalid/server-forbidden close codes and a reason exceeding the control payload limit.
595    #[test]
596    fn test_close_validation() {
597        assert!(matches!(
598            Parser::parse_close_payload(&[1]),
599            Err(ProtocolError::InvalidClosePayload)
600        ));
601        assert!(matches!(
602            Parser::parse_close_payload(&1006u16.to_be_bytes()),
603            Err(ProtocolError::InvalidCloseCode(1006))
604        ));
605        assert!(matches!(
606            Parser::parse_close_payload(&[0x03, 0xe8, 0xff]),
607            Err(ProtocolError::InvalidUtf8)
608        ));
609
610        let mut buf = BytePages::default();
611        assert!(matches!(
612            Parser::write_message(
613                &mut buf,
614                Bytes::from(vec![0; 126]),
615                OpCode::Ping,
616                true,
617                false
618            ),
619            Err(ProtocolError::InvalidLength(126))
620        ));
621        assert!(matches!(
622            Parser::write_message(&mut buf, Bytes::new(), OpCode::Pong, false, false),
623            Err(ProtocolError::FragmentedControlFrame(OpCode::Pong))
624        ));
625        assert!(matches!(
626            Parser::write_close(
627                &mut buf,
628                Some(CloseReason {
629                    code: CloseCode::Other(2000),
630                    description: None,
631                }),
632                false
633            ),
634            Err(ProtocolError::InvalidCloseCode(2000))
635        ));
636        assert!(matches!(
637            Parser::write_close(
638                &mut buf,
639                Some(CloseReason {
640                    code: CloseCode::Extension,
641                    description: None,
642                }),
643                false
644            ),
645            Err(ProtocolError::InvalidCloseCode(1010))
646        ));
647        assert!(matches!(
648            Parser::write_close(
649                &mut buf,
650                Some(CloseReason {
651                    code: CloseCode::Normal,
652                    description: Some("x".repeat(124)),
653                }),
654                false
655            ),
656            Err(ProtocolError::InvalidLength(126))
657        ));
658    }
659
660    /// STATEMENT: Frame parsing handles extended-length overflow, partial masks, and optional close reasons.
661    ///
662    /// HOW:
663    /// - Reject a length above the configured maximum and wait on an incomplete mask key.
664    /// - Parse empty and populated close payloads and compare reason fields.
665    #[test]
666    fn test_parse_edge_cases() {
667        // 64-bit length over the max size
668        let mut buf = BytesMut::from(&[0x82u8, 127, 0, 0, 0, 0, 0, 1, 0, 0][..]);
669        assert!(matches!(
670            Parser::parse(&mut buf, false, 65_535),
671            Err(ProtocolError::Overflow)
672        ));
673
674        // masking key is not received yet
675        let mut buf = BytesMut::from(&[0x82u8, 0x81, 1, 2][..]);
676        assert!(is_none(&Parser::parse(&mut buf, true, 1024)));
677
678        assert!(Parser::parse_close_payload(&[]).unwrap().is_none());
679        let reason = Parser::parse_close_payload(&[0x03, 0xe8, b'o', b'k'])
680            .unwrap()
681            .unwrap();
682        assert_eq!(reason.code, CloseCode::Normal);
683        assert_eq!(reason.description.as_deref(), Some("ok"));
684    }
685
686    /// STATEMENT: Large binary frames use extended length encoding without altering payload bytes.
687    ///
688    /// HOW:
689    /// - Encode a 70,000-byte frame, inspect its length discriminator, and decode it back to the original payload.
690    #[test]
691    fn test_large_frame_roundtrip() {
692        let payload = Bytes::from(vec![7u8; 70_000]);
693        let mut buf = BytePages::default();
694        Parser::write_message(&mut buf, payload.clone(), OpCode::Binary, true, false).unwrap();
695
696        let mut buf = BytesMut::from(&Bytes::from(buf)[..]);
697        assert_eq!(&buf[..2], &[0x82, 127]);
698        let frame = extract(Parser::parse(&mut buf, false, 100_000));
699        assert!(frame.finished);
700        assert_eq!(frame.opcode, OpCode::Binary);
701        assert_eq!(frame.payload, payload);
702    }
703}