hyperlane-plugin-websocket 23.0.0

A WebSocket plugin for the Hyperlane framework, providing robust WebSocket communication capabilities and integrating with hyperlane-broadcast for efficient message dissemination.
Documentation
use super::*;

/// Formats an unsigned `u64` in decimal directly into `buf` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of ASCII decimal bytes written, or `None` if `buf` is too small.
#[inline(always)]
pub(crate) fn write_u64_decimal_bytes(mut value: u64, buf: &mut [u8]) -> Option<usize> {
    if value < 10 {
        if buf.is_empty() {
            return None;
        }
        buf[0] = BYTE_ZERO + value as u8;
        return Some(1);
    }
    let mut digits: [u8; 20] = [0u8; 20];
    let mut idx: usize = 20;
    while value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = (value as usize) * 2;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        idx -= 1;
        digits[idx] = BYTE_ZERO + value as u8;
    }
    let len: usize = 20 - idx;
    if len > buf.len() {
        return None;
    }
    buf[..len].copy_from_slice(&digits[idx..]);
    Some(len)
}

/// Formats a signed `i64` in decimal directly into `buf` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `i64` - Signed integer to format.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of ASCII decimal bytes written, or `None` if `buf` is too small.
#[inline(always)]
pub(crate) fn write_i64_decimal_bytes(value: i64, buf: &mut [u8]) -> Option<usize> {
    if value < 0 {
        if buf.is_empty() {
            return None;
        }
        buf[0] = BYTE_DASH;
        let written: usize = write_u64_decimal_bytes(value.unsigned_abs(), &mut buf[1..])?;
        return Some(written + 1);
    }
    write_u64_decimal_bytes(value as u64, buf)
}

/// Formats an unsigned `u128` in decimal directly into `buf` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `u128` - Unsigned 128-bit integer to format.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of ASCII decimal bytes written, or `None` if `buf` is too small.
#[inline]
pub(crate) fn write_u128_decimal_bytes(mut value: u128, buf: &mut [u8]) -> Option<usize> {
    if value <= u128::from(u64::MAX) {
        return write_u64_decimal_bytes(value as u64, buf);
    }
    let mut digits: [u8; 39] = [0u8; 39];
    let mut idx: usize = 39;
    while value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = (value as usize) * 2;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        idx -= 1;
        digits[idx] = BYTE_ZERO + value as u8;
    }
    let len: usize = 39 - idx;
    if len > buf.len() {
        return None;
    }
    buf[..len].copy_from_slice(&digits[idx..]);
    Some(len)
}

/// Formats a signed `i128` in decimal directly into `buf` using a 2-digit lookup table.
///
/// # Arguments
///
/// - `i128` - Signed 128-bit integer to format.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of ASCII decimal bytes written, or `None` if `buf` is too small.
#[inline]
pub(crate) fn write_i128_decimal_bytes(value: i128, buf: &mut [u8]) -> Option<usize> {
    if value < 0 {
        if buf.is_empty() {
            return None;
        }
        buf[0] = BYTE_DASH;
        let written: usize = write_u128_decimal_bytes(value.unsigned_abs(), &mut buf[1..])?;
        return Some(written + 1);
    }
    write_u128_decimal_bytes(value as u128, buf)
}

/// Formats a `char` as UTF-8 bytes directly into `buf`.
///
/// # Arguments
///
/// - `char` - Character to encode.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of UTF-8 bytes written, or `None` if `buf` is too small.
#[inline(always)]
pub(crate) fn write_char_utf8_bytes(ch: char, buf: &mut [u8]) -> Option<usize> {
    let needed: usize = ch.len_utf8();
    if needed > buf.len() {
        return None;
    }
    let _: &mut str = ch.encode_utf8(&mut buf[..needed]);
    Some(needed)
}

/// Formats a `bool` as ASCII `"true"` or `"false"` directly into `buf`.
///
/// # Arguments
///
/// - `bool` - Boolean value to encode.
/// - `&mut [u8]` - Destination byte buffer.
///
/// # Returns
///
/// - `Option<usize>` - Number of ASCII bytes written, or `None` if `buf` is too small.
#[inline(always)]
pub(crate) fn write_bool_bytes(flag: bool, buf: &mut [u8]) -> Option<usize> {
    let src: &[u8] = if flag {
        BOOL_TRUE_BYTES
    } else {
        BOOL_FALSE_BYTES
    };
    if src.len() > buf.len() {
        return None;
    }
    buf[..src.len()].copy_from_slice(src);
    Some(src.len())
}

/// Appends RFC 6455 unmasked server WebSocket frames for `data` directly into reusable buffer `out`.
///
/// Produces byte-for-byte identical output to [`WebSocketFrame::create_frame_list`] while avoiding
/// intermediate `Vec<Vec<u8>>` and per-frame heap allocations.
///
/// # Arguments
///
/// - `&[u8]` - Raw broadcast payload bytes.
/// - `&mut Vec<u8>` - Reusable wire output buffer.
#[inline]
pub(crate) fn append_ws_server_frames(data: &[u8], out: &mut Vec<u8>) {
    let total_len: usize = data.len();
    if total_len == 0 {
        out.extend_from_slice(&WS_EMPTY_TEXT_FRAME);
        return;
    }
    let is_valid_utf8: bool = from_utf8(data).is_ok();
    let base_opcode: u8 = if is_valid_utf8 {
        WS_OPCODE_TEXT
    } else {
        WS_OPCODE_BINARY
    };
    if total_len <= MAX_FRAME_SIZE {
        let hdr_len: usize = if total_len < 126 { 2 } else { 4 };
        out.reserve(hdr_len + total_len);
        out.push(WS_FIN_BIT | base_opcode);
        if total_len < 126 {
            out.push(total_len as u8);
        } else {
            out.push(126);
            out.extend_from_slice(&(total_len as u16).to_be_bytes());
        }
        out.extend_from_slice(data);
        return;
    }
    let frames_est: usize = (total_len / MAX_FRAME_SIZE) + 1;
    out.reserve(total_len + frames_est * 10);
    let mut offset: usize = 0;
    let mut is_first_frame: bool = true;
    while offset < total_len {
        let remaining: usize = total_len - offset;
        let mut frame_size: usize = remaining.min(MAX_FRAME_SIZE);
        if is_valid_utf8 && frame_size < remaining {
            while frame_size > 0 && (data[offset + frame_size] & 0xC0) == 0x80 {
                frame_size -= 1;
            }
            if frame_size == 0 {
                frame_size = remaining.min(MAX_FRAME_SIZE);
            }
        }
        let opcode: u8 = if is_first_frame {
            base_opcode
        } else {
            WS_OPCODE_CONTINUATION
        };
        let fin: u8 = if remaining > frame_size {
            0x00
        } else {
            WS_FIN_BIT
        };
        out.push(fin | opcode);
        if frame_size < 126 {
            out.push(frame_size as u8);
        } else if frame_size <= usize::from(u16::MAX) {
            out.push(126);
            out.extend_from_slice(&(frame_size as u16).to_be_bytes());
        } else {
            out.push(127);
            out.extend_from_slice(&(frame_size as u64).to_be_bytes());
        }
        let end: usize = offset + frame_size;
        out.extend_from_slice(&data[offset..end]);
        offset = end;
        is_first_frame = false;
    }
}