hyperlane-plugin-sse 23.1.0

A Server-Sent Events (SSE) streaming and topic pub/sub plugin for the Hyperlane framework with Last-Event-ID replay, heartbeat, and CRLF-safe event framing.
Documentation
use super::*;

/// Computes the shard index for `topic` with zero allocations.
///
/// # Arguments
///
/// - `&str` - Topic name to hash.
///
/// # Returns
///
/// - `usize` - Shard slot in `0..SSE_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn sse_shard_index(topic: &str) -> usize {
    let mut hasher: FxHasher = FxHasher::default();
    hasher.write(topic.as_bytes());
    let h: u64 = hasher.finish();
    (((h >> 32) ^ h) as usize) & (SSE_SHARD_COUNT - 1)
}

/// Tests whether an 8-byte word contains any zero byte using SWAR bit-parallel arithmetic.
///
/// # Arguments
///
/// - `u64` - Input 8-byte word.
///
/// # Returns
///
/// - `bool` - `true` if any lane equals `0x00`.
#[inline(always)]
pub(crate) fn swar_has_zero(word: u64) -> bool {
    (word.wrapping_sub(SWAR_LO_ONES) & !word & SWAR_HI_BITS) != 0
}

/// Reports whether `bytes` contains any `\r`, `\n`, or NUL byte using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `bool` - `true` when any forbidden control byte is present.
#[inline]
pub(crate) fn has_forbidden_sse_byte(bytes: &[u8]) -> bool {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for chunk in chunks {
        let w: u64 = u64::from_ne_bytes(*chunk);
        if swar_has_zero(w) || swar_has_zero(w ^ SWAR_LF_MASK) || swar_has_zero(w ^ SWAR_CR_MASK) {
            return true;
        }
    }
    for &b in rem {
        if b == BYTE_LF || b == BYTE_CR || b == 0 {
            return true;
        }
    }
    false
}

/// Finds the first `\r` or `\n` offset within `bytes` using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&[u8]` - Input payload byte slice.
///
/// # Returns
///
/// - `Option<usize>` - Byte index of the first line break, or `None` if single-line.
#[inline]
pub(crate) fn find_line_break(bytes: &[u8]) -> Option<usize> {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for (ci, chunk) in chunks.iter().enumerate() {
        let w: u64 = u64::from_ne_bytes(*chunk);
        let lf: u64 = w ^ SWAR_LF_MASK;
        let cr: u64 = w ^ SWAR_CR_MASK;
        let mask: u64 = ((lf.wrapping_sub(SWAR_LO_ONES) & !lf)
            | (cr.wrapping_sub(SWAR_LO_ONES) & !cr))
            & SWAR_HI_BITS;
        if mask != 0 {
            let base: usize = ci * 8;
            for (j, &b) in chunk.iter().enumerate() {
                if b == BYTE_LF || b == BYTE_CR {
                    return Some(base + j);
                }
            }
        }
    }
    let tail_base: usize = chunks.len() * 8;
    for (j, &b) in rem.iter().enumerate() {
        if b == BYTE_LF || b == BYTE_CR {
            return Some(tail_base + j);
        }
    }
    None
}

/// Writes sanitized single-line SSE header bytes directly into `out`, stripping `\r`, `\n`, and NUL.
///
/// # Arguments
///
/// - `&str` - Raw field text.
/// - `&mut Vec<u8>` - Destination wire buffer.
#[inline]
pub(crate) fn write_sanitized_sse_bytes(raw: &str, out: &mut Vec<u8>) {
    let bytes: &[u8] = raw.as_bytes();
    if !has_forbidden_sse_byte(bytes) {
        out.extend_from_slice(bytes);
        return;
    }
    for &b in bytes {
        if b != BYTE_CR && b != BYTE_LF && b != 0 {
            out.push(b);
        }
    }
}

/// Writes sanitized single-line SSE bytes into fixed stack slice `buf` at `pos`, returning new offset.
///
/// # Arguments
///
/// - `&str` - Raw field text.
/// - `&mut [u8]` - Destination stack buffer.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline]
pub(crate) fn write_sanitized_sse_slice(raw: &str, buf: &mut [u8], pos: usize) -> Option<usize> {
    let bytes: &[u8] = raw.as_bytes();
    if !has_forbidden_sse_byte(bytes) {
        let next: usize = pos + bytes.len();
        if next > buf.len() {
            return None;
        }
        buf[pos..next].copy_from_slice(bytes);
        return Some(next);
    }
    let mut cur: usize = pos;
    for &b in bytes {
        if b != BYTE_CR && b != BYTE_LF && b != 0 {
            if cur >= buf.len() {
                return None;
            }
            buf[cur] = b;
            cur += 1;
        }
    }
    Some(cur)
}

/// Writes an unsigned 64-bit decimal integer into a 20-byte stack array, returning the start index.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8; U64_DECIMAL_BUF_LEN]` - Destination digit array.
///
/// # Returns
///
/// - `usize` - Start index inside `digits` (`digits[idx..]` holds the formatted digits).
#[inline(always)]
pub(crate) fn format_u64_digits(mut value: u64, digits: &mut [u8; U64_DECIMAL_BUF_LEN]) -> usize {
    if value < 10 {
        let idx: usize = U64_DECIMAL_BUF_LEN - 1;
        digits[idx] = BYTE_ZERO + value as u8;
        return idx;
    }
    let mut idx: usize = U64_DECIMAL_BUF_LEN;
    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;
    }
    idx
}

/// Writes an unsigned 64-bit decimal integer directly into `out` without allocating.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut Vec<u8>` - Destination wire buffer.
#[inline]
pub(crate) fn write_u64_decimal(value: u64, out: &mut Vec<u8>) {
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let pos: usize = format_u64_digits(value, &mut digits);
    out.extend_from_slice(&digits[pos..]);
}

/// Writes an unsigned 64-bit decimal integer into fixed stack slice `buf` at `pos`.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8]` - Destination stack buffer.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline]
pub(crate) fn write_u64_decimal_slice(value: u64, buf: &mut [u8], pos: usize) -> Option<usize> {
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let start: usize = format_u64_digits(value, &mut digits);
    let slice: &[u8] = &digits[start..];
    let next: usize = pos + slice.len();
    if next > buf.len() {
        return None;
    }
    buf[pos..next].copy_from_slice(slice);
    Some(next)
}

/// Formats an unsigned 64-bit integer into a decimal `String` via a 2-digit LUT stack buffer.
///
/// # Arguments
///
/// - `u64` - Unsigned integer value.
///
/// # Returns
///
/// - `String` - Decimal string representation.
#[inline]
pub(crate) fn format_u64_string(value: u64) -> String {
    if value == 0 {
        return ZERO_STR.to_owned();
    }
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let pos: usize = format_u64_digits(value, &mut digits);
    from_utf8(&digits[pos..]).unwrap_or_default().to_owned()
}

/// Parses a `Last-Event-ID` string into a numeric sequence id when valid.
///
/// # Arguments
///
/// - `Option<&str>` - Raw `Last-Event-ID` header value.
///
/// # Returns
///
/// - `Option<u64>` - Parsed sequence id, or `None` when absent or non-numeric.
#[inline]
pub(crate) fn parse_last_event_id(raw: Option<&str>) -> Option<u64> {
    raw.and_then(|text: &str| text.trim().parse::<u64>().ok())
}