use super::*;
#[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)
}
#[inline(always)]
pub(crate) fn swar_has_zero(word: u64) -> bool {
(word.wrapping_sub(SWAR_LO_ONES) & !word & SWAR_HI_BITS) != 0
}
#[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
}
#[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
}
#[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);
}
}
}
#[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)
}
#[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
}
#[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..]);
}
#[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)
}
#[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()
}
#[inline]
pub(crate) fn parse_last_event_id(raw: Option<&str>) -> Option<u64> {
raw.and_then(|text: &str| text.trim().parse::<u64>().ok())
}
#[inline]
pub(crate) fn take_sse_coalesce_buf() -> SseScratchBuf {
let buf: Vec<u8> = SSE_COALESCE_BUF_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
let mut guard: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
match guard.pop() {
Some(mut existing) => {
existing.clear();
existing
}
None => Vec::new(),
}
});
SseScratchBuf { buf }
}
#[inline]
pub(crate) fn return_sse_coalesce_buf(mut buf: Vec<u8>) {
if buf.capacity() == 0 || buf.capacity() > SSE_COALESCE_MAX_RETAIN {
return;
}
buf.clear();
SSE_COALESCE_BUF_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
let mut guard: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
if guard.len() < SSE_MAX_POOLED_COALESCE_BUFS {
guard.push(buf);
}
});
}
pub(crate) fn build_initial_sse_head(ctx: &mut Context, retry_ms: u64) -> Vec<u8> {
SseStream::prepare(ctx);
let mut head: Vec<u8> = ctx.get_mut_response().build_head();
if retry_ms > 0 {
head.reserve(SSE_RETRY_HINT_STACK_CAP);
head.extend_from_slice(SSE_COMMENT_PREFIX.as_bytes());
head.extend_from_slice(SSE_HEARTBEAT_COMMENT.as_bytes());
head.push(BYTE_LF);
head.extend_from_slice(SSE_FIELD_RETRY.as_bytes());
write_u64_decimal(retry_ms, &mut head);
head.push(BYTE_LF);
head.push(BYTE_LF);
}
head
}
pub(crate) async fn next_sse_action(
subscription: &mut SseSubscription,
heartbeat: &mut Option<Receiver<u64>>,
) -> Result<SseLoopAction, SseError> {
loop {
match heartbeat {
None => match subscription.recv_shared().await {
Ok(shared) => return Ok(SseLoopAction::Event(shared)),
Err(SseError::Lagged(_)) => continue,
Err(SseError::ChannelClosed) => return Ok(SseLoopAction::Closed),
Err(err) => return Err(err),
},
Some(hb_rx) => {
select! {
biased;
next = subscription.recv_shared() => match next {
Ok(shared) => return Ok(SseLoopAction::Event(shared)),
Err(SseError::Lagged(_)) => continue,
Err(SseError::ChannelClosed) => return Ok(SseLoopAction::Closed),
Err(err) => return Err(err),
},
tick = hb_rx.changed() => {
if tick.is_ok() {
return Ok(SseLoopAction::Heartbeat);
}
}
}
}
}
}
}
pub(crate) async fn drive_sse_heartbeat_wheel(
hub: Weak<SseHubInner>,
key: (Id, u64),
wheel: Arc<SseHeartbeatWheel>,
step: Duration,
) {
let mut ticker: Interval = interval(step);
ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
let _: Instant = ticker.tick().await;
let bucket_count: usize = wheel.buckets.len();
loop {
let _: Instant = ticker.tick().await;
if wheel.total_receivers() == 0 {
let Some(hub_arc) = hub.upgrade() else {
wheel.alive.store(false, Ordering::Release);
return;
};
if let Ok(mut map) = hub_arc.heartbeats.lock()
&& wheel.total_receivers() == 0
{
wheel.alive.store(false, Ordering::Release);
if map
.get(&key)
.is_some_and(|cur: &Arc<SseHeartbeatWheel>| Arc::ptr_eq(cur, &wheel))
{
let _: Option<Arc<SseHeartbeatWheel>> = map.remove(&key);
}
return;
}
}
let step_idx: usize = wheel.phase.fetch_add(1, Ordering::AcqRel) % bucket_count;
wheel.buckets[step_idx].send_modify(|tick: &mut u64| {
*tick = tick.wrapping_add(1);
});
}
}