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<Vec<u8>>` - A vector of `Vec<u8>` (byte vectors), where each element represents a framed WebSocket message.
389    pub fn create_frame_list<D>(data: D) -> Vec<Vec<u8>>
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<Vec<u8>> = Vec::with_capacity((total_len / MAX_FRAME_SIZE) + 1);
400        let mut is_first_frame: bool = true;
401        let is_valid_utf8: bool = from_utf8(data_ref).is_ok();
402        let base_opcode: WebSocketOpcode = if is_valid_utf8 {
403            WebSocketOpcode::Text
404        } else {
405            WebSocketOpcode::Binary
406        };
407        while offset < total_len {
408            let remaining: usize = total_len - offset;
409            let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
410            if is_valid_utf8 && frame_size < remaining {
411                while frame_size > 0 && (data_ref[offset + frame_size] & 0xC0) == 0x80 {
412                    frame_size -= 1;
413                }
414                if frame_size == 0 {
415                    frame_size = remaining.min(MAX_FRAME_SIZE);
416                }
417            }
418            let mut frame: Vec<u8> = Vec::with_capacity(frame_size + 10);
419            let opcode: WebSocketOpcode = if is_first_frame {
420                base_opcode
421            } else {
422                WebSocketOpcode::Continuation
423            };
424            let fin: u8 = if remaining > frame_size { 0x00 } else { 0x80 };
425            let opcode_byte: u8 = opcode.to_u8() & 0x0F;
426            frame.push(fin | opcode_byte);
427            if frame_size < 126 {
428                frame.push(frame_size as u8);
429            } else if frame_size <= usize::from(u16::MAX) {
430                frame.push(126);
431                frame.extend_from_slice(&(frame_size as u16).to_be_bytes());
432            } else {
433                frame.push(127);
434                frame.extend_from_slice(&(frame_size as u64).to_be_bytes());
435            }
436            let end: usize = offset + frame_size;
437            frame.extend_from_slice(&data_ref[offset..end]);
438            frames_list.push(frame);
439            offset = end;
440            is_first_frame = false;
441        }
442        frames_list
443    }
444
445    /// Compresses one 64-byte SHA-1 block into `hash_state`.
446    ///
447    /// # Arguments
448    ///
449    /// - `&mut [u32; 5]` - Running SHA-1 state words.
450    /// - `&[u8; 64]` - One 512-bit input block.
451    #[inline(always)]
452    fn sha1_compress_block(hash_state: &mut [u32; 5], block: &[u8; 64]) {
453        let mut message_schedule: [u32; 80] = [0u32; 80];
454        let (words, _): (&[[u8; 4]], &[u8]) = block.as_chunks::<4>();
455        for (chunk_index, block_chunk) in words.iter().enumerate() {
456            message_schedule[chunk_index] = u32::from_be_bytes(*block_chunk);
457        }
458        for schedule_index in 16..80 {
459            message_schedule[schedule_index] = (message_schedule[schedule_index - 3]
460                ^ message_schedule[schedule_index - 8]
461                ^ message_schedule[schedule_index - 14]
462                ^ message_schedule[schedule_index - 16])
463                .rotate_left(1);
464        }
465        let [mut hash_a, mut hash_b, mut hash_c, mut hash_d, mut hash_e] = *hash_state;
466        for &schedule_word in &message_schedule[0..20] {
467            let round_function: u32 = (hash_b & hash_c) | (!hash_b & hash_d);
468            let temp: u32 = hash_a
469                .rotate_left(5)
470                .wrapping_add(round_function)
471                .wrapping_add(hash_e)
472                .wrapping_add(0x5A82_7999)
473                .wrapping_add(schedule_word);
474            hash_e = hash_d;
475            hash_d = hash_c;
476            hash_c = hash_b.rotate_left(30);
477            hash_b = hash_a;
478            hash_a = temp;
479        }
480        for &schedule_word in &message_schedule[20..40] {
481            let round_function: u32 = hash_b ^ hash_c ^ hash_d;
482            let temp: u32 = hash_a
483                .rotate_left(5)
484                .wrapping_add(round_function)
485                .wrapping_add(hash_e)
486                .wrapping_add(0x6ED9_EBA1)
487                .wrapping_add(schedule_word);
488            hash_e = hash_d;
489            hash_d = hash_c;
490            hash_c = hash_b.rotate_left(30);
491            hash_b = hash_a;
492            hash_a = temp;
493        }
494        for &schedule_word in &message_schedule[40..60] {
495            let round_function: u32 = (hash_b & hash_c) | (hash_b & hash_d) | (hash_c & hash_d);
496            let temp: u32 = hash_a
497                .rotate_left(5)
498                .wrapping_add(round_function)
499                .wrapping_add(hash_e)
500                .wrapping_add(0x8F1B_BCDC)
501                .wrapping_add(schedule_word);
502            hash_e = hash_d;
503            hash_d = hash_c;
504            hash_c = hash_b.rotate_left(30);
505            hash_b = hash_a;
506            hash_a = temp;
507        }
508        for &schedule_word in &message_schedule[60..80] {
509            let round_function: u32 = hash_b ^ hash_c ^ hash_d;
510            let temp: u32 = hash_a
511                .rotate_left(5)
512                .wrapping_add(round_function)
513                .wrapping_add(hash_e)
514                .wrapping_add(0xCA62_C1D6)
515                .wrapping_add(schedule_word);
516            hash_e = hash_d;
517            hash_d = hash_c;
518            hash_c = hash_b.rotate_left(30);
519            hash_b = hash_a;
520            hash_a = temp;
521        }
522        hash_state[0] = hash_state[0].wrapping_add(hash_a);
523        hash_state[1] = hash_state[1].wrapping_add(hash_b);
524        hash_state[2] = hash_state[2].wrapping_add(hash_c);
525        hash_state[3] = hash_state[3].wrapping_add(hash_d);
526        hash_state[4] = hash_state[4].wrapping_add(hash_e);
527    }
528
529    /// Calculates the SHA-1 hash of the input data.
530    ///
531    /// This function implements the SHA-1 cryptographic hash algorithm according to RFC 3174.
532    /// It processes the input data in 512-bit (64-byte) blocks without heap allocation and
533    /// produces a 160-bit (20-byte) hash.
534    ///
535    /// # Arguments
536    ///
537    /// - `D` - The input data to be hashed, which requires the `AsRef<[u8]>` bound.
538    ///
539    /// # Returns
540    ///
541    /// A 20-byte array representing the SHA-1 hash of the input data.
542    pub fn sha1<D>(data: D) -> [u8; 20]
543    where
544        D: AsRef<[u8]>,
545    {
546        let data_ref: &[u8] = data.as_ref();
547        let mut hash_state: [u32; 5] = HASH_STATE;
548        let original_size_bits: u64 = (data_ref.len() as u64).wrapping_mul(8);
549        let (blocks, remainder): (&[[u8; 64]], &[u8]) = data_ref.as_chunks::<64>();
550        for block in blocks {
551            Self::sha1_compress_block(&mut hash_state, block);
552        }
553        let mut final_block: [u8; 64] = [0u8; 64];
554        let rem_len: usize = remainder.len();
555        final_block[..rem_len].copy_from_slice(remainder);
556        final_block[rem_len] = 0x80;
557        if rem_len >= 56 {
558            Self::sha1_compress_block(&mut hash_state, &final_block);
559            final_block = [0u8; 64];
560        }
561        final_block[56..64].copy_from_slice(&original_size_bits.to_be_bytes());
562        Self::sha1_compress_block(&mut hash_state, &final_block);
563        let mut result: [u8; 20] = [0u8; 20];
564        for (state_index, &state_value) in hash_state.iter().enumerate() {
565            result[state_index * 4..(state_index + 1) * 4]
566                .copy_from_slice(&state_value.to_be_bytes());
567        }
568        result
569    }
570
571    /// Generates a WebSocket accept key from the client-provided key, returning an `Option<String>`.
572    ///
573    /// # Arguments
574    ///
575    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
576    ///   requires the `AsRef<str>` bound.
577    ///
578    /// # Returns
579    ///
580    /// - `Option<String>` - An optional string representing the generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
581    #[inline(always)]
582    pub fn try_generate_accept_key<K>(key: K) -> Option<String>
583    where
584        K: AsRef<str>,
585    {
586        let key_bytes: &[u8] = key.as_ref().as_bytes();
587        if key_bytes.len() != 24
588            || key_bytes[22] != WS_KEY_PAD_BYTE
589            || key_bytes[23] != WS_KEY_PAD_BYTE
590        {
591            return None;
592        }
593        if !key_bytes[..22].iter().all(|byte: &u8| {
594            byte.is_ascii_alphanumeric() || *byte == WS_KEY_PLUS_BYTE || *byte == WS_KEY_SLASH_BYTE
595        }) {
596            return None;
597        }
598        let mut data: [u8; 60] = [0u8; 60];
599        data[..24].copy_from_slice(key_bytes);
600        data[24..].copy_from_slice(GUID);
601        let hash: [u8; 20] = Self::sha1(data);
602        Self::try_base64_encode(hash)
603    }
604
605    /// Generates a WebSocket accept key from the client-provided key.
606    ///
607    /// This function is used during the WebSocket handshake to validate the client's request.
608    /// It concatenates the client's key with a specific GUID, calculates the SHA-1 hash of the result,
609    /// and then encodes the hash in base64.
610    ///
611    /// # Arguments
612    ///
613    /// - `K` - The client-provided key (typically from the `Sec-WebSocket-Key` header), which
614    ///   requires the `AsRef<str>` bound.
615    ///
616    /// # Returns
617    ///
618    /// - `String` - The generated WebSocket accept key (typically for the `Sec-WebSocket-Accept` header).
619    #[inline(always)]
620    pub fn generate_accept_key<K>(key: K) -> String
621    where
622        K: AsRef<str>,
623    {
624        let key_bytes: &[u8] = key.as_ref().as_bytes();
625        if key_bytes.len() <= 24 {
626            let mut data: [u8; 60] = [0u8; 60];
627            let key_len: usize = key_bytes.len();
628            data[..key_len].copy_from_slice(key_bytes);
629            data[key_len..key_len + GUID.len()].copy_from_slice(GUID);
630            let hash: [u8; 20] = Self::sha1(&data[..key_len + GUID.len()]);
631            return Self::base64_encode(hash);
632        }
633        let mut data: Vec<u8> = Vec::with_capacity(key_bytes.len() + GUID.len());
634        data.extend_from_slice(key_bytes);
635        data.extend_from_slice(GUID);
636        let hash: [u8; 20] = Self::sha1(&data);
637        Self::base64_encode(hash)
638    }
639
640    /// Encodes the input data as a base64 string, returning an `Option<String>`.
641    ///
642    /// # Arguments
643    ///
644    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
645    ///
646    /// # Returns
647    ///
648    /// - `Option<String>` - An optional string with the base64 encoded representation of the input data.
649    pub fn try_base64_encode<D>(data: D) -> Option<String>
650    where
651        D: AsRef<[u8]>,
652    {
653        let data_ref: &[u8] = data.as_ref();
654        let out_len: usize = data_ref.len().div_ceil(3) * 4;
655        let mut encoded_data: Vec<u8> = Vec::with_capacity(out_len);
656        let (chunks, remainder): (&[[u8; 3]], &[u8]) = data_ref.as_chunks::<3>();
657        for &[b0, b1, b2] in chunks {
658            encoded_data.push(BASE64_CHARSET_TABLE[(b0 >> 2) as usize]);
659            encoded_data.push(BASE64_CHARSET_TABLE[(((b0 & 0b11) << 4) | (b1 >> 4)) as usize]);
660            encoded_data.push(BASE64_CHARSET_TABLE[(((b1 & 0b1111) << 2) | (b2 >> 6)) as usize]);
661            encoded_data.push(BASE64_CHARSET_TABLE[(b2 & 0b11_1111) as usize]);
662        }
663        let pad: u8 = EQUAL_BYTES[0];
664        match remainder {
665            [b0] => {
666                encoded_data.push(BASE64_CHARSET_TABLE[(*b0 >> 2) as usize]);
667                encoded_data.push(BASE64_CHARSET_TABLE[((*b0 & 0b11) << 4) as usize]);
668                encoded_data.push(pad);
669                encoded_data.push(pad);
670            }
671            [b0, b1] => {
672                encoded_data.push(BASE64_CHARSET_TABLE[(*b0 >> 2) as usize]);
673                encoded_data
674                    .push(BASE64_CHARSET_TABLE[(((*b0 & 0b11) << 4) | (*b1 >> 4)) as usize]);
675                encoded_data.push(BASE64_CHARSET_TABLE[((*b1 & 0b1111) << 2) as usize]);
676                encoded_data.push(pad);
677            }
678            _ => {}
679        }
680        // SAFETY: Every byte pushed comes from `BASE64_CHARSET_TABLE` or `'='`, all valid ASCII.
681        Some(unsafe { String::from_utf8_unchecked(encoded_data) })
682    }
683
684    /// Encodes the input data as a base64 string.
685    ///
686    /// # Arguments
687    ///
688    /// - `D` - The data to encode in base64, which requires the `AsRef<[u8]>` bound.
689    ///
690    /// # Returns
691    ///
692    /// - `String` - A string with the base64 encoded representation of the input data.
693    ///
694    /// # Panics
695    ///
696    /// This function will panic if the input data cannot be converted to a UTF-8 string.
697    #[inline(always)]
698    pub fn base64_encode<D>(data: D) -> String
699    where
700        D: AsRef<[u8]>,
701    {
702        Self::try_base64_encode(data).unwrap()
703    }
704
705    /// Checks if the opcode is a continuation frame.
706    ///
707    /// # Returns
708    ///
709    /// - `bool` - `true` if the opcode is `Continuation`, otherwise `false`.
710    #[inline(always)]
711    pub fn is_continuation_opcode(&self) -> bool {
712        self.get_opcode().is_continuation()
713    }
714
715    /// Checks if the opcode is a text frame.
716    ///
717    /// # Returns
718    ///
719    /// - `bool` - `true` if the opcode is `Text`, otherwise `false`.
720    #[inline(always)]
721    pub fn is_text_opcode(&self) -> bool {
722        self.get_opcode().is_text()
723    }
724
725    /// Checks if the opcode is a binary frame.
726    ///
727    /// # Returns
728    ///
729    /// - `bool` - `true` if the opcode is `Binary`, otherwise `false`.
730    #[inline(always)]
731    pub fn is_binary_opcode(&self) -> bool {
732        self.get_opcode().is_binary()
733    }
734
735    /// Checks if the opcode is a close frame.
736    ///
737    /// # Returns
738    ///
739    /// - `bool` - `true` if the opcode is `Close`, otherwise `false`.
740    #[inline(always)]
741    pub fn is_close_opcode(&self) -> bool {
742        self.get_opcode().is_close()
743    }
744
745    /// Checks if the opcode is a ping frame.
746    ///
747    /// # Returns
748    ///
749    /// - `bool` - `true` if the opcode is `Ping`, otherwise `false`.
750    #[inline(always)]
751    pub fn is_ping_opcode(&self) -> bool {
752        self.get_opcode().is_ping()
753    }
754
755    /// Checks if the opcode is a pong frame.
756    ///
757    /// # Returns
758    ///
759    /// - `bool` - `true` if the opcode is `Pong`, otherwise `false`.
760    #[inline(always)]
761    pub fn is_pong_opcode(&self) -> bool {
762        self.get_opcode().is_pong()
763    }
764
765    /// Checks if the opcode is a reserved frame.
766    ///
767    /// # Returns
768    ///
769    /// - `bool` - `true` if the opcode is `Reserved(_)`, otherwise `false`.
770    #[inline(always)]
771    pub fn is_reserved_opcode(&self) -> bool {
772        self.get_opcode().is_reserved()
773    }
774}