Skip to main content

http_type/websocket_frame/
impl.rs

1use super::*;
2
3/// Implements the `Default` trait for `WebSocketFrame`.
4///
5/// Provides a default `WebSocketFrame` with `fin: false`, `opcode: WebSocketOpcode::Text`,
6/// `mask: false`, and an empty `payload_data`.
7impl Default for WebSocketFrame {
8    /// Returns the default `WebSocketFrame`.
9    ///
10    /// # Returns
11    ///
12    /// - `Self` - A default `WebSocketFrame` instance.
13    #[inline(always)]
14    fn default() -> Self {
15        Self {
16            fin: false,
17            opcode: WebSocketOpcode::Text,
18            mask: false,
19            payload_data: Vec::new(),
20        }
21    }
22}
23
24/// Inherent implementation of [`WebSocketOpcode`].
25impl WebSocketOpcode {
26    /// Creates a `WebSocketOpcode` from a raw u8 value.
27    ///
28    /// # Arguments
29    ///
30    /// - `u8` - The raw opcode value.
31    ///
32    /// # Returns
33    ///
34    /// - `Self` - A `WebSocketOpcode` enum variant corresponding to the raw value.
35    #[inline(always)]
36    pub fn from_u8(opcode: u8) -> Self {
37        match opcode {
38            0x0 => Self::Continuation,
39            0x1 => Self::Text,
40            0x2 => Self::Binary,
41            0x8 => Self::Close,
42            0x9 => Self::Ping,
43            0xA => Self::Pong,
44            _ => Self::Reserved(opcode),
45        }
46    }
47
48    /// Converts the `WebSocketOpcode` to its raw u8 value.
49    ///
50    /// # Returns
51    ///
52    /// - `u8` - The raw u8 value of the opcode.
53    #[inline(always)]
54    pub fn to_u8(&self) -> u8 {
55        match self {
56            Self::Continuation => 0x0,
57            Self::Text => 0x1,
58            Self::Binary => 0x2,
59            Self::Close => 0x8,
60            Self::Ping => 0x9,
61            Self::Pong => 0xA,
62            Self::Reserved(code) => *code,
63        }
64    }
65
66    /// Checks if the opcode is a control frame.
67    ///
68    /// # Returns
69    ///
70    /// - `bool` - `true` if the opcode represents a control frame (Close, Ping, Pong), otherwise `false`.
71    #[inline(always)]
72    pub fn is_control(&self) -> bool {
73        matches!(self, Self::Close | Self::Ping | Self::Pong)
74    }
75
76    /// Checks if the opcode is a data frame.
77    ///
78    /// # Returns
79    ///
80    /// - `bool` - `true` if the opcode represents a data frame (Text, Binary, Continuation), otherwise `false`.
81    #[inline(always)]
82    pub fn is_data(&self) -> bool {
83        matches!(self, Self::Text | Self::Binary | Self::Continuation)
84    }
85
86    /// Checks if the opcode is a continuation frame.
87    ///
88    /// # Returns
89    ///
90    /// - `bool` - `true` if the opcode is `Continuation`, otherwise `false`.
91    #[inline(always)]
92    pub fn is_continuation(&self) -> bool {
93        matches!(self, Self::Continuation)
94    }
95
96    /// Checks if the opcode is a text frame.
97    ///
98    /// # Returns
99    ///
100    /// - `bool` - `true` if the opcode is `Text`, otherwise `false`.
101    #[inline(always)]
102    pub fn is_text(&self) -> bool {
103        matches!(self, Self::Text)
104    }
105
106    /// Checks if the opcode is a binary frame.
107    ///
108    /// # Returns
109    ///
110    /// - `bool` - `true` if the opcode is `Binary`, otherwise `false`.
111    #[inline(always)]
112    pub fn is_binary(&self) -> bool {
113        matches!(self, Self::Binary)
114    }
115
116    /// Checks if the opcode is a close frame.
117    ///
118    /// # Returns
119    ///
120    /// - `bool` - `true` if the opcode is `Close`, otherwise `false`.
121    #[inline(always)]
122    pub fn is_close(&self) -> bool {
123        matches!(self, Self::Close)
124    }
125
126    /// Checks if the opcode is a ping frame.
127    ///
128    /// # Returns
129    ///
130    /// - `bool` - `true` if the opcode is `Ping`, otherwise `false`.
131    #[inline(always)]
132    pub fn is_ping(&self) -> bool {
133        matches!(self, Self::Ping)
134    }
135
136    /// Checks if the opcode is a pong frame.
137    ///
138    /// # Returns
139    ///
140    /// - `bool` - `true` if the opcode is `Pong`, otherwise `false`.
141    #[inline(always)]
142    pub fn is_pong(&self) -> bool {
143        matches!(self, Self::Pong)
144    }
145
146    /// Checks if the opcode is a reserved frame.
147    ///
148    /// # Returns
149    ///
150    /// - `bool` - `true` if the opcode is `Reserved(_)`, otherwise `false`.
151    #[inline(always)]
152    pub fn is_reserved(&self) -> bool {
153        matches!(self, Self::Reserved(_))
154    }
155}
156
157/// Inherent implementation of [`WebSocketFrame`].
158impl WebSocketFrame {
159    /// Decodes a WebSocket frame from the provided data slice.
160    ///
161    /// This function parses the raw bytes from a WebSocket stream according to the WebSocket protocol
162    /// specification to reconstruct a `WebSocketFrame`. It handles FIN bit, opcode, mask bit,
163    /// payload length (including extended lengths), mask key, and the payload data itself.
164    ///
165    /// # Arguments
166    ///
167    /// - `D` - The raw data to decode into a WebSocket frame, which requires the `AsRef<[u8]>` bound.
168    ///
169    /// # Returns
170    ///
171    /// - `Option<(WebSocketFrame, usize)>` - `Some((frame, consumed))` when the frame is
172    ///   successfully decoded, otherwise `None` when the frame is incomplete or malformed.
173    pub fn decode_ws_frame<D>(data: D) -> Option<(WebSocketFrame, usize)>
174    where
175        D: AsRef<[u8]>,
176    {
177        let data_ref: &[u8] = data.as_ref();
178        if data_ref.len() < 2 {
179            return None;
180        }
181        let mut index: usize = 0;
182        let fin: bool = (data_ref[index] & 0b1000_0000) != 0;
183        let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(data_ref[index] & 0b0000_1111);
184        index += 1;
185        let mask: bool = (data_ref[index] & 0b1000_0000) != 0;
186        let mut payload_len: usize = (data_ref[index] & 0b0111_1111) as usize;
187        index += 1;
188        if payload_len == 126 {
189            if data_ref.len() < index + 2 {
190                return None;
191            }
192            payload_len = u16::from_be_bytes(data_ref[index..index + 2].try_into().ok()?) as usize;
193            index += 2;
194        } else if payload_len == 127 {
195            if data_ref.len() < index + 8 {
196                return None;
197            }
198            let raw_len: u64 = u64::from_be_bytes(data_ref[index..index + 8].try_into().ok()?);
199            if (raw_len >> 63) != 0 {
200                return None;
201            }
202            payload_len = usize::try_from(raw_len).ok()?;
203            index += 8;
204        }
205        let mask_key: Option<[u8; 4]> = if mask {
206            if data_ref.len() < index + 4 {
207                return None;
208            }
209            let key: [u8; 4] = data_ref[index..index + 4].try_into().ok()?;
210            index += 4;
211            Some(key)
212        } else {
213            None
214        };
215        let total_len: usize = index.checked_add(payload_len)?;
216        if data_ref.len() < total_len {
217            return None;
218        }
219        let mut payload: Vec<u8> = data_ref[index..total_len].to_vec();
220        if let Some(mask_key) = mask_key {
221            Self::apply_mask(&mut payload, mask_key);
222        }
223        let frame: WebSocketFrame = WebSocketFrame {
224            fin,
225            opcode,
226            mask,
227            payload_data: payload,
228        };
229        Some((frame, total_len))
230    }
231
232    /// Decodes and validates one WebSocket frame against RFC 6455 rules and a payload size cap.
233    ///
234    /// Unlike [`Self::decode_ws_frame`], this method rejects protocol violations immediately
235    /// instead of waiting for more bytes, preventing memory exhaustion on oversized or
236    /// malformed headers.
237    ///
238    /// # Arguments
239    ///
240    /// - `&[u8]` - The buffered unread wire bytes.
241    /// - `usize` - The maximum permitted payload length in bytes.
242    ///
243    /// # Returns
244    ///
245    /// - `Result<Option<(WebSocketFrame, usize)>, RequestError>` - A decoded frame and consumed
246    ///   byte count, `Ok(None)` when more wire bytes are needed, or a protocol error.
247    pub(crate) fn decode_ws_frame_checked(
248        data_ref: &[u8],
249        max_payload_size: usize,
250    ) -> Result<Option<(WebSocketFrame, usize)>, RequestError> {
251        if data_ref.len() < 2 {
252            return Ok(None);
253        }
254        let first_byte: u8 = data_ref[0];
255        let second_byte: u8 = data_ref[1];
256        if (first_byte & 0b0111_0000) != 0 {
257            return Err(RequestError::WebSocketInvalidExtension(
258                HttpStatus::BadRequest,
259            ));
260        }
261        let fin: bool = (first_byte & 0b1000_0000) != 0;
262        let opcode: WebSocketOpcode = WebSocketOpcode::from_u8(first_byte & 0b0000_1111);
263        if opcode.is_reserved() {
264            return Err(RequestError::WebSocketOpcodeUnsupported(
265                HttpStatus::NotImplemented,
266            ));
267        }
268        let mask: bool = (second_byte & 0b1000_0000) != 0;
269        let len_code: u8 = second_byte & 0b0111_1111;
270        if opcode.is_control() && (!fin || len_code >= 126) {
271            return Err(RequestError::WebSocketPayloadCorrupted(
272                HttpStatus::BadRequest,
273            ));
274        }
275        let mut index: usize = 2;
276        let payload_len: usize = if len_code == 126 {
277            if data_ref.len() < index + 2 {
278                return Ok(None);
279            }
280            let raw_len: u16 = u16::from_be_bytes([data_ref[index], data_ref[index + 1]]);
281            if raw_len < 126 {
282                return Err(RequestError::WebSocketPayloadCorrupted(
283                    HttpStatus::BadRequest,
284                ));
285            }
286            index += 2;
287            usize::from(raw_len)
288        } else if len_code == 127 {
289            if data_ref.len() < index + 8 {
290                return Ok(None);
291            }
292            let raw_len: u64 = u64::from_be_bytes([
293                data_ref[index],
294                data_ref[index + 1],
295                data_ref[index + 2],
296                data_ref[index + 3],
297                data_ref[index + 4],
298                data_ref[index + 5],
299                data_ref[index + 6],
300                data_ref[index + 7],
301            ]);
302            if (raw_len >> 63) != 0 || raw_len <= u64::from(u16::MAX) {
303                return Err(RequestError::WebSocketPayloadCorrupted(
304                    HttpStatus::BadRequest,
305                ));
306            }
307            index += 8;
308            usize::try_from(raw_len)
309                .map_err(|_| RequestError::WebSocketFrameTooLarge(HttpStatus::PayloadTooLarge))?
310        } else {
311            usize::from(len_code)
312        };
313        if max_payload_size != DEFAULT_LOW_SECURITY_MAX_BODY_SIZE && payload_len > max_payload_size
314        {
315            return Err(RequestError::WebSocketFrameTooLarge(
316                HttpStatus::PayloadTooLarge,
317            ));
318        }
319        let mask_key: Option<[u8; 4]> = if mask {
320            if data_ref.len() < index + 4 {
321                return Ok(None);
322            }
323            let key: [u8; 4] = [
324                data_ref[index],
325                data_ref[index + 1],
326                data_ref[index + 2],
327                data_ref[index + 3],
328            ];
329            index += 4;
330            Some(key)
331        } else {
332            None
333        };
334        let total_len: usize =
335            index
336                .checked_add(payload_len)
337                .ok_or(RequestError::WebSocketFrameTooLarge(
338                    HttpStatus::PayloadTooLarge,
339                ))?;
340        if data_ref.len() < total_len {
341            return Ok(None);
342        }
343        let mut payload: Vec<u8> = data_ref[index..total_len].to_vec();
344        if let Some(mask_key) = mask_key {
345            Self::apply_mask(&mut payload, mask_key);
346        }
347        let frame: WebSocketFrame = WebSocketFrame {
348            fin,
349            opcode,
350            mask,
351            payload_data: payload,
352        };
353        Ok(Some((frame, total_len)))
354    }
355
356    /// Applies a 4-byte RFC 6455 XOR mask to a payload slice in place.
357    ///
358    /// # Arguments
359    ///
360    /// - `&mut [u8]` - The payload bytes to mask or unmask.
361    /// - `[u8; 4]` - The 4-byte masking key.
362    #[inline(always)]
363    fn apply_mask(payload: &mut [u8], mask_key: [u8; 4]) {
364        let mask_u32: u32 = u32::from_ne_bytes(mask_key);
365        let (chunks, remainder): (&mut [[u8; 4]], &mut [u8]) = payload.as_chunks_mut::<4>();
366        for chunk in chunks {
367            let word: u32 = u32::from_ne_bytes(*chunk) ^ mask_u32;
368            *chunk = word.to_ne_bytes();
369        }
370        for (idx, byte) in remainder.iter_mut().enumerate() {
371            *byte ^= mask_key[idx];
372        }
373    }
374
375    /// Creates a list of response frames from the provided body.
376    ///
377    /// This method segments the response body into WebSocket frames, respecting the maximum frame size
378    /// and handling UTF-8 character boundaries for text frames. It determines the appropriate opcode
379    /// (Text or Binary) based on the body's content.
380    ///
381    /// # Arguments
382    ///
383    /// - `D` - A reference to a response body (payload) as a byte slice, which requires the
384    ///   `AsRef<[u8]>` bound.
385    ///
386    /// # Returns
387    ///
388    /// - `Vec<ResponseBody>` - A vector of `ResponseBody` (byte vectors), where each element represents a framed WebSocket message.
389    pub fn create_frame_list<D>(data: D) -> Vec<ResponseBody>
390    where
391        D: AsRef<[u8]>,
392    {
393        let data_ref: &[u8] = data.as_ref();
394        let total_len: usize = data_ref.len();
395        if total_len == 0 {
396            return vec![vec![0x81, 0x00]];
397        }
398        let mut offset: usize = 0;
399        let mut frames_list: Vec<ResponseBody> =
400            Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
401        let mut is_first_frame: bool = true;
402        let is_valid_utf8: bool = from_utf8(data_ref).is_ok();
403        let base_opcode: WebSocketOpcode = if is_valid_utf8 {
404            WebSocketOpcode::Text
405        } else {
406            WebSocketOpcode::Binary
407        };
408        while offset < total_len {
409            let remaining: usize = total_len - offset;
410            let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
411            if is_valid_utf8 && frame_size < remaining {
412                while frame_size > 0 && (data_ref[offset + frame_size] & 0xC0) == 0x80 {
413                    frame_size -= 1;
414                }
415                if frame_size == 0 {
416                    frame_size = remaining.min(MAX_FRAME_SIZE);
417                }
418            }
419            let mut frame: ResponseBody = Vec::with_capacity(frame_size + 10);
420            let opcode: WebSocketOpcode = if is_first_frame {
421                base_opcode
422            } else {
423                WebSocketOpcode::Continuation
424            };
425            let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
426            let opcode_byte: u8 = opcode.to_u8() & 0x0F;
427            frame.push(fin | opcode_byte);
428            if frame_size < 126 {
429                frame.push(frame_size as u8);
430            } else if frame_size <= usize::from(u16::MAX) {
431                frame.push(126);
432                frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
433            } else {
434                frame.push(127);
435                frame.extend_from_slice(&(frame_size as u64).to_be_bytes());
436            }
437            let end: usize = offset + frame_size;
438            frame.extend_from_slice(&data_ref[offset..end]);
439            frames_list.push(frame);
440            offset = end;
441            is_first_frame = false;
442        }
443        frames_list
444    }
445
446    /// Calculates the SHA-1 hash of the input data.
447    ///
448    /// This function implements the SHA-1 cryptographic hash algorithm according to RFC 3174.
449    /// It processes the input data in 512-bit (64-byte) blocks and produces a 160-bit (20-byte) hash.
450    ///
451    /// # Arguments
452    ///
453    /// - `D` - The input data to be hashed, which requires the `AsRef<[u8]>` bound.
454    ///
455    /// # Returns
456    ///
457    /// A 20-byte array representing the SHA-1 hash of the input data.
458    pub fn sha1<D>(data: D) -> [u8; 20]
459    where
460        D: AsRef<[u8]>,
461    {
462        let data_ref: &[u8] = data.as_ref();
463        let mut hash_state: [u32; 5] = HASH_STATE;
464        let mut padded_data: Vec<u8> = Vec::from(data_ref);
465        let original_size_bits: u64 = (padded_data.len() * 8) as u64;
466        padded_data.push(0x80);
467        while !(padded_data.len() + 8).is_multiple_of(64) {
468            padded_data.push(0);
469        }
470        padded_data.extend_from_slice(&original_size_bits.to_be_bytes());
471        for block in padded_data.as_chunks::<64>().0 {
472            let mut message_schedule: [u32; 80] = [0u32; 80];
473            for (chunk_index, block_chunk) in block.as_chunks::<4>().0.iter().enumerate().take(16) {
474                message_schedule[chunk_index] = u32::from_be_bytes([
475                    block_chunk[0],
476                    block_chunk[1],
477                    block_chunk[2],
478                    block_chunk[3],
479                ]);
480            }
481            for schedule_index in 16..80 {
482                message_schedule[schedule_index] = (message_schedule[schedule_index - 3]
483                    ^ message_schedule[schedule_index - 8]
484                    ^ message_schedule[schedule_index - 14]
485                    ^ message_schedule[schedule_index - 16])
486                    .rotate_left(1);
487            }
488            let [mut hash_a, mut hash_b, mut hash_c, mut hash_d, mut hash_e] = hash_state;
489            for (round_index, &schedule_word) in message_schedule.iter().enumerate() {
490                let (round_function, round_constant): (u32, u32) = match round_index {
491                    0..=19 => ((hash_b & hash_c) | (!hash_b & hash_d), 0x5A827999),
492                    20..=39 => (hash_b ^ hash_c ^ hash_d, 0x6ED9EBA1),
493                    40..=59 => (
494                        (hash_b & hash_c) | (hash_b & hash_d) | (hash_c & hash_d),
495                        0x8F1BBCDC,
496                    ),
497                    _ => (hash_b ^ hash_c ^ hash_d, 0xCA62C1D6),
498                };
499                let temp: u32 = hash_a
500                    .rotate_left(5)
501                    .wrapping_add(round_function)
502                    .wrapping_add(hash_e)
503                    .wrapping_add(round_constant)
504                    .wrapping_add(schedule_word);
505                hash_e = hash_d;
506                hash_d = hash_c;
507                hash_c = hash_b.rotate_left(30);
508                hash_b = hash_a;
509                hash_a = temp;
510            }
511            hash_state[0] = hash_state[0].wrapping_add(hash_a);
512            hash_state[1] = hash_state[1].wrapping_add(hash_b);
513            hash_state[2] = hash_state[2].wrapping_add(hash_c);
514            hash_state[3] = hash_state[3].wrapping_add(hash_d);
515            hash_state[4] = hash_state[4].wrapping_add(hash_e);
516        }
517        let mut result: [u8; 20] = [0u8; 20];
518        for (state_index, &state_value) in hash_state.iter().enumerate() {
519            result[state_index * 4..(state_index + 1) * 4]
520                .copy_from_slice(&state_value.to_be_bytes());
521        }
522        result
523    }
524
525    /// Generates a WebSocket accept key from the client-provided key, returning an `Option<String>`.
526    ///
527    /// # Arguments
528    ///
529    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
530    ///   requires the `AsRef<str>` bound.
531    ///
532    /// # Returns
533    ///
534    /// - `Option<String>` - An optional string representing the generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
535    #[inline(always)]
536    pub fn try_generate_accept_key<K>(key: K) -> Option<String>
537    where
538        K: AsRef<str>,
539    {
540        let key_bytes: &[u8] = key.as_ref().as_bytes();
541        if key_bytes.len() != 24
542            || key_bytes[22] != b'='
543            || key_bytes[23] != b'='
544            || !key_bytes[..22]
545                .iter()
546                .all(|byte: &u8| byte.is_ascii_alphanumeric() || *byte == b'+' || *byte == b'/')
547        {
548            return None;
549        }
550        let mut data: [u8; 60] = [0u8; 60];
551        data[..24].copy_from_slice(key_bytes);
552        data[24..].copy_from_slice(GUID);
553        let hash: [u8; 20] = Self::sha1(data);
554        Self::try_base64_encode(hash)
555    }
556
557    /// Generates a WebSocket accept key from the client-provided key.
558    ///
559    /// This function is used during the WebSocket handshake to validate the client's request.
560    /// It concatenates the client's key with a specific GUID, calculates the SHA-1 hash of the result,
561    /// and then encodes the hash in base64.
562    ///
563    /// # Arguments
564    ///
565    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
566    ///   requires the `AsRef<str>` bound.
567    ///
568    /// # Returns
569    ///
570    /// - `String` - The generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
571    #[inline(always)]
572    pub fn generate_accept_key<K>(key: K) -> String
573    where
574        K: AsRef<str>,
575    {
576        let key_bytes: &[u8] = key.as_ref().as_bytes();
577        if key_bytes.len() <= 24 {
578            let mut data: [u8; 60] = [0u8; 60];
579            let key_len: usize = key_bytes.len();
580            data[..key_len].copy_from_slice(key_bytes);
581            data[key_len..key_len + GUID.len()].copy_from_slice(GUID);
582            let hash: [u8; 20] = Self::sha1(&data[..key_len + GUID.len()]);
583            return Self::base64_encode(hash);
584        }
585        let mut data: Vec<u8> = Vec::with_capacity(key_bytes.len() + GUID.len());
586        data.extend_from_slice(key_bytes);
587        data.extend_from_slice(GUID);
588        let hash: [u8; 20] = Self::sha1(&data);
589        Self::base64_encode(hash)
590    }
591
592    /// Encodes the input data as a base64 string, returning an `Option<String>`.
593    ///
594    /// # Arguments
595    ///
596    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
597    ///
598    /// # Returns
599    ///
600    /// - `Option<String>` - An optional string with the base64 encoded representation of the input data.
601    pub fn try_base64_encode<D>(data: D) -> Option<String>
602    where
603        D: AsRef<[u8]>,
604    {
605        let data_ref: &[u8] = data.as_ref();
606        let mut encoded_data: Vec<u8> = Vec::with_capacity(data_ref.len().div_ceil(3) * 4);
607        for chunk in data_ref.chunks(3) {
608            let mut buffer: [u8; 3] = [0u8; 3];
609            buffer[..chunk.len()].copy_from_slice(chunk);
610            let indices: [u8; 4] = [
611                buffer[0] >> 2,
612                ((buffer[0] & 0b11) << 4) | (buffer[1] >> 4),
613                ((buffer[1] & 0b1111) << 2) | (buffer[2] >> 6),
614                buffer[2] & 0b111111,
615            ];
616            for &idx in &indices[..chunk.len() + 1] {
617                encoded_data.push(BASE64_CHARSET_TABLE[idx as usize]);
618            }
619            while !encoded_data.len().is_multiple_of(4) {
620                encoded_data.push(EQUAL_BYTES[0]);
621            }
622        }
623        String::from_utf8(encoded_data).ok()
624    }
625
626    /// Encodes the input data as a base64 string.
627    ///
628    /// # Arguments
629    ///
630    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
631    ///
632    /// # Returns
633    ///
634    /// - `String` - A string with the base64 encoded representation of the input data.
635    ///
636    /// # Panics
637    ///
638    /// This function will panic if the input data cannot be converted to a UTF-8 string.
639    #[inline(always)]
640    pub fn base64_encode<D>(data: D) -> String
641    where
642        D: AsRef<[u8]>,
643    {
644        Self::try_base64_encode(data).unwrap()
645    }
646
647    /// Checks if the opcode is a continuation frame.
648    ///
649    /// # Returns
650    ///
651    /// - `bool` - `true` if the opcode is `Continuation`, otherwise `false`.
652    #[inline(always)]
653    pub fn is_continuation_opcode(&self) -> bool {
654        self.get_opcode().is_continuation()
655    }
656
657    /// Checks if the opcode is a text frame.
658    ///
659    /// # Returns
660    ///
661    /// - `bool` - `true` if the opcode is `Text`, otherwise `false`.
662    #[inline(always)]
663    pub fn is_text_opcode(&self) -> bool {
664        self.get_opcode().is_text()
665    }
666
667    /// Checks if the opcode is a binary frame.
668    ///
669    /// # Returns
670    ///
671    /// - `bool` - `true` if the opcode is `Binary`, otherwise `false`.
672    #[inline(always)]
673    pub fn is_binary_opcode(&self) -> bool {
674        self.get_opcode().is_binary()
675    }
676
677    /// Checks if the opcode is a close frame.
678    ///
679    /// # Returns
680    ///
681    /// - `bool` - `true` if the opcode is `Close`, otherwise `false`.
682    #[inline(always)]
683    pub fn is_close_opcode(&self) -> bool {
684        self.get_opcode().is_close()
685    }
686
687    /// Checks if the opcode is a ping frame.
688    ///
689    /// # Returns
690    ///
691    /// - `bool` - `true` if the opcode is `Ping`, otherwise `false`.
692    #[inline(always)]
693    pub fn is_ping_opcode(&self) -> bool {
694        self.get_opcode().is_ping()
695    }
696
697    /// Checks if the opcode is a pong frame.
698    ///
699    /// # Returns
700    ///
701    /// - `bool` - `true` if the opcode is `Pong`, otherwise `false`.
702    #[inline(always)]
703    pub fn is_pong_opcode(&self) -> bool {
704        self.get_opcode().is_pong()
705    }
706
707    /// Checks if the opcode is a reserved frame.
708    ///
709    /// # Returns
710    ///
711    /// - `bool` - `true` if the opcode is `Reserved(_)`, otherwise `false`.
712    #[inline(always)]
713    pub fn is_reserved_opcode(&self) -> bool {
714        self.get_opcode().is_reserved()
715    }
716}