use super::*;
impl Write for StackKeyWriter<'_> {
#[inline]
fn write_str(&mut self, s: &str) -> fmt::Result {
let Self { buf, len } = self;
let bytes: &[u8] = s.as_bytes();
let next: usize = *len + bytes.len();
if next > buf.len() {
return Err(fmt::Error);
}
buf[*len..next].copy_from_slice(bytes);
*len = next;
Ok(())
}
}
impl BroadcastTypeTrait for String {
#[inline(always)]
fn as_broadcast_str(&self) -> Option<&str> {
Some(self.as_str())
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
f.write_str(self)
}
}
impl BroadcastTypeTrait for &str {
#[inline(always)]
fn as_broadcast_str(&self) -> Option<&str> {
Some(self)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
f.write_str(self)
}
}
impl BroadcastTypeTrait for char {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_char_utf8_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
f.write_char(*self)
}
}
impl BroadcastTypeTrait for bool {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_bool_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for i8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for i16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for i32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for i64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for i128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i128_decimal_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for isize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(*self as i64, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for u8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for u16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for u32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(*self), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for u64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for u128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u128_decimal_bytes(*self, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for usize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(*self as u64, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for f32 {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for f64 {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for IpAddr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for Ipv4Addr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for Ipv6Addr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for SocketAddr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroU8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroU16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroU32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(u64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroU64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(self.get(), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroU128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u128_decimal_bytes(self.get(), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroUsize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_u64_decimal_bytes(self.get() as u64, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroI8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroI16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroI32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(i64::from(self.get()), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroI64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(self.get(), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroI128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i128_decimal_bytes(self.get(), buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for NonZeroIsize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
write_i64_decimal_bytes(self.get() as i64, buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
write!(f, "{self}")
}
}
impl BroadcastTypeTrait for Infallible {}
impl BroadcastTypeTrait for &String {
#[inline(always)]
fn as_broadcast_str(&self) -> Option<&str> {
Some(self.as_str())
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
f.write_str(self)
}
}
impl BroadcastTypeTrait for &&str {
#[inline(always)]
fn as_broadcast_str(&self) -> Option<&str> {
Some(self)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
f.write_str(self)
}
}
impl BroadcastTypeTrait for &char {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &bool {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &i8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &i16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &i32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &i64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &i128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &isize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &u8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &u16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &u32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &u64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &u128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &usize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &f32 {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &f64 {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &IpAddr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &Ipv4Addr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &Ipv6Addr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &SocketAddr {
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroU8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroU16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroU32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroU64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroU128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroUsize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroI8 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroI16 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroI32 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroI64 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroI128 {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &NonZeroIsize {
#[inline(always)]
fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
(**self).write_broadcast_bytes(buf)
}
#[inline]
fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
(**self).write_broadcast_key(f)
}
}
impl BroadcastTypeTrait for &Infallible {}
impl<B> Default for BroadcastType<B>
where
B: BroadcastTypeTrait,
{
#[inline(always)]
fn default() -> Self {
BroadcastType::Unknown
}
}
impl<B> BroadcastType<B>
where
B: BroadcastTypeTrait,
{
#[cold]
#[inline(never)]
fn with_key_slow<R, F>(&self, op: F) -> R
where
F: FnOnce(&str) -> R,
{
match self {
BroadcastType::PointToPoint(key1, key2) => {
let (first_key, second_key): (&B, &B) = if key1 <= key2 {
(key1, key2)
} else {
(key2, key1)
};
let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
let mut writer: StackKeyWriter<'_> = StackKeyWriter {
buf: &mut stack,
len: 0,
};
let fits: bool = writer.write_str(POINT_TO_POINT_PREFIX).is_ok()
&& first_key.write_broadcast_key(&mut writer).is_ok()
&& writer.write_char('-').is_ok()
&& second_key.write_broadcast_key(&mut writer).is_ok();
if fits {
let written: usize = writer.len;
if let Ok(key) = from_utf8(&stack[..written]) {
return op(key);
}
}
let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
key.push_str(POINT_TO_POINT_PREFIX);
let _: fmt::Result = first_key.write_broadcast_key(&mut key);
key.push('-');
let _: fmt::Result = second_key.write_broadcast_key(&mut key);
op(&key)
}
BroadcastType::PointToGroup(group_key) => {
let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
let mut writer: StackKeyWriter<'_> = StackKeyWriter {
buf: &mut stack,
len: 0,
};
let fits: bool = writer.write_str(POINT_TO_GROUP_PREFIX).is_ok()
&& group_key.write_broadcast_key(&mut writer).is_ok();
if fits {
let written: usize = writer.len;
if let Ok(key) = from_utf8(&stack[..written]) {
return op(key);
}
}
let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
key.push_str(POINT_TO_GROUP_PREFIX);
let _: fmt::Result = group_key.write_broadcast_key(&mut key);
op(&key)
}
BroadcastType::Unknown => op(EMPTY_STR),
}
}
#[inline(always)]
pub(crate) fn with_key<R, F>(&self, op: F) -> R
where
F: FnOnce(&str) -> R,
{
match self {
BroadcastType::PointToGroup(group_key) => {
let prefix: &[u8] = POINT_TO_GROUP_PREFIX.as_bytes();
let p_len: usize = prefix.len();
let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
if let Some(group_str) = group_key.as_broadcast_str() {
let group_bytes: &[u8] = group_str.as_bytes();
let total: usize = p_len + group_bytes.len();
if total <= STACK_KEY_BUF_LEN {
stack[..p_len].copy_from_slice(prefix);
stack[p_len..total].copy_from_slice(group_bytes);
if let Ok(key) = from_utf8(&stack[..total]) {
return op(key);
}
}
} else if let Some(written) = group_key.write_broadcast_bytes(&mut stack[p_len..]) {
stack[..p_len].copy_from_slice(prefix);
if let Ok(key) = from_utf8(&stack[..p_len + written]) {
return op(key);
}
}
self.with_key_slow(op)
}
BroadcastType::PointToPoint(key1, key2) => {
let (first_key, second_key): (&B, &B) = if key1 <= key2 {
(key1, key2)
} else {
(key2, key1)
};
let prefix: &[u8] = POINT_TO_POINT_PREFIX.as_bytes();
let p1: usize = prefix.len();
let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
if let (Some(first_str), Some(second_str)) =
(first_key.as_broadcast_str(), second_key.as_broadcast_str())
{
let a: &[u8] = first_str.as_bytes();
let b: &[u8] = second_str.as_bytes();
let total: usize = p1 + a.len() + 1 + b.len();
if total <= STACK_KEY_BUF_LEN {
let p2: usize = p1 + a.len();
stack[..p1].copy_from_slice(prefix);
stack[p1..p2].copy_from_slice(a);
stack[p2] = BYTE_DASH;
stack[p2 + 1..total].copy_from_slice(b);
if let Ok(key) = from_utf8(&stack[..total]) {
return op(key);
}
}
} else if let Some(w1) = first_key.write_broadcast_bytes(&mut stack[p1..]) {
let p2: usize = p1 + w1;
if p2 + 1 < STACK_KEY_BUF_LEN
&& let Some(w2) = second_key.write_broadcast_bytes(&mut stack[p2 + 1..])
{
stack[..p1].copy_from_slice(prefix);
stack[p2] = BYTE_DASH;
if let Ok(key) = from_utf8(&stack[..p2 + 1 + w2]) {
return op(key);
}
}
}
self.with_key_slow(op)
}
BroadcastType::Unknown => op(EMPTY_STR),
}
}
#[inline(always)]
pub fn get_key(broadcast_type: BroadcastType<B>) -> String {
broadcast_type.with_key(str::to_owned)
}
}
impl<'a, B> WebSocketConfig<'a, B>
where
B: BroadcastTypeTrait,
{
#[inline(always)]
pub fn new(stream: &'a mut Stream, context: &'a mut Context) -> Self {
Self {
stream,
context,
capacity: DEFAULT_BROADCAST_SENDER_CAPACITY,
broadcast_type: BroadcastType::default(),
connected_hook: Hook::default_handler(),
request_hook: Hook::default_handler(),
sended_hook: Hook::default_handler(),
closed_hook: Hook::default_handler(),
}
}
#[inline(always)]
pub fn take_parts(self) -> (&'a mut Stream, &'a mut Context) {
let Self {
stream, context, ..
} = self;
(stream, context)
}
}
impl<'a, B> WebSocketConfig<'a, B>
where
B: BroadcastTypeTrait,
{
#[inline(always)]
pub fn set_capacity(mut self, capacity: usize) -> Self {
self.capacity = capacity;
self
}
#[inline(always)]
pub fn set_context(mut self, context: &'a mut Context) -> Self {
self.context = context;
self
}
#[inline(always)]
pub fn set_broadcast_type(mut self, broadcast_type: BroadcastType<B>) -> Self {
self.broadcast_type = broadcast_type;
self
}
#[inline(always)]
pub fn set_connected_hook<S>(mut self) -> Self
where
S: ServerHook,
{
self.connected_hook = Hook::factory::<S>();
self
}
#[inline(always)]
pub fn set_request_hook<S>(mut self) -> Self
where
S: ServerHook,
{
self.request_hook = Hook::factory::<S>();
self
}
#[inline(always)]
pub fn set_sended_hook<S>(mut self) -> Self
where
S: ServerHook,
{
self.sended_hook = Hook::factory::<S>();
self
}
#[inline(always)]
pub fn set_closed_hook<S>(mut self) -> Self
where
S: ServerHook,
{
self.closed_hook = Hook::factory::<S>();
self
}
}
impl Hasher for WsKeyHasher {
#[inline(always)]
fn finish(&self) -> u64 {
let Self { state } = *self;
state
}
#[inline(always)]
fn write(&mut self, bytes: &[u8]) {
let Self { state } = self;
let mut h: u64 = *state;
let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
for chunk in chunks {
h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(WS_FX_HASH_K);
}
let mut tail: &[u8] = rem;
if tail.len() >= 4 {
let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(WS_FX_HASH_K);
tail = &tail[4..];
}
if tail.len() >= 2 {
let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(WS_FX_HASH_K);
tail = &tail[2..];
}
if let Some(&b) = tail.first() {
h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(WS_FX_HASH_K);
}
*state = h;
}
#[inline(always)]
fn write_u8(&mut self, i: u8) {
let Self { state } = self;
*state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(WS_FX_HASH_K);
}
}
impl Drop for WsScratchBuf {
fn drop(&mut self) {
let Self { buf } = self;
return_ws_coalesce_buf(take(buf));
}
}
impl WsRoomRing {
#[inline]
pub(crate) fn new(capacity: usize) -> Self {
Self {
entries: VecDeque::new(),
head_seq: 0,
next_seq: 0,
subscribers: 0,
capacity: capacity.max(1),
closed: false,
}
}
#[inline]
fn reclaim_consumed_front(&mut self) {
let Self {
entries,
head_seq,
next_seq,
..
} = self;
while entries
.front()
.is_some_and(|entry: &WsRoomEntry| entry.unread == 0)
{
let _: Option<WsRoomEntry> = entries.pop_front();
}
*head_seq = entries
.front()
.map_or(*next_seq, |entry: &WsRoomEntry| entry.seq);
if entries.is_empty() && entries.capacity() > 0 {
*entries = VecDeque::new();
}
}
#[inline]
pub(crate) fn subscribe(&mut self) -> u64 {
let Self {
subscribers,
next_seq,
..
} = self;
*subscribers += 1;
*next_seq
}
#[inline]
pub(crate) fn push(&mut self, frame: Arc<[u8]>) -> usize {
let Self {
entries,
head_seq,
next_seq,
subscribers,
capacity,
closed,
} = self;
if *subscribers == 0 || *closed {
return 0;
}
if entries.len() >= *capacity {
let _: Option<WsRoomEntry> = entries.pop_front();
*head_seq = entries
.front()
.map_or(*next_seq, |entry: &WsRoomEntry| entry.seq);
}
let seq: u64 = *next_seq;
if entries.is_empty() {
*head_seq = seq;
}
let receiver_count: usize = *subscribers;
entries.push_back(WsRoomEntry {
seq,
frame,
unread: receiver_count,
});
*next_seq = seq + 1;
receiver_count
}
#[inline]
pub(crate) fn try_pop(&mut self, cursor: &mut u64) -> Option<WsRoomRecv> {
let Self {
entries,
head_seq,
next_seq,
closed,
..
} = self;
if *cursor < *head_seq {
*cursor = *head_seq;
return Some(WsRoomRecv::Lagged);
}
if *cursor >= *next_seq {
if *closed {
return Some(WsRoomRecv::Closed);
}
return None;
}
let offset: usize = (*cursor - *head_seq) as usize;
let frame: Arc<[u8]> = Arc::clone(&entries[offset].frame);
entries[offset].unread = entries[offset].unread.saturating_sub(1);
*cursor += 1;
if offset == 0 && entries[0].unread == 0 {
self.reclaim_consumed_front();
}
Some(WsRoomRecv::Frame(frame))
}
#[inline]
pub(crate) fn unsubscribe(&mut self, cursor: u64) {
let Self {
entries,
head_seq,
next_seq,
subscribers,
..
} = self;
*subscribers = subscribers.saturating_sub(1);
let start_seq: u64 = cursor.max(*head_seq);
if start_seq < *next_seq {
let start_idx: usize = (start_seq - *head_seq) as usize;
for entry in entries.iter_mut().skip(start_idx) {
entry.unread = entry.unread.saturating_sub(1);
}
self.reclaim_consumed_front();
}
}
}
impl SparseWsHubInner {
pub(crate) fn new() -> Self {
let shards: Box<[WsShard; WS_SHARD_COUNT]> = Box::new(from_fn(|_: usize| WsShard {
map: RwLock::new(HashMap::default()),
}));
Self { shards }
}
pub(crate) fn clone_snapshot(&self) -> Self {
let Self { shards } = self;
let cloned: Box<[WsShard; WS_SHARD_COUNT]> = Box::new(from_fn(|idx: usize| {
let entries: WsShardMap = shards[idx]
.map
.read()
.map(|guard: RwLockReadGuard<'_, WsShardMap>| guard.clone())
.unwrap_or_default();
WsShard {
map: RwLock::new(entries),
}
}));
Self { shards: cloned }
}
pub(crate) fn subscribe(self: &Arc<Self>, key: &str, capacity: usize) -> SparseWsSubscription {
let Self { shards } = self.as_ref();
let shard_idx: usize = ws_shard_index(key);
let shard: &RwLock<WsShardMap> = &shards[shard_idx].map;
let (room_key, room): (Arc<str>, Arc<WsRoom>) = if let Ok(read_map) = shard.read()
&& let Some((existing_key, existing_room)) = read_map.get_key_value(key)
{
(Arc::clone(existing_key), Arc::clone(existing_room))
} else if let Ok(mut write_map) = shard.write() {
if let Some((existing_key, existing_room)) = write_map.get_key_value(key) {
(Arc::clone(existing_key), Arc::clone(existing_room))
} else {
let created_key: Arc<str> = Arc::from(key);
let created_room: Arc<WsRoom> = Arc::new(WsRoom {
subscribers: AtomicUsize::new(0),
notify: Notify::new(),
ring: Mutex::new(WsRoomRing::new(capacity)),
});
let _: Option<Arc<WsRoom>> =
write_map.insert(Arc::clone(&created_key), Arc::clone(&created_room));
(created_key, created_room)
}
} else {
let created_key: Arc<str> = Arc::from(key);
let created_room: Arc<WsRoom> = Arc::new(WsRoom {
subscribers: AtomicUsize::new(0),
notify: Notify::new(),
ring: Mutex::new(WsRoomRing::new(capacity)),
});
(created_key, created_room)
};
let cursor: u64 = room
.ring
.lock()
.map(|mut ring: MutexGuard<'_, WsRoomRing>| ring.subscribe())
.unwrap_or(0);
room.subscribers.fetch_add(1, Ordering::Release);
SparseWsSubscription {
key: room_key,
room,
hub: Arc::clone(self),
cursor,
}
}
#[inline]
pub(crate) fn receiver_count(&self, key: &str) -> usize {
let Self { shards } = self;
let shard_idx: usize = ws_shard_index(key);
shards[shard_idx]
.map
.read()
.ok()
.and_then(|map: RwLockReadGuard<'_, WsShardMap>| {
map.get(key)
.map(|room: &Arc<WsRoom>| room.subscribers.load(Ordering::Acquire))
})
.unwrap_or(0)
}
#[inline]
pub(crate) fn try_send_payload(&self, key: &str, payload: &[u8]) -> Option<usize> {
let Self { shards } = self;
let shard_idx: usize = ws_shard_index(key);
let room: Arc<WsRoom> = shards[shard_idx]
.map
.read()
.ok()
.and_then(|map: RwLockReadGuard<'_, WsShardMap>| map.get(key).cloned())?;
if room.subscribers.load(Ordering::Acquire) == 0 {
return None;
}
let frame: Arc<[u8]> = build_ws_server_frames(payload);
let delivered: usize = room
.ring
.lock()
.map(|mut ring: MutexGuard<'_, WsRoomRing>| ring.push(frame))
.unwrap_or(0);
if delivered > 0 {
room.notify.notify_waiters();
return Some(delivered);
}
None
}
pub(crate) fn room_count(&self) -> usize {
let Self { shards } = self;
let mut total: usize = 0;
for shard in shards.iter() {
if let Ok(map) = shard.map.read() {
total += map.len();
}
}
total
}
}
impl Clone for SparseWsHub {
fn clone(&self) -> Self {
let Self { inner } = self;
let next: OnceLock<Arc<SparseWsHubInner>> = OnceLock::new();
if let Some(existing) = inner.get() {
let _: Result<(), Arc<SparseWsHubInner>> =
next.set(Arc::new(existing.clone_snapshot()));
}
Self { inner: next }
}
}
impl SparseWsHub {
#[inline]
pub(crate) fn subscribe(&self, key: &str, capacity: usize) -> SparseWsSubscription {
let Self { inner } = self;
let hub: &Arc<SparseWsHubInner> = inner.get_or_init(|| Arc::new(SparseWsHubInner::new()));
hub.subscribe(key, capacity)
}
#[inline]
pub(crate) fn receiver_count(&self, key: &str) -> usize {
let Self { inner } = self;
inner
.get()
.map_or(0, |hub: &Arc<SparseWsHubInner>| hub.receiver_count(key))
}
#[inline]
pub(crate) fn try_send_payload(&self, key: &str, payload: &[u8]) -> Option<usize> {
let Self { inner } = self;
inner
.get()
.and_then(|hub: &Arc<SparseWsHubInner>| hub.try_send_payload(key, payload))
}
pub(crate) fn room_count(&self) -> usize {
let Self { inner } = self;
inner
.get()
.map_or(0, |hub: &Arc<SparseWsHubInner>| hub.room_count())
}
}
impl SparseWsSubscription {
#[inline]
pub(crate) fn try_recv(&mut self) -> Option<WsRoomRecv> {
let Self { room, cursor, .. } = self;
match room.ring.lock() {
Ok(mut ring) => ring.try_pop(cursor),
Err(_) => Some(WsRoomRecv::Closed),
}
}
pub(crate) async fn recv(&mut self) -> WsRoomRecv {
loop {
if let Some(item) = self.try_recv() {
return item;
}
let Self { room, cursor, .. } = self;
let notified: Notified<'_> = room.notify.notified();
let mut pinned: Pin<&mut Notified<'_>> = pin!(notified);
pinned.as_mut().enable();
if let Some(item) = match room.ring.lock() {
Ok(mut ring) => ring.try_pop(cursor),
Err(_) => Some(WsRoomRecv::Closed),
} {
return item;
}
pinned.await;
}
}
#[inline]
pub(crate) fn drain_queued_into(&mut self, out: &mut Vec<u8>, max_bytes: usize) -> bool {
let Self { room, cursor, .. } = self;
let Ok(mut ring) = room.ring.lock() else {
return true;
};
while out.len() < max_bytes {
match ring.try_pop(cursor) {
Some(WsRoomRecv::Frame(frame)) => out.extend_from_slice(&frame),
Some(WsRoomRecv::Lagged) => continue,
Some(WsRoomRecv::Closed) => return true,
None => break,
}
}
false
}
}
impl Drop for SparseWsSubscription {
fn drop(&mut self) {
let Self {
key,
room,
hub,
cursor,
} = self;
if let Ok(mut ring) = room.ring.lock() {
ring.unsubscribe(*cursor);
}
if room.subscribers.fetch_sub(1, Ordering::AcqRel) > 1 {
return;
}
let shard_idx: usize = ws_shard_index(key);
if let Ok(mut write_map) = hub.shards[shard_idx].map.write()
&& let Some(current) = write_map.get(key.as_ref())
&& Arc::ptr_eq(current, room)
&& current.subscribers.load(Ordering::Acquire) == 0
{
let _: Option<Arc<WsRoom>> = write_map.remove(key.as_ref());
}
}
}
impl Clone for WebSocket {
fn clone(&self) -> Self {
let Self {
broadcast_map,
sparse_hub,
} = self;
Self {
broadcast_map: broadcast_map.clone(),
sparse_hub: sparse_hub.clone(),
}
}
}
impl Debug for WebSocket {
fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
let Self {
broadcast_map,
sparse_hub,
} = self;
formatter
.debug_struct(WS_DEBUG_STRUCT_NAME)
.field(WS_DEBUG_BROADCAST_FIELD, broadcast_map)
.field(WS_DEBUG_SPARSE_ROOMS_FIELD, &sparse_hub.room_count())
.finish()
}
}
impl WebSocket {
#[inline(always)]
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> usize
where
B: BroadcastTypeTrait,
{
let Self {
broadcast_map,
sparse_hub,
} = self;
broadcast_type.with_key(|key: &str| {
sparse_hub
.receiver_count(key)
.saturating_add(broadcast_map.receiver_count(key).unwrap_or(0))
})
}
#[inline(always)]
pub fn receiver_count_before_connected<B>(&self, broadcast_type: BroadcastType<B>) -> usize
where
B: BroadcastTypeTrait,
{
let count: usize = self.receiver_count(broadcast_type);
count.clamp(0, usize::MAX - 1) + 1
}
#[inline(always)]
pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> usize
where
B: BroadcastTypeTrait,
{
let count: usize = self.receiver_count(broadcast_type);
count.clamp(1, usize::MAX) - 1
}
#[inline]
fn try_send_by_key(
&self,
key: &str,
data: Vec<u8>,
) -> Result<Option<usize>, SendError<Vec<u8>>> {
let Self {
broadcast_map,
sparse_hub,
} = self;
let sparse_sent: Option<usize> = sparse_hub.try_send_payload(key, &data);
let legacy_exists: bool = broadcast_map.receiver_count(key).is_some();
if !legacy_exists {
return Ok(sparse_sent);
}
match broadcast_map.try_send(key, data) {
Ok(Some(legacy_count)) => Ok(Some(sparse_sent.unwrap_or(0) + legacy_count)),
Ok(None) => Ok(sparse_sent),
Err(err) => match sparse_sent {
Some(sparse_count) => Ok(Some(sparse_count)),
None => Err(err),
},
}
}
#[inline]
fn try_send_slice(&self, key: &str, data: &[u8]) -> Result<Option<usize>, SendError<Vec<u8>>> {
let Self {
broadcast_map,
sparse_hub,
} = self;
let sparse_sent: Option<usize> = sparse_hub.try_send_payload(key, data);
if broadcast_map.receiver_count(key).is_none() {
return Ok(sparse_sent);
}
match broadcast_map.try_send(key, data.to_vec()) {
Ok(Some(legacy_count)) => Ok(Some(sparse_sent.unwrap_or(0) + legacy_count)),
Ok(None) => Ok(sparse_sent),
Err(err) => match sparse_sent {
Some(sparse_count) => Ok(Some(sparse_count)),
None => Err(err),
},
}
}
#[inline(always)]
pub fn try_send<T, B>(
&self,
broadcast_type: BroadcastType<B>,
data: T,
) -> Result<Option<usize>, SendError<Vec<u8>>>
where
T: Into<Vec<u8>>,
B: BroadcastTypeTrait,
{
broadcast_type.with_key(|key: &str| self.try_send_by_key(key, data.into()))
}
#[inline(always)]
pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<usize>
where
T: Into<Vec<u8>>,
B: BroadcastTypeTrait,
{
self.try_send(broadcast_type, data).unwrap()
}
#[cold]
async fn run_legacy_connection(
&self,
stream: &mut Stream,
ctx: &mut Context,
key: String,
mut legacy_rx: Receiver<Vec<u8>>,
connected_hook: ServerHookHandler,
hooks: (ServerHookHandler, ServerHookHandler, ServerHookHandler),
) {
let (request_hook, sended_hook, closed_hook): (
ServerHookHandler,
ServerHookHandler,
ServerHookHandler,
) = hooks;
let Self { broadcast_map, .. } = self;
let mut closed_called: bool = false;
let connected: bool = connected_hook(stream, ctx).await.is_continue();
drop(connected_hook);
if connected {
loop {
tokio::select! {
request_res = stream.try_get_websocket_request() => {
if let Ok(body) = request_res {
ctx.get_mut_request().set_body(body);
let is_reject: bool = request_hook(stream, ctx).await.is_reject();
let is_err: bool =
self.try_send_slice(&key, ctx.get_response().get_body()).is_err();
if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
break;
}
} else {
closed_called = true;
ctx.get_mut_response().get_mut_body().clear();
closed_hook(stream, ctx).await;
if !ctx.get_response().get_body().is_empty() {
let _: Result<Option<usize>, SendError<Vec<u8>>> =
self.try_send_slice(&key, ctx.get_response().get_body());
let _: Status = sended_hook(stream, ctx).await;
}
break;
}
},
msg_res = legacy_rx.recv() => {
match msg_res {
Ok(raw) => {
if !send_legacy_ws_frames(stream, &mut legacy_rx, raw).await {
break;
}
}
Err(RecvError::Lagged(_)) => continue,
Err(RecvError::Closed) => break,
}
}
}
}
}
if !closed_called {
ctx.get_mut_response().get_mut_body().clear();
closed_hook(stream, ctx).await;
if !ctx.get_response().get_body().is_empty() {
let body: Vec<u8> = take(ctx.get_mut_response().get_mut_body());
let _: Result<Option<usize>, SendError<Vec<u8>>> = self.try_send_by_key(&key, body);
}
}
drop(legacy_rx);
if broadcast_map.receiver_count(&key) == Some(0) {
let _: Option<Broadcast<Vec<u8>>> = broadcast_map.unsubscribe(&key);
}
stream.set_closed(true);
}
async fn run_sparse_loop(
&self,
stream: &mut Stream,
ctx: &mut Context,
sub: &mut SparseWsSubscription,
hooks: (&ServerHookHandler, &ServerHookHandler, &ServerHookHandler),
) -> bool {
let (request_hook, sended_hook, closed_hook): (
&ServerHookHandler,
&ServerHookHandler,
&ServerHookHandler,
) = hooks;
loop {
tokio::select! {
request_res = stream.try_get_websocket_request() => {
if let Ok(body) = request_res {
ctx.get_mut_request().set_body(body);
let is_reject: bool = request_hook(stream, ctx).await.is_reject();
let is_err: bool = self
.try_send_slice(&sub.key, ctx.get_response().get_body())
.is_err();
if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
return false;
}
} else {
ctx.get_mut_response().get_mut_body().clear();
closed_hook(stream, ctx).await;
if !ctx.get_response().get_body().is_empty() {
let _: Result<Option<usize>, SendError<Vec<u8>>> =
self.try_send_slice(&sub.key, ctx.get_response().get_body());
let _: Status = sended_hook(stream, ctx).await;
}
return true;
}
},
recv_step = sub.recv() => {
match recv_step {
WsRoomRecv::Frame(frame) => {
if !send_sparse_ws_frame(stream, sub, frame).await {
return false;
}
}
WsRoomRecv::Lagged => continue,
WsRoomRecv::Closed => return false,
}
}
}
}
}
pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
where
B: BroadcastTypeTrait,
{
let WebSocketConfig {
stream,
context: ctx,
capacity,
broadcast_type,
connected_hook,
request_hook,
sended_hook,
closed_hook,
}: WebSocketConfig<'_, B> = websocket_config;
if matches!(broadcast_type, BroadcastType::Unknown) {
stream.set_closed(true);
return;
}
let Self {
broadcast_map,
sparse_hub,
} = self;
let legacy_choice: Option<(String, Receiver<Vec<u8>>)> =
broadcast_type.with_key(|key: &str| {
broadcast_map
.subscribe(key)
.map(|rx: Receiver<Vec<u8>>| (key.to_owned(), rx))
});
if let Some((legacy_key, legacy_rx)) = legacy_choice {
drop(broadcast_type);
Box::pin(self.run_legacy_connection(
stream,
ctx,
legacy_key,
legacy_rx,
connected_hook,
(request_hook, sended_hook, closed_hook),
))
.await;
return;
}
let mut sub: SparseWsSubscription =
broadcast_type.with_key(|key: &str| sparse_hub.subscribe(key, capacity));
drop(broadcast_type);
let mut closed_called: bool = false;
let connected: bool = connected_hook(stream, ctx).await.is_continue();
drop(connected_hook);
if connected {
closed_called = self
.run_sparse_loop(
stream,
ctx,
&mut sub,
(&request_hook, &sended_hook, &closed_hook),
)
.await;
}
if !closed_called {
ctx.get_mut_response().get_mut_body().clear();
closed_hook(stream, ctx).await;
if !ctx.get_response().get_body().is_empty() {
let body: Vec<u8> = take(ctx.get_mut_response().get_mut_body());
let _: Result<Option<usize>, SendError<Vec<u8>>> =
self.try_send_by_key(&sub.key, body);
}
}
let key: Arc<str> = Arc::clone(&sub.key);
drop(sub);
if broadcast_map.receiver_count(key.as_ref()) == Some(0) {
let _: Option<Broadcast<Vec<u8>>> = broadcast_map.unsubscribe(key.as_ref());
}
stream.set_closed(true);
}
}
impl WebSocketPlugin {
pub fn init(websocket: WebSocket) -> &'static Self {
WEBSOCKET_PLUGIN.get_or_init(|| Self { websocket })
}
pub fn init_default() -> &'static Self {
WEBSOCKET_PLUGIN.get_or_init(Self::default)
}
pub fn get() -> Option<&'static Self> {
WEBSOCKET_PLUGIN.get()
}
pub fn get_websocket(&self) -> &WebSocket {
&self.websocket
}
}