Skip to main content

hyperlane_plugin_websocket/
impl.rs

1use super::*;
2
3/// Implements `fmt::Write` for [`StackKeyWriter`].
4impl Write for StackKeyWriter<'_> {
5    /// Copies `s` into the underlying stack byte buffer when capacity permits.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - UTF-8 chunk to append.
10    ///
11    /// # Returns
12    ///
13    /// - `fmt::Result` - `Ok(())` on success or `Err(fmt::Error)` on overflow.
14    #[inline]
15    fn write_str(&mut self, s: &str) -> fmt::Result {
16        let Self { buf, len } = self;
17        let bytes: &[u8] = s.as_bytes();
18        let next: usize = *len + bytes.len();
19        if next > buf.len() {
20            return Err(fmt::Error);
21        }
22        buf[*len..next].copy_from_slice(bytes);
23        *len = next;
24        Ok(())
25    }
26}
27
28/// Allows `String` to be used as a broadcast identifier.
29impl BroadcastTypeTrait for String {
30    /// Returns the underlying string slice without formatting or allocation.
31    ///
32    /// # Returns
33    ///
34    /// - `Option<&str>` - Always `Some(self.as_str())`.
35    #[inline(always)]
36    fn as_broadcast_str(&self) -> Option<&str> {
37        Some(self.as_str())
38    }
39
40    /// Writes the string slice directly without allocating.
41    ///
42    /// # Arguments
43    ///
44    /// - `&mut dyn Write` - Destination formatting writer.
45    ///
46    /// # Returns
47    ///
48    /// - `fmt::Result` - Formatting outcome.
49    #[inline]
50    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
51        f.write_str(self)
52    }
53}
54
55/// Allows string slices to be used as broadcast identifiers.
56impl BroadcastTypeTrait for &str {
57    /// Returns this string slice directly without formatting or allocation.
58    ///
59    /// # Returns
60    ///
61    /// - `Option<&str>` - Always `Some(self)`.
62    #[inline(always)]
63    fn as_broadcast_str(&self) -> Option<&str> {
64        Some(self)
65    }
66
67    /// Writes the string slice directly without allocating.
68    ///
69    /// # Arguments
70    ///
71    /// - `&mut dyn Write` - Destination formatting writer.
72    ///
73    /// # Returns
74    ///
75    /// - `fmt::Result` - Formatting outcome.
76    #[inline]
77    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
78        f.write_str(self)
79    }
80}
81
82/// Allows `char` to be used as a broadcast identifier.
83impl BroadcastTypeTrait for char {
84    /// Encodes this `char` directly into `buf` without `fmt::Write`.
85    ///
86    /// # Arguments
87    ///
88    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
89    ///
90    /// # Returns
91    ///
92    /// - `Option<usize>` - Written byte count if it fits.
93    #[inline(always)]
94    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
95        write_char_utf8_bytes(*self, buf)
96    }
97
98    /// Writes this `char` directly without allocating.
99    ///
100    /// # Arguments
101    ///
102    /// - `&mut dyn Write` - Destination formatting writer.
103    ///
104    /// # Returns
105    ///
106    /// - `fmt::Result` - Formatting outcome.
107    #[inline]
108    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
109        f.write_char(*self)
110    }
111}
112
113/// Allows `bool` to be used as a broadcast identifier.
114impl BroadcastTypeTrait for bool {
115    /// Encodes this `bool` directly into `buf` without `fmt::Write`.
116    ///
117    /// # Arguments
118    ///
119    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
120    ///
121    /// # Returns
122    ///
123    /// - `Option<usize>` - Written byte count if it fits.
124    #[inline(always)]
125    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
126        write_bool_bytes(*self, buf)
127    }
128
129    /// Writes this `bool` directly without allocating.
130    ///
131    /// # Arguments
132    ///
133    /// - `&mut dyn Write` - Destination formatting writer.
134    ///
135    /// # Returns
136    ///
137    /// - `fmt::Result` - Formatting outcome.
138    #[inline]
139    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
140        write!(f, "{self}")
141    }
142}
143
144/// Allows `i8` to be used as a broadcast identifier.
145impl BroadcastTypeTrait for i8 {
146    /// Formats this integer directly into `buf` without `fmt::Write`.
147    ///
148    /// # Arguments
149    ///
150    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
151    ///
152    /// # Returns
153    ///
154    /// - `Option<usize>` - Written byte count if it fits.
155    #[inline(always)]
156    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
157        write_i64_decimal_bytes(i64::from(*self), buf)
158    }
159
160    /// Writes this integer directly without allocating.
161    ///
162    /// # Arguments
163    ///
164    /// - `&mut dyn Write` - Destination formatting writer.
165    ///
166    /// # Returns
167    ///
168    /// - `fmt::Result` - Formatting outcome.
169    #[inline]
170    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
171        write!(f, "{self}")
172    }
173}
174
175/// Allows `i16` to be used as a broadcast identifier.
176impl BroadcastTypeTrait for i16 {
177    /// Formats this integer directly into `buf` without `fmt::Write`.
178    ///
179    /// # Arguments
180    ///
181    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
182    ///
183    /// # Returns
184    ///
185    /// - `Option<usize>` - Written byte count if it fits.
186    #[inline(always)]
187    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
188        write_i64_decimal_bytes(i64::from(*self), buf)
189    }
190
191    /// Writes this integer directly without allocating.
192    ///
193    /// # Arguments
194    ///
195    /// - `&mut dyn Write` - Destination formatting writer.
196    ///
197    /// # Returns
198    ///
199    /// - `fmt::Result` - Formatting outcome.
200    #[inline]
201    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
202        write!(f, "{self}")
203    }
204}
205
206/// Allows `i32` to be used as a broadcast identifier.
207impl BroadcastTypeTrait for i32 {
208    /// Formats this integer directly into `buf` without `fmt::Write`.
209    ///
210    /// # Arguments
211    ///
212    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
213    ///
214    /// # Returns
215    ///
216    /// - `Option<usize>` - Written byte count if it fits.
217    #[inline(always)]
218    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
219        write_i64_decimal_bytes(i64::from(*self), buf)
220    }
221
222    /// Writes this integer directly without allocating.
223    ///
224    /// # Arguments
225    ///
226    /// - `&mut dyn Write` - Destination formatting writer.
227    ///
228    /// # Returns
229    ///
230    /// - `fmt::Result` - Formatting outcome.
231    #[inline]
232    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
233        write!(f, "{self}")
234    }
235}
236
237/// Allows `i64` to be used as a broadcast identifier.
238impl BroadcastTypeTrait for i64 {
239    /// Formats this integer directly into `buf` without `fmt::Write`.
240    ///
241    /// # Arguments
242    ///
243    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
244    ///
245    /// # Returns
246    ///
247    /// - `Option<usize>` - Written byte count if it fits.
248    #[inline(always)]
249    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
250        write_i64_decimal_bytes(*self, buf)
251    }
252
253    /// Writes this integer directly without allocating.
254    ///
255    /// # Arguments
256    ///
257    /// - `&mut dyn Write` - Destination formatting writer.
258    ///
259    /// # Returns
260    ///
261    /// - `fmt::Result` - Formatting outcome.
262    #[inline]
263    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
264        write!(f, "{self}")
265    }
266}
267
268/// Allows `i128` to be used as a broadcast identifier.
269impl BroadcastTypeTrait for i128 {
270    /// Formats this integer directly into `buf` without `fmt::Write`.
271    ///
272    /// # Arguments
273    ///
274    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
275    ///
276    /// # Returns
277    ///
278    /// - `Option<usize>` - Written byte count if it fits.
279    #[inline(always)]
280    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
281        write_i128_decimal_bytes(*self, buf)
282    }
283
284    /// Writes this integer directly without allocating.
285    ///
286    /// # Arguments
287    ///
288    /// - `&mut dyn Write` - Destination formatting writer.
289    ///
290    /// # Returns
291    ///
292    /// - `fmt::Result` - Formatting outcome.
293    #[inline]
294    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
295        write!(f, "{self}")
296    }
297}
298
299/// Allows `isize` to be used as a broadcast identifier.
300impl BroadcastTypeTrait for isize {
301    /// Formats this integer directly into `buf` without `fmt::Write`.
302    ///
303    /// # Arguments
304    ///
305    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
306    ///
307    /// # Returns
308    ///
309    /// - `Option<usize>` - Written byte count if it fits.
310    #[inline(always)]
311    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
312        write_i64_decimal_bytes(*self as i64, buf)
313    }
314
315    /// Writes this integer directly without allocating.
316    ///
317    /// # Arguments
318    ///
319    /// - `&mut dyn Write` - Destination formatting writer.
320    ///
321    /// # Returns
322    ///
323    /// - `fmt::Result` - Formatting outcome.
324    #[inline]
325    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
326        write!(f, "{self}")
327    }
328}
329
330/// Allows `u8` to be used as a broadcast identifier.
331impl BroadcastTypeTrait for u8 {
332    /// Formats this integer directly into `buf` without `fmt::Write`.
333    ///
334    /// # Arguments
335    ///
336    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
337    ///
338    /// # Returns
339    ///
340    /// - `Option<usize>` - Written byte count if it fits.
341    #[inline(always)]
342    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
343        write_u64_decimal_bytes(u64::from(*self), buf)
344    }
345
346    /// Writes this integer directly without allocating.
347    ///
348    /// # Arguments
349    ///
350    /// - `&mut dyn Write` - Destination formatting writer.
351    ///
352    /// # Returns
353    ///
354    /// - `fmt::Result` - Formatting outcome.
355    #[inline]
356    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
357        write!(f, "{self}")
358    }
359}
360
361/// Allows `u16` to be used as a broadcast identifier.
362impl BroadcastTypeTrait for u16 {
363    /// Formats this integer directly into `buf` without `fmt::Write`.
364    ///
365    /// # Arguments
366    ///
367    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
368    ///
369    /// # Returns
370    ///
371    /// - `Option<usize>` - Written byte count if it fits.
372    #[inline(always)]
373    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
374        write_u64_decimal_bytes(u64::from(*self), buf)
375    }
376
377    /// Writes this integer directly without allocating.
378    ///
379    /// # Arguments
380    ///
381    /// - `&mut dyn Write` - Destination formatting writer.
382    ///
383    /// # Returns
384    ///
385    /// - `fmt::Result` - Formatting outcome.
386    #[inline]
387    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
388        write!(f, "{self}")
389    }
390}
391
392/// Allows `u32` to be used as a broadcast identifier.
393impl BroadcastTypeTrait for u32 {
394    /// Formats this integer directly into `buf` without `fmt::Write`.
395    ///
396    /// # Arguments
397    ///
398    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
399    ///
400    /// # Returns
401    ///
402    /// - `Option<usize>` - Written byte count if it fits.
403    #[inline(always)]
404    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
405        write_u64_decimal_bytes(u64::from(*self), buf)
406    }
407
408    /// Writes this integer directly without allocating.
409    ///
410    /// # Arguments
411    ///
412    /// - `&mut dyn Write` - Destination formatting writer.
413    ///
414    /// # Returns
415    ///
416    /// - `fmt::Result` - Formatting outcome.
417    #[inline]
418    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
419        write!(f, "{self}")
420    }
421}
422
423/// Allows `u64` to be used as a broadcast identifier.
424impl BroadcastTypeTrait for u64 {
425    /// Formats this integer directly into `buf` without `fmt::Write`.
426    ///
427    /// # Arguments
428    ///
429    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
430    ///
431    /// # Returns
432    ///
433    /// - `Option<usize>` - Written byte count if it fits.
434    #[inline(always)]
435    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
436        write_u64_decimal_bytes(*self, buf)
437    }
438
439    /// Writes this integer directly without allocating.
440    ///
441    /// # Arguments
442    ///
443    /// - `&mut dyn Write` - Destination formatting writer.
444    ///
445    /// # Returns
446    ///
447    /// - `fmt::Result` - Formatting outcome.
448    #[inline]
449    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
450        write!(f, "{self}")
451    }
452}
453
454/// Allows `u128` to be used as a broadcast identifier.
455impl BroadcastTypeTrait for u128 {
456    /// Formats this integer directly into `buf` without `fmt::Write`.
457    ///
458    /// # Arguments
459    ///
460    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
461    ///
462    /// # Returns
463    ///
464    /// - `Option<usize>` - Written byte count if it fits.
465    #[inline(always)]
466    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
467        write_u128_decimal_bytes(*self, buf)
468    }
469
470    /// Writes this integer directly without allocating.
471    ///
472    /// # Arguments
473    ///
474    /// - `&mut dyn Write` - Destination formatting writer.
475    ///
476    /// # Returns
477    ///
478    /// - `fmt::Result` - Formatting outcome.
479    #[inline]
480    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
481        write!(f, "{self}")
482    }
483}
484
485/// Allows `usize` to be used as a broadcast identifier.
486impl BroadcastTypeTrait for usize {
487    /// Formats this integer directly into `buf` without `fmt::Write`.
488    ///
489    /// # Arguments
490    ///
491    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
492    ///
493    /// # Returns
494    ///
495    /// - `Option<usize>` - Written byte count if it fits.
496    #[inline(always)]
497    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
498        write_u64_decimal_bytes(*self as u64, buf)
499    }
500
501    /// Writes this integer directly without allocating.
502    ///
503    /// # Arguments
504    ///
505    /// - `&mut dyn Write` - Destination formatting writer.
506    ///
507    /// # Returns
508    ///
509    /// - `fmt::Result` - Formatting outcome.
510    #[inline]
511    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
512        write!(f, "{self}")
513    }
514}
515
516/// Allows `f32` to be used as a broadcast identifier.
517impl BroadcastTypeTrait for f32 {
518    /// Writes this float directly without allocating.
519    ///
520    /// # Arguments
521    ///
522    /// - `&mut dyn Write` - Destination formatting writer.
523    ///
524    /// # Returns
525    ///
526    /// - `fmt::Result` - Formatting outcome.
527    #[inline]
528    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
529        write!(f, "{self}")
530    }
531}
532
533/// Allows `f64` to be used as a broadcast identifier.
534impl BroadcastTypeTrait for f64 {
535    /// Writes this float directly without allocating.
536    ///
537    /// # Arguments
538    ///
539    /// - `&mut dyn Write` - Destination formatting writer.
540    ///
541    /// # Returns
542    ///
543    /// - `fmt::Result` - Formatting outcome.
544    #[inline]
545    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
546        write!(f, "{self}")
547    }
548}
549
550/// Allows `IpAddr` to be used as a broadcast identifier.
551impl BroadcastTypeTrait for IpAddr {
552    /// Writes this IP address directly without allocating.
553    ///
554    /// # Arguments
555    ///
556    /// - `&mut dyn Write` - Destination formatting writer.
557    ///
558    /// # Returns
559    ///
560    /// - `fmt::Result` - Formatting outcome.
561    #[inline]
562    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
563        write!(f, "{self}")
564    }
565}
566
567/// Allows `Ipv4Addr` to be used as a broadcast identifier.
568impl BroadcastTypeTrait for Ipv4Addr {
569    /// Writes this IPv4 address directly without allocating.
570    ///
571    /// # Arguments
572    ///
573    /// - `&mut dyn Write` - Destination formatting writer.
574    ///
575    /// # Returns
576    ///
577    /// - `fmt::Result` - Formatting outcome.
578    #[inline]
579    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
580        write!(f, "{self}")
581    }
582}
583
584/// Allows `Ipv6Addr` to be used as a broadcast identifier.
585impl BroadcastTypeTrait for Ipv6Addr {
586    /// Writes this IPv6 address directly without allocating.
587    ///
588    /// # Arguments
589    ///
590    /// - `&mut dyn Write` - Destination formatting writer.
591    ///
592    /// # Returns
593    ///
594    /// - `fmt::Result` - Formatting outcome.
595    #[inline]
596    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
597        write!(f, "{self}")
598    }
599}
600
601/// Allows `SocketAddr` to be used as a broadcast identifier.
602impl BroadcastTypeTrait for SocketAddr {
603    /// Writes this socket address directly without allocating.
604    ///
605    /// # Arguments
606    ///
607    /// - `&mut dyn Write` - Destination formatting writer.
608    ///
609    /// # Returns
610    ///
611    /// - `fmt::Result` - Formatting outcome.
612    #[inline]
613    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
614        write!(f, "{self}")
615    }
616}
617
618/// Allows `NonZeroU8` to be used as a broadcast identifier.
619impl BroadcastTypeTrait for NonZeroU8 {
620    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
621    ///
622    /// # Arguments
623    ///
624    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
625    ///
626    /// # Returns
627    ///
628    /// - `Option<usize>` - Written byte count if it fits.
629    #[inline(always)]
630    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
631        write_u64_decimal_bytes(u64::from(self.get()), buf)
632    }
633
634    /// Writes this non-zero integer directly without allocating.
635    ///
636    /// # Arguments
637    ///
638    /// - `&mut dyn Write` - Destination formatting writer.
639    ///
640    /// # Returns
641    ///
642    /// - `fmt::Result` - Formatting outcome.
643    #[inline]
644    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
645        write!(f, "{self}")
646    }
647}
648
649/// Allows `NonZeroU16` to be used as a broadcast identifier.
650impl BroadcastTypeTrait for NonZeroU16 {
651    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
652    ///
653    /// # Arguments
654    ///
655    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
656    ///
657    /// # Returns
658    ///
659    /// - `Option<usize>` - Written byte count if it fits.
660    #[inline(always)]
661    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
662        write_u64_decimal_bytes(u64::from(self.get()), buf)
663    }
664
665    /// Writes this non-zero integer directly without allocating.
666    ///
667    /// # Arguments
668    ///
669    /// - `&mut dyn Write` - Destination formatting writer.
670    ///
671    /// # Returns
672    ///
673    /// - `fmt::Result` - Formatting outcome.
674    #[inline]
675    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
676        write!(f, "{self}")
677    }
678}
679
680/// Allows `NonZeroU32` to be used as a broadcast identifier.
681impl BroadcastTypeTrait for NonZeroU32 {
682    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
683    ///
684    /// # Arguments
685    ///
686    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
687    ///
688    /// # Returns
689    ///
690    /// - `Option<usize>` - Written byte count if it fits.
691    #[inline(always)]
692    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
693        write_u64_decimal_bytes(u64::from(self.get()), buf)
694    }
695
696    /// Writes this non-zero integer directly without allocating.
697    ///
698    /// # Arguments
699    ///
700    /// - `&mut dyn Write` - Destination formatting writer.
701    ///
702    /// # Returns
703    ///
704    /// - `fmt::Result` - Formatting outcome.
705    #[inline]
706    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
707        write!(f, "{self}")
708    }
709}
710
711/// Allows `NonZeroU64` to be used as a broadcast identifier.
712impl BroadcastTypeTrait for NonZeroU64 {
713    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
714    ///
715    /// # Arguments
716    ///
717    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
718    ///
719    /// # Returns
720    ///
721    /// - `Option<usize>` - Written byte count if it fits.
722    #[inline(always)]
723    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
724        write_u64_decimal_bytes(self.get(), buf)
725    }
726
727    /// Writes this non-zero integer directly without allocating.
728    ///
729    /// # Arguments
730    ///
731    /// - `&mut dyn Write` - Destination formatting writer.
732    ///
733    /// # Returns
734    ///
735    /// - `fmt::Result` - Formatting outcome.
736    #[inline]
737    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
738        write!(f, "{self}")
739    }
740}
741
742/// Allows `NonZeroU128` to be used as a broadcast identifier.
743impl BroadcastTypeTrait for NonZeroU128 {
744    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
745    ///
746    /// # Arguments
747    ///
748    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
749    ///
750    /// # Returns
751    ///
752    /// - `Option<usize>` - Written byte count if it fits.
753    #[inline(always)]
754    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
755        write_u128_decimal_bytes(self.get(), buf)
756    }
757
758    /// Writes this non-zero integer directly without allocating.
759    ///
760    /// # Arguments
761    ///
762    /// - `&mut dyn Write` - Destination formatting writer.
763    ///
764    /// # Returns
765    ///
766    /// - `fmt::Result` - Formatting outcome.
767    #[inline]
768    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
769        write!(f, "{self}")
770    }
771}
772
773/// Allows `NonZeroUsize` to be used as a broadcast identifier.
774impl BroadcastTypeTrait for NonZeroUsize {
775    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
776    ///
777    /// # Arguments
778    ///
779    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
780    ///
781    /// # Returns
782    ///
783    /// - `Option<usize>` - Written byte count if it fits.
784    #[inline(always)]
785    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
786        write_u64_decimal_bytes(self.get() as u64, buf)
787    }
788
789    /// Writes this non-zero integer directly without allocating.
790    ///
791    /// # Arguments
792    ///
793    /// - `&mut dyn Write` - Destination formatting writer.
794    ///
795    /// # Returns
796    ///
797    /// - `fmt::Result` - Formatting outcome.
798    #[inline]
799    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
800        write!(f, "{self}")
801    }
802}
803
804/// Allows `NonZeroI8` to be used as a broadcast identifier.
805impl BroadcastTypeTrait for NonZeroI8 {
806    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
807    ///
808    /// # Arguments
809    ///
810    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
811    ///
812    /// # Returns
813    ///
814    /// - `Option<usize>` - Written byte count if it fits.
815    #[inline(always)]
816    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
817        write_i64_decimal_bytes(i64::from(self.get()), buf)
818    }
819
820    /// Writes this non-zero integer directly without allocating.
821    ///
822    /// # Arguments
823    ///
824    /// - `&mut dyn Write` - Destination formatting writer.
825    ///
826    /// # Returns
827    ///
828    /// - `fmt::Result` - Formatting outcome.
829    #[inline]
830    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
831        write!(f, "{self}")
832    }
833}
834
835/// Allows `NonZeroI16` to be used as a broadcast identifier.
836impl BroadcastTypeTrait for NonZeroI16 {
837    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
838    ///
839    /// # Arguments
840    ///
841    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
842    ///
843    /// # Returns
844    ///
845    /// - `Option<usize>` - Written byte count if it fits.
846    #[inline(always)]
847    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
848        write_i64_decimal_bytes(i64::from(self.get()), buf)
849    }
850
851    /// Writes this non-zero integer directly without allocating.
852    ///
853    /// # Arguments
854    ///
855    /// - `&mut dyn Write` - Destination formatting writer.
856    ///
857    /// # Returns
858    ///
859    /// - `fmt::Result` - Formatting outcome.
860    #[inline]
861    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
862        write!(f, "{self}")
863    }
864}
865
866/// Allows `NonZeroI32` to be used as a broadcast identifier.
867impl BroadcastTypeTrait for NonZeroI32 {
868    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
869    ///
870    /// # Arguments
871    ///
872    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
873    ///
874    /// # Returns
875    ///
876    /// - `Option<usize>` - Written byte count if it fits.
877    #[inline(always)]
878    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
879        write_i64_decimal_bytes(i64::from(self.get()), buf)
880    }
881
882    /// Writes this non-zero integer directly without allocating.
883    ///
884    /// # Arguments
885    ///
886    /// - `&mut dyn Write` - Destination formatting writer.
887    ///
888    /// # Returns
889    ///
890    /// - `fmt::Result` - Formatting outcome.
891    #[inline]
892    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
893        write!(f, "{self}")
894    }
895}
896
897/// Allows `NonZeroI64` to be used as a broadcast identifier.
898impl BroadcastTypeTrait for NonZeroI64 {
899    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
900    ///
901    /// # Arguments
902    ///
903    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
904    ///
905    /// # Returns
906    ///
907    /// - `Option<usize>` - Written byte count if it fits.
908    #[inline(always)]
909    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
910        write_i64_decimal_bytes(self.get(), buf)
911    }
912
913    /// Writes this non-zero integer directly without allocating.
914    ///
915    /// # Arguments
916    ///
917    /// - `&mut dyn Write` - Destination formatting writer.
918    ///
919    /// # Returns
920    ///
921    /// - `fmt::Result` - Formatting outcome.
922    #[inline]
923    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
924        write!(f, "{self}")
925    }
926}
927
928/// Allows `NonZeroI128` to be used as a broadcast identifier.
929impl BroadcastTypeTrait for NonZeroI128 {
930    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
931    ///
932    /// # Arguments
933    ///
934    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
935    ///
936    /// # Returns
937    ///
938    /// - `Option<usize>` - Written byte count if it fits.
939    #[inline(always)]
940    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
941        write_i128_decimal_bytes(self.get(), buf)
942    }
943
944    /// Writes this non-zero integer directly without allocating.
945    ///
946    /// # Arguments
947    ///
948    /// - `&mut dyn Write` - Destination formatting writer.
949    ///
950    /// # Returns
951    ///
952    /// - `fmt::Result` - Formatting outcome.
953    #[inline]
954    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
955        write!(f, "{self}")
956    }
957}
958
959/// Allows `NonZeroIsize` to be used as a broadcast identifier.
960impl BroadcastTypeTrait for NonZeroIsize {
961    /// Formats this non-zero integer directly into `buf` without `fmt::Write`.
962    ///
963    /// # Arguments
964    ///
965    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
966    ///
967    /// # Returns
968    ///
969    /// - `Option<usize>` - Written byte count if it fits.
970    #[inline(always)]
971    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
972        write_i64_decimal_bytes(self.get() as i64, buf)
973    }
974
975    /// Writes this non-zero integer directly without allocating.
976    ///
977    /// # Arguments
978    ///
979    /// - `&mut dyn Write` - Destination formatting writer.
980    ///
981    /// # Returns
982    ///
983    /// - `fmt::Result` - Formatting outcome.
984    #[inline]
985    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
986        write!(f, "{self}")
987    }
988}
989
990/// Allows `Infallible` to be used as a broadcast identifier.
991impl BroadcastTypeTrait for Infallible {}
992
993/// Allows references to `String` to be used as broadcast identifiers.
994impl BroadcastTypeTrait for &String {
995    /// Returns the referenced string slice directly without formatting or allocation.
996    ///
997    /// # Returns
998    ///
999    /// - `Option<&str>` - Always `Some(self.as_str())`.
1000    #[inline(always)]
1001    fn as_broadcast_str(&self) -> Option<&str> {
1002        Some(self.as_str())
1003    }
1004
1005    /// Writes the referenced string directly without allocating.
1006    ///
1007    /// # Arguments
1008    ///
1009    /// - `&mut dyn Write` - Destination formatting writer.
1010    ///
1011    /// # Returns
1012    ///
1013    /// - `fmt::Result` - Formatting outcome.
1014    #[inline]
1015    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1016        f.write_str(self)
1017    }
1018}
1019
1020/// Allows double references to string slices to be used as broadcast identifiers.
1021impl BroadcastTypeTrait for &&str {
1022    /// Returns the referenced string slice directly without formatting or allocation.
1023    ///
1024    /// # Returns
1025    ///
1026    /// - `Option<&str>` - Always `Some(self)`.
1027    #[inline(always)]
1028    fn as_broadcast_str(&self) -> Option<&str> {
1029        Some(self)
1030    }
1031
1032    /// Writes the referenced string slice directly without allocating.
1033    ///
1034    /// # Arguments
1035    ///
1036    /// - `&mut dyn Write` - Destination formatting writer.
1037    ///
1038    /// # Returns
1039    ///
1040    /// - `fmt::Result` - Formatting outcome.
1041    #[inline]
1042    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1043        f.write_str(self)
1044    }
1045}
1046
1047/// Allows references to `char` to be used as broadcast identifiers.
1048impl BroadcastTypeTrait for &char {
1049    /// Encodes the referenced `char` directly into `buf` without allocating.
1050    ///
1051    /// # Arguments
1052    ///
1053    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1054    ///
1055    /// # Returns
1056    ///
1057    /// - `Option<usize>` - Written byte count if it fits.
1058    #[inline(always)]
1059    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1060        (**self).write_broadcast_bytes(buf)
1061    }
1062
1063    /// Writes the referenced `char` directly without allocating.
1064    ///
1065    /// # Arguments
1066    ///
1067    /// - `&mut dyn Write` - Destination formatting writer.
1068    ///
1069    /// # Returns
1070    ///
1071    /// - `fmt::Result` - Formatting outcome.
1072    #[inline]
1073    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1074        (**self).write_broadcast_key(f)
1075    }
1076}
1077
1078/// Allows references to `bool` to be used as broadcast identifiers.
1079impl BroadcastTypeTrait for &bool {
1080    /// Encodes the referenced `bool` directly into `buf` without allocating.
1081    ///
1082    /// # Arguments
1083    ///
1084    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1085    ///
1086    /// # Returns
1087    ///
1088    /// - `Option<usize>` - Written byte count if it fits.
1089    #[inline(always)]
1090    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1091        (**self).write_broadcast_bytes(buf)
1092    }
1093
1094    /// Writes the referenced `bool` directly without allocating.
1095    ///
1096    /// # Arguments
1097    ///
1098    /// - `&mut dyn Write` - Destination formatting writer.
1099    ///
1100    /// # Returns
1101    ///
1102    /// - `fmt::Result` - Formatting outcome.
1103    #[inline]
1104    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1105        (**self).write_broadcast_key(f)
1106    }
1107}
1108
1109/// Allows references to `i8` to be used as broadcast identifiers.
1110impl BroadcastTypeTrait for &i8 {
1111    /// Formats the referenced integer directly into `buf` without allocating.
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `Option<usize>` - Written byte count if it fits.
1120    #[inline(always)]
1121    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1122        (**self).write_broadcast_bytes(buf)
1123    }
1124
1125    /// Writes the referenced integer directly without allocating.
1126    ///
1127    /// # Arguments
1128    ///
1129    /// - `&mut dyn Write` - Destination formatting writer.
1130    ///
1131    /// # Returns
1132    ///
1133    /// - `fmt::Result` - Formatting outcome.
1134    #[inline]
1135    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1136        (**self).write_broadcast_key(f)
1137    }
1138}
1139
1140/// Allows references to `i16` to be used as broadcast identifiers.
1141impl BroadcastTypeTrait for &i16 {
1142    /// Formats the referenced integer directly into `buf` without allocating.
1143    ///
1144    /// # Arguments
1145    ///
1146    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1147    ///
1148    /// # Returns
1149    ///
1150    /// - `Option<usize>` - Written byte count if it fits.
1151    #[inline(always)]
1152    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1153        (**self).write_broadcast_bytes(buf)
1154    }
1155
1156    /// Writes the referenced integer directly without allocating.
1157    ///
1158    /// # Arguments
1159    ///
1160    /// - `&mut dyn Write` - Destination formatting writer.
1161    ///
1162    /// # Returns
1163    ///
1164    /// - `fmt::Result` - Formatting outcome.
1165    #[inline]
1166    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1167        (**self).write_broadcast_key(f)
1168    }
1169}
1170
1171/// Allows references to `i32` to be used as broadcast identifiers.
1172impl BroadcastTypeTrait for &i32 {
1173    /// Formats the referenced integer directly into `buf` without allocating.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1178    ///
1179    /// # Returns
1180    ///
1181    /// - `Option<usize>` - Written byte count if it fits.
1182    #[inline(always)]
1183    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1184        (**self).write_broadcast_bytes(buf)
1185    }
1186
1187    /// Writes the referenced integer directly without allocating.
1188    ///
1189    /// # Arguments
1190    ///
1191    /// - `&mut dyn Write` - Destination formatting writer.
1192    ///
1193    /// # Returns
1194    ///
1195    /// - `fmt::Result` - Formatting outcome.
1196    #[inline]
1197    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1198        (**self).write_broadcast_key(f)
1199    }
1200}
1201
1202/// Allows references to `i64` to be used as broadcast identifiers.
1203impl BroadcastTypeTrait for &i64 {
1204    /// Formats the referenced integer directly into `buf` without allocating.
1205    ///
1206    /// # Arguments
1207    ///
1208    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1209    ///
1210    /// # Returns
1211    ///
1212    /// - `Option<usize>` - Written byte count if it fits.
1213    #[inline(always)]
1214    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1215        (**self).write_broadcast_bytes(buf)
1216    }
1217
1218    /// Writes the referenced integer directly without allocating.
1219    ///
1220    /// # Arguments
1221    ///
1222    /// - `&mut dyn Write` - Destination formatting writer.
1223    ///
1224    /// # Returns
1225    ///
1226    /// - `fmt::Result` - Formatting outcome.
1227    #[inline]
1228    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1229        (**self).write_broadcast_key(f)
1230    }
1231}
1232
1233/// Allows references to `i128` to be used as broadcast identifiers.
1234impl BroadcastTypeTrait for &i128 {
1235    /// Formats the referenced integer directly into `buf` without allocating.
1236    ///
1237    /// # Arguments
1238    ///
1239    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1240    ///
1241    /// # Returns
1242    ///
1243    /// - `Option<usize>` - Written byte count if it fits.
1244    #[inline(always)]
1245    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1246        (**self).write_broadcast_bytes(buf)
1247    }
1248
1249    /// Writes the referenced integer directly without allocating.
1250    ///
1251    /// # Arguments
1252    ///
1253    /// - `&mut dyn Write` - Destination formatting writer.
1254    ///
1255    /// # Returns
1256    ///
1257    /// - `fmt::Result` - Formatting outcome.
1258    #[inline]
1259    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1260        (**self).write_broadcast_key(f)
1261    }
1262}
1263
1264/// Allows references to `isize` to be used as broadcast identifiers.
1265impl BroadcastTypeTrait for &isize {
1266    /// Formats the referenced integer directly into `buf` without allocating.
1267    ///
1268    /// # Arguments
1269    ///
1270    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1271    ///
1272    /// # Returns
1273    ///
1274    /// - `Option<usize>` - Written byte count if it fits.
1275    #[inline(always)]
1276    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1277        (**self).write_broadcast_bytes(buf)
1278    }
1279
1280    /// Writes the referenced integer directly without allocating.
1281    ///
1282    /// # Arguments
1283    ///
1284    /// - `&mut dyn Write` - Destination formatting writer.
1285    ///
1286    /// # Returns
1287    ///
1288    /// - `fmt::Result` - Formatting outcome.
1289    #[inline]
1290    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1291        (**self).write_broadcast_key(f)
1292    }
1293}
1294
1295/// Allows references to `u8` to be used as broadcast identifiers.
1296impl BroadcastTypeTrait for &u8 {
1297    /// Formats the referenced integer directly into `buf` without allocating.
1298    ///
1299    /// # Arguments
1300    ///
1301    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1302    ///
1303    /// # Returns
1304    ///
1305    /// - `Option<usize>` - Written byte count if it fits.
1306    #[inline(always)]
1307    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1308        (**self).write_broadcast_bytes(buf)
1309    }
1310
1311    /// Writes the referenced integer directly without allocating.
1312    ///
1313    /// # Arguments
1314    ///
1315    /// - `&mut dyn Write` - Destination formatting writer.
1316    ///
1317    /// # Returns
1318    ///
1319    /// - `fmt::Result` - Formatting outcome.
1320    #[inline]
1321    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1322        (**self).write_broadcast_key(f)
1323    }
1324}
1325
1326/// Allows references to `u16` to be used as broadcast identifiers.
1327impl BroadcastTypeTrait for &u16 {
1328    /// Formats the referenced integer directly into `buf` without allocating.
1329    ///
1330    /// # Arguments
1331    ///
1332    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1333    ///
1334    /// # Returns
1335    ///
1336    /// - `Option<usize>` - Written byte count if it fits.
1337    #[inline(always)]
1338    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1339        (**self).write_broadcast_bytes(buf)
1340    }
1341
1342    /// Writes the referenced integer directly without allocating.
1343    ///
1344    /// # Arguments
1345    ///
1346    /// - `&mut dyn Write` - Destination formatting writer.
1347    ///
1348    /// # Returns
1349    ///
1350    /// - `fmt::Result` - Formatting outcome.
1351    #[inline]
1352    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1353        (**self).write_broadcast_key(f)
1354    }
1355}
1356
1357/// Allows references to `u32` to be used as broadcast identifiers.
1358impl BroadcastTypeTrait for &u32 {
1359    /// Formats the referenced integer directly into `buf` without allocating.
1360    ///
1361    /// # Arguments
1362    ///
1363    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1364    ///
1365    /// # Returns
1366    ///
1367    /// - `Option<usize>` - Written byte count if it fits.
1368    #[inline(always)]
1369    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1370        (**self).write_broadcast_bytes(buf)
1371    }
1372
1373    /// Writes the referenced integer directly without allocating.
1374    ///
1375    /// # Arguments
1376    ///
1377    /// - `&mut dyn Write` - Destination formatting writer.
1378    ///
1379    /// # Returns
1380    ///
1381    /// - `fmt::Result` - Formatting outcome.
1382    #[inline]
1383    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1384        (**self).write_broadcast_key(f)
1385    }
1386}
1387
1388/// Implements `BroadcastTypeTrait` for `&u64`.
1389impl BroadcastTypeTrait for &u64 {
1390    /// Formats the referenced integer directly into `buf` without allocating.
1391    ///
1392    /// # Arguments
1393    ///
1394    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1395    ///
1396    /// # Returns
1397    ///
1398    /// - `Option<usize>` - Written byte count if it fits.
1399    #[inline(always)]
1400    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1401        (**self).write_broadcast_bytes(buf)
1402    }
1403
1404    /// Writes the referenced integer directly without allocating.
1405    ///
1406    /// # Arguments
1407    ///
1408    /// - `&mut dyn Write` - Destination formatting writer.
1409    ///
1410    /// # Returns
1411    ///
1412    /// - `fmt::Result` - Formatting outcome.
1413    #[inline]
1414    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1415        (**self).write_broadcast_key(f)
1416    }
1417}
1418
1419/// Implements `BroadcastTypeTrait` for `&u128`.
1420impl BroadcastTypeTrait for &u128 {
1421    /// Formats the referenced integer directly into `buf` without allocating.
1422    ///
1423    /// # Arguments
1424    ///
1425    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1426    ///
1427    /// # Returns
1428    ///
1429    /// - `Option<usize>` - Written byte count if it fits.
1430    #[inline(always)]
1431    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1432        (**self).write_broadcast_bytes(buf)
1433    }
1434
1435    /// Writes the referenced integer directly without allocating.
1436    ///
1437    /// # Arguments
1438    ///
1439    /// - `&mut dyn Write` - Destination formatting writer.
1440    ///
1441    /// # Returns
1442    ///
1443    /// - `fmt::Result` - Formatting outcome.
1444    #[inline]
1445    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1446        (**self).write_broadcast_key(f)
1447    }
1448}
1449
1450/// Implements `BroadcastTypeTrait` for `&usize`.
1451impl BroadcastTypeTrait for &usize {
1452    /// Formats the referenced integer directly into `buf` without allocating.
1453    ///
1454    /// # Arguments
1455    ///
1456    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1457    ///
1458    /// # Returns
1459    ///
1460    /// - `Option<usize>` - Written byte count if it fits.
1461    #[inline(always)]
1462    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1463        (**self).write_broadcast_bytes(buf)
1464    }
1465
1466    /// Writes the referenced integer directly without allocating.
1467    ///
1468    /// # Arguments
1469    ///
1470    /// - `&mut dyn Write` - Destination formatting writer.
1471    ///
1472    /// # Returns
1473    ///
1474    /// - `fmt::Result` - Formatting outcome.
1475    #[inline]
1476    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1477        (**self).write_broadcast_key(f)
1478    }
1479}
1480
1481/// Implements `BroadcastTypeTrait` for `&f32`.
1482impl BroadcastTypeTrait for &f32 {
1483    /// Writes the referenced float directly without allocating.
1484    ///
1485    /// # Arguments
1486    ///
1487    /// - `&mut dyn Write` - Destination formatting writer.
1488    ///
1489    /// # Returns
1490    ///
1491    /// - `fmt::Result` - Formatting outcome.
1492    #[inline]
1493    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1494        (**self).write_broadcast_key(f)
1495    }
1496}
1497
1498/// Implements `BroadcastTypeTrait` for `&f64`.
1499impl BroadcastTypeTrait for &f64 {
1500    /// Writes the referenced float directly without allocating.
1501    ///
1502    /// # Arguments
1503    ///
1504    /// - `&mut dyn Write` - Destination formatting writer.
1505    ///
1506    /// # Returns
1507    ///
1508    /// - `fmt::Result` - Formatting outcome.
1509    #[inline]
1510    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1511        (**self).write_broadcast_key(f)
1512    }
1513}
1514
1515/// Implements `BroadcastTypeTrait` for `&IpAddr`.
1516impl BroadcastTypeTrait for &IpAddr {
1517    /// Writes the referenced IP address directly without allocating.
1518    ///
1519    /// # Arguments
1520    ///
1521    /// - `&mut dyn Write` - Destination formatting writer.
1522    ///
1523    /// # Returns
1524    ///
1525    /// - `fmt::Result` - Formatting outcome.
1526    #[inline]
1527    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1528        (**self).write_broadcast_key(f)
1529    }
1530}
1531
1532/// Implements `BroadcastTypeTrait` for `&Ipv4Addr`.
1533impl BroadcastTypeTrait for &Ipv4Addr {
1534    /// Writes the referenced IPv4 address directly without allocating.
1535    ///
1536    /// # Arguments
1537    ///
1538    /// - `&mut dyn Write` - Destination formatting writer.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `fmt::Result` - Formatting outcome.
1543    #[inline]
1544    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1545        (**self).write_broadcast_key(f)
1546    }
1547}
1548
1549/// Implements `BroadcastTypeTrait` for `&Ipv6Addr`.
1550impl BroadcastTypeTrait for &Ipv6Addr {
1551    /// Writes the referenced IPv6 address directly without allocating.
1552    ///
1553    /// # Arguments
1554    ///
1555    /// - `&mut dyn Write` - Destination formatting writer.
1556    ///
1557    /// # Returns
1558    ///
1559    /// - `fmt::Result` - Formatting outcome.
1560    #[inline]
1561    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1562        (**self).write_broadcast_key(f)
1563    }
1564}
1565
1566/// Implements `BroadcastTypeTrait` for `&SocketAddr`.
1567impl BroadcastTypeTrait for &SocketAddr {
1568    /// Writes the referenced socket address directly without allocating.
1569    ///
1570    /// # Arguments
1571    ///
1572    /// - `&mut dyn Write` - Destination formatting writer.
1573    ///
1574    /// # Returns
1575    ///
1576    /// - `fmt::Result` - Formatting outcome.
1577    #[inline]
1578    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1579        (**self).write_broadcast_key(f)
1580    }
1581}
1582
1583/// Implements `BroadcastTypeTrait` for `&NonZeroU8`.
1584impl BroadcastTypeTrait for &NonZeroU8 {
1585    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1586    ///
1587    /// # Arguments
1588    ///
1589    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1590    ///
1591    /// # Returns
1592    ///
1593    /// - `Option<usize>` - Written byte count if it fits.
1594    #[inline(always)]
1595    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1596        (**self).write_broadcast_bytes(buf)
1597    }
1598
1599    /// Writes the referenced non-zero integer directly without allocating.
1600    ///
1601    /// # Arguments
1602    ///
1603    /// - `&mut dyn Write` - Destination formatting writer.
1604    ///
1605    /// # Returns
1606    ///
1607    /// - `fmt::Result` - Formatting outcome.
1608    #[inline]
1609    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1610        (**self).write_broadcast_key(f)
1611    }
1612}
1613
1614/// Implements `BroadcastTypeTrait` for `&NonZeroU16`.
1615impl BroadcastTypeTrait for &NonZeroU16 {
1616    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1617    ///
1618    /// # Arguments
1619    ///
1620    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1621    ///
1622    /// # Returns
1623    ///
1624    /// - `Option<usize>` - Written byte count if it fits.
1625    #[inline(always)]
1626    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1627        (**self).write_broadcast_bytes(buf)
1628    }
1629
1630    /// Writes the referenced non-zero integer directly without allocating.
1631    ///
1632    /// # Arguments
1633    ///
1634    /// - `&mut dyn Write` - Destination formatting writer.
1635    ///
1636    /// # Returns
1637    ///
1638    /// - `fmt::Result` - Formatting outcome.
1639    #[inline]
1640    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1641        (**self).write_broadcast_key(f)
1642    }
1643}
1644
1645/// Implements `BroadcastTypeTrait` for `&NonZeroU32`.
1646impl BroadcastTypeTrait for &NonZeroU32 {
1647    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1648    ///
1649    /// # Arguments
1650    ///
1651    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1652    ///
1653    /// # Returns
1654    ///
1655    /// - `Option<usize>` - Written byte count if it fits.
1656    #[inline(always)]
1657    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1658        (**self).write_broadcast_bytes(buf)
1659    }
1660
1661    /// Writes the referenced non-zero integer directly without allocating.
1662    ///
1663    /// # Arguments
1664    ///
1665    /// - `&mut dyn Write` - Destination formatting writer.
1666    ///
1667    /// # Returns
1668    ///
1669    /// - `fmt::Result` - Formatting outcome.
1670    #[inline]
1671    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1672        (**self).write_broadcast_key(f)
1673    }
1674}
1675
1676/// Implements `BroadcastTypeTrait` for `&NonZeroU64`.
1677impl BroadcastTypeTrait for &NonZeroU64 {
1678    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1679    ///
1680    /// # Arguments
1681    ///
1682    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1683    ///
1684    /// # Returns
1685    ///
1686    /// - `Option<usize>` - Written byte count if it fits.
1687    #[inline(always)]
1688    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1689        (**self).write_broadcast_bytes(buf)
1690    }
1691
1692    /// Writes the referenced non-zero integer directly without allocating.
1693    ///
1694    /// # Arguments
1695    ///
1696    /// - `&mut dyn Write` - Destination formatting writer.
1697    ///
1698    /// # Returns
1699    ///
1700    /// - `fmt::Result` - Formatting outcome.
1701    #[inline]
1702    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1703        (**self).write_broadcast_key(f)
1704    }
1705}
1706
1707/// Implements `BroadcastTypeTrait` for `&NonZeroU128`.
1708impl BroadcastTypeTrait for &NonZeroU128 {
1709    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1710    ///
1711    /// # Arguments
1712    ///
1713    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1714    ///
1715    /// # Returns
1716    ///
1717    /// - `Option<usize>` - Written byte count if it fits.
1718    #[inline(always)]
1719    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1720        (**self).write_broadcast_bytes(buf)
1721    }
1722
1723    /// Writes the referenced non-zero integer directly without allocating.
1724    ///
1725    /// # Arguments
1726    ///
1727    /// - `&mut dyn Write` - Destination formatting writer.
1728    ///
1729    /// # Returns
1730    ///
1731    /// - `fmt::Result` - Formatting outcome.
1732    #[inline]
1733    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1734        (**self).write_broadcast_key(f)
1735    }
1736}
1737
1738/// Implements `BroadcastTypeTrait` for `&NonZeroUsize`.
1739impl BroadcastTypeTrait for &NonZeroUsize {
1740    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1741    ///
1742    /// # Arguments
1743    ///
1744    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1745    ///
1746    /// # Returns
1747    ///
1748    /// - `Option<usize>` - Written byte count if it fits.
1749    #[inline(always)]
1750    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1751        (**self).write_broadcast_bytes(buf)
1752    }
1753
1754    /// Writes the referenced non-zero integer directly without allocating.
1755    ///
1756    /// # Arguments
1757    ///
1758    /// - `&mut dyn Write` - Destination formatting writer.
1759    ///
1760    /// # Returns
1761    ///
1762    /// - `fmt::Result` - Formatting outcome.
1763    #[inline]
1764    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1765        (**self).write_broadcast_key(f)
1766    }
1767}
1768
1769/// Implements `BroadcastTypeTrait` for `&NonZeroI8`.
1770impl BroadcastTypeTrait for &NonZeroI8 {
1771    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1772    ///
1773    /// # Arguments
1774    ///
1775    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1776    ///
1777    /// # Returns
1778    ///
1779    /// - `Option<usize>` - Written byte count if it fits.
1780    #[inline(always)]
1781    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1782        (**self).write_broadcast_bytes(buf)
1783    }
1784
1785    /// Writes the referenced non-zero integer directly without allocating.
1786    ///
1787    /// # Arguments
1788    ///
1789    /// - `&mut dyn Write` - Destination formatting writer.
1790    ///
1791    /// # Returns
1792    ///
1793    /// - `fmt::Result` - Formatting outcome.
1794    #[inline]
1795    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1796        (**self).write_broadcast_key(f)
1797    }
1798}
1799
1800/// Implements `BroadcastTypeTrait` for `&NonZeroI16`.
1801impl BroadcastTypeTrait for &NonZeroI16 {
1802    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1803    ///
1804    /// # Arguments
1805    ///
1806    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1807    ///
1808    /// # Returns
1809    ///
1810    /// - `Option<usize>` - Written byte count if it fits.
1811    #[inline(always)]
1812    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1813        (**self).write_broadcast_bytes(buf)
1814    }
1815
1816    /// Writes the referenced non-zero integer directly without allocating.
1817    ///
1818    /// # Arguments
1819    ///
1820    /// - `&mut dyn Write` - Destination formatting writer.
1821    ///
1822    /// # Returns
1823    ///
1824    /// - `fmt::Result` - Formatting outcome.
1825    #[inline]
1826    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1827        (**self).write_broadcast_key(f)
1828    }
1829}
1830
1831/// Implements `BroadcastTypeTrait` for `&NonZeroI32`.
1832impl BroadcastTypeTrait for &NonZeroI32 {
1833    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1834    ///
1835    /// # Arguments
1836    ///
1837    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1838    ///
1839    /// # Returns
1840    ///
1841    /// - `Option<usize>` - Written byte count if it fits.
1842    #[inline(always)]
1843    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1844        (**self).write_broadcast_bytes(buf)
1845    }
1846
1847    /// Writes the referenced non-zero integer directly without allocating.
1848    ///
1849    /// # Arguments
1850    ///
1851    /// - `&mut dyn Write` - Destination formatting writer.
1852    ///
1853    /// # Returns
1854    ///
1855    /// - `fmt::Result` - Formatting outcome.
1856    #[inline]
1857    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1858        (**self).write_broadcast_key(f)
1859    }
1860}
1861
1862/// Implements `BroadcastTypeTrait` for `&NonZeroI64`.
1863impl BroadcastTypeTrait for &NonZeroI64 {
1864    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1865    ///
1866    /// # Arguments
1867    ///
1868    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1869    ///
1870    /// # Returns
1871    ///
1872    /// - `Option<usize>` - Written byte count if it fits.
1873    #[inline(always)]
1874    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1875        (**self).write_broadcast_bytes(buf)
1876    }
1877
1878    /// Writes the referenced non-zero integer directly without allocating.
1879    ///
1880    /// # Arguments
1881    ///
1882    /// - `&mut dyn Write` - Destination formatting writer.
1883    ///
1884    /// # Returns
1885    ///
1886    /// - `fmt::Result` - Formatting outcome.
1887    #[inline]
1888    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1889        (**self).write_broadcast_key(f)
1890    }
1891}
1892
1893/// Implements `BroadcastTypeTrait` for `&NonZeroI128`.
1894impl BroadcastTypeTrait for &NonZeroI128 {
1895    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1896    ///
1897    /// # Arguments
1898    ///
1899    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1900    ///
1901    /// # Returns
1902    ///
1903    /// - `Option<usize>` - Written byte count if it fits.
1904    #[inline(always)]
1905    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1906        (**self).write_broadcast_bytes(buf)
1907    }
1908
1909    /// Writes the referenced non-zero integer directly without allocating.
1910    ///
1911    /// # Arguments
1912    ///
1913    /// - `&mut dyn Write` - Destination formatting writer.
1914    ///
1915    /// # Returns
1916    ///
1917    /// - `fmt::Result` - Formatting outcome.
1918    #[inline]
1919    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1920        (**self).write_broadcast_key(f)
1921    }
1922}
1923
1924/// Implements `BroadcastTypeTrait` for `&NonZeroIsize`.
1925impl BroadcastTypeTrait for &NonZeroIsize {
1926    /// Formats the referenced non-zero integer directly into `buf` without allocating.
1927    ///
1928    /// # Arguments
1929    ///
1930    /// - `&mut [u8]` - Destination UTF-8 byte buffer.
1931    ///
1932    /// # Returns
1933    ///
1934    /// - `Option<usize>` - Written byte count if it fits.
1935    #[inline(always)]
1936    fn write_broadcast_bytes(&self, buf: &mut [u8]) -> Option<usize> {
1937        (**self).write_broadcast_bytes(buf)
1938    }
1939
1940    /// Writes the referenced non-zero integer directly without allocating.
1941    ///
1942    /// # Arguments
1943    ///
1944    /// - `&mut dyn Write` - Destination formatting writer.
1945    ///
1946    /// # Returns
1947    ///
1948    /// - `fmt::Result` - Formatting outcome.
1949    #[inline]
1950    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
1951        (**self).write_broadcast_key(f)
1952    }
1953}
1954
1955/// Implements `BroadcastTypeTrait` for `&Infallible`.
1956impl BroadcastTypeTrait for &Infallible {}
1957
1958/// Implements the `Default` trait for `BroadcastType`.
1959///
1960/// The default value is `BroadcastType::Unknown`.
1961///
1962/// # Type Parameters
1963///
1964/// - `BroadcastTypeTrait`: The type parameter for `BroadcastType`, which must implement `BroadcastTypeTrait`.
1965impl<B> Default for BroadcastType<B>
1966where
1967    B: BroadcastTypeTrait,
1968{
1969    /// Returns the default `BroadcastType`, which is `BroadcastType::Unknown`.
1970    #[inline(always)]
1971    fn default() -> Self {
1972        BroadcastType::Unknown
1973    }
1974}
1975
1976impl<B> BroadcastType<B>
1977where
1978    B: BroadcastTypeTrait,
1979{
1980    /// Slow-path formatter handling non-string identifiers or keys exceeding [`STACK_KEY_BUF_LEN`].
1981    ///
1982    /// # Arguments
1983    ///
1984    /// - `F` - Closure receiving the formatted room key.
1985    ///
1986    /// # Returns
1987    ///
1988    /// - `R` - Value returned by `op`.
1989    #[cold]
1990    #[inline(never)]
1991    fn with_key_slow<R, F>(&self, op: F) -> R
1992    where
1993        F: FnOnce(&str) -> R,
1994    {
1995        match self {
1996            BroadcastType::PointToPoint(key1, key2) => {
1997                let (first_key, second_key): (&B, &B) = if key1 <= key2 {
1998                    (key1, key2)
1999                } else {
2000                    (key2, key1)
2001                };
2002                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
2003                let mut writer: StackKeyWriter<'_> = StackKeyWriter {
2004                    buf: &mut stack,
2005                    len: 0,
2006                };
2007                let fits: bool = writer.write_str(POINT_TO_POINT_PREFIX).is_ok()
2008                    && first_key.write_broadcast_key(&mut writer).is_ok()
2009                    && writer.write_char('-').is_ok()
2010                    && second_key.write_broadcast_key(&mut writer).is_ok();
2011                if fits {
2012                    let written: usize = writer.len;
2013                    if let Ok(key) = from_utf8(&stack[..written]) {
2014                        return op(key);
2015                    }
2016                }
2017                let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
2018                key.push_str(POINT_TO_POINT_PREFIX);
2019                let _: fmt::Result = first_key.write_broadcast_key(&mut key);
2020                key.push('-');
2021                let _: fmt::Result = second_key.write_broadcast_key(&mut key);
2022                op(&key)
2023            }
2024            BroadcastType::PointToGroup(group_key) => {
2025                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
2026                let mut writer: StackKeyWriter<'_> = StackKeyWriter {
2027                    buf: &mut stack,
2028                    len: 0,
2029                };
2030                let fits: bool = writer.write_str(POINT_TO_GROUP_PREFIX).is_ok()
2031                    && group_key.write_broadcast_key(&mut writer).is_ok();
2032                if fits {
2033                    let written: usize = writer.len;
2034                    if let Ok(key) = from_utf8(&stack[..written]) {
2035                        return op(key);
2036                    }
2037                }
2038                let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
2039                key.push_str(POINT_TO_GROUP_PREFIX);
2040                let _: fmt::Result = group_key.write_broadcast_key(&mut key);
2041                op(&key)
2042            }
2043            BroadcastType::Unknown => op(EMPTY_STR),
2044        }
2045    }
2046
2047    /// Formats this broadcast type's key into a stack buffer when it fits and passes the `&str` to `op`.
2048    ///
2049    /// # Arguments
2050    ///
2051    /// - `F` - Closure receiving the borrowed formatted room key.
2052    ///
2053    /// # Returns
2054    ///
2055    /// - `R` - Value returned by `op`.
2056    #[inline(always)]
2057    pub(crate) fn with_key<R, F>(&self, op: F) -> R
2058    where
2059        F: FnOnce(&str) -> R,
2060    {
2061        match self {
2062            BroadcastType::PointToGroup(group_key) => {
2063                let prefix: &[u8] = POINT_TO_GROUP_PREFIX.as_bytes();
2064                let p_len: usize = prefix.len();
2065                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
2066                if let Some(group_str) = group_key.as_broadcast_str() {
2067                    let group_bytes: &[u8] = group_str.as_bytes();
2068                    let total: usize = p_len + group_bytes.len();
2069                    if total <= STACK_KEY_BUF_LEN {
2070                        stack[..p_len].copy_from_slice(prefix);
2071                        stack[p_len..total].copy_from_slice(group_bytes);
2072                        if let Ok(key) = from_utf8(&stack[..total]) {
2073                            return op(key);
2074                        }
2075                    }
2076                } else if let Some(written) = group_key.write_broadcast_bytes(&mut stack[p_len..]) {
2077                    stack[..p_len].copy_from_slice(prefix);
2078                    if let Ok(key) = from_utf8(&stack[..p_len + written]) {
2079                        return op(key);
2080                    }
2081                }
2082                self.with_key_slow(op)
2083            }
2084            BroadcastType::PointToPoint(key1, key2) => {
2085                let (first_key, second_key): (&B, &B) = if key1 <= key2 {
2086                    (key1, key2)
2087                } else {
2088                    (key2, key1)
2089                };
2090                let prefix: &[u8] = POINT_TO_POINT_PREFIX.as_bytes();
2091                let p1: usize = prefix.len();
2092                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
2093                if let (Some(first_str), Some(second_str)) =
2094                    (first_key.as_broadcast_str(), second_key.as_broadcast_str())
2095                {
2096                    let a: &[u8] = first_str.as_bytes();
2097                    let b: &[u8] = second_str.as_bytes();
2098                    let total: usize = p1 + a.len() + 1 + b.len();
2099                    if total <= STACK_KEY_BUF_LEN {
2100                        let p2: usize = p1 + a.len();
2101                        stack[..p1].copy_from_slice(prefix);
2102                        stack[p1..p2].copy_from_slice(a);
2103                        stack[p2] = BYTE_DASH;
2104                        stack[p2 + 1..total].copy_from_slice(b);
2105                        if let Ok(key) = from_utf8(&stack[..total]) {
2106                            return op(key);
2107                        }
2108                    }
2109                } else if let Some(w1) = first_key.write_broadcast_bytes(&mut stack[p1..]) {
2110                    let p2: usize = p1 + w1;
2111                    if p2 + 1 < STACK_KEY_BUF_LEN
2112                        && let Some(w2) = second_key.write_broadcast_bytes(&mut stack[p2 + 1..])
2113                    {
2114                        stack[..p1].copy_from_slice(prefix);
2115                        stack[p2] = BYTE_DASH;
2116                        if let Ok(key) = from_utf8(&stack[..p2 + 1 + w2]) {
2117                            return op(key);
2118                        }
2119                    }
2120                }
2121                self.with_key_slow(op)
2122            }
2123            BroadcastType::Unknown => op(EMPTY_STR),
2124        }
2125    }
2126
2127    /// Generates a unique key string for a given broadcast type.
2128    ///
2129    /// For point-to-point types, the keys are sorted to ensure consistent key generation
2130    /// regardless of the order of the input keys.
2131    ///
2132    /// # Arguments
2133    ///
2134    /// - `BroadcastType<B>` - The broadcast type for which to generate the key.
2135    ///
2136    /// # Returns
2137    ///
2138    /// - `String` - The unique key string for the broadcast type.
2139    #[inline(always)]
2140    pub fn get_key(broadcast_type: BroadcastType<B>) -> String {
2141        broadcast_type.with_key(str::to_owned)
2142    }
2143}
2144
2145impl<'a, B> WebSocketConfig<'a, B>
2146where
2147    B: BroadcastTypeTrait,
2148{
2149    /// Creates a new WebSocket configuration with the given context.
2150    ///
2151    /// # Arguments
2152    ///
2153    /// - `&'a mut Stream` - The stream object serving this WebSocket.
2154    /// - `&'a mut Context` - The context object to associate with the WebSocket.
2155    ///
2156    /// # Returns
2157    ///
2158    /// - `WebSocketConfig<B>` - A new WebSocket configuration instance.
2159    #[inline(always)]
2160    pub fn new(stream: &'a mut Stream, context: &'a mut Context) -> Self {
2161        Self {
2162            stream,
2163            context,
2164            capacity: DEFAULT_BROADCAST_SENDER_CAPACITY,
2165            broadcast_type: BroadcastType::default(),
2166            connected_hook: Hook::default_handler(),
2167            request_hook: Hook::default_handler(),
2168            sended_hook: Hook::default_handler(),
2169            closed_hook: Hook::default_handler(),
2170        }
2171    }
2172
2173    /// Hands out the stream and the context together.
2174    ///
2175    /// The two borrows live in the same configuration, so they have to be
2176    /// taken together: a caller that wants to run a hook needs both, and the
2177    /// borrow checker will not let it take them one at a time.
2178    ///
2179    /// # Returns
2180    ///
2181    /// - `(&'a mut Stream, &'a mut Context)` - The stream and the context.
2182    #[inline(always)]
2183    pub fn take_parts(self) -> (&'a mut Stream, &'a mut Context) {
2184        // The destructuring pattern is the §17.13 escape hatch: it is not
2185        // `self.field` access, and it hands out the two borrows together
2186        // with the lifetime the struct holds them under.
2187        let Self {
2188            stream, context, ..
2189        } = self;
2190        (stream, context)
2191    }
2192}
2193
2194impl<'a, B> WebSocketConfig<'a, B>
2195where
2196    B: BroadcastTypeTrait,
2197{
2198    /// Sets the capacity for the broadcast sender.
2199    ///
2200    /// # Arguments
2201    ///
2202    /// - `usize` - The desired capacity.
2203    ///
2204    /// # Returns
2205    ///
2206    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
2207    #[inline(always)]
2208    pub fn set_capacity(mut self, capacity: usize) -> Self {
2209        self.capacity = capacity;
2210        self
2211    }
2212
2213    /// Sets the context for the WebSocket connection.
2214    ///
2215    /// # Arguments
2216    ///
2217    /// - `&'a mut Context` - The context object to associate with the WebSocket.
2218    ///
2219    /// # Returns
2220    ///
2221    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
2222    #[inline(always)]
2223    pub fn set_context(mut self, context: &'a mut Context) -> Self {
2224        self.context = context;
2225        self
2226    }
2227
2228    /// Sets the broadcast type for the WebSocket connection.
2229    ///
2230    /// # Arguments
2231    ///
2232    /// - `BroadcastType<B>` - The broadcast type to use for this WebSocket.
2233    ///
2234    /// # Returns
2235    ///
2236    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
2237    #[inline(always)]
2238    pub fn set_broadcast_type(mut self, broadcast_type: BroadcastType<B>) -> Self {
2239        self.broadcast_type = broadcast_type;
2240        self
2241    }
2242
2243    /// Sets the connected hook handler.
2244    ///
2245    /// This hook is executed when the WebSocket connection is established.
2246    ///
2247    /// # Type Parameters
2248    ///
2249    /// - `S`: The hook type, which must implement `ServerHook`.
2250    ///
2251    /// # Returns
2252    ///
2253    /// The modified `WebSocketConfig` instance.
2254    ///
2255    /// # Examples
2256    ///
2257    /// ```rust
2258    /// use hyperlane::{Context, ServerHook, Status, Stream};
2259    /// use hyperlane_plugin_websocket::WebSocketConfig;
2260    /// # use hyperlane::{RequestConfig, Transport, tokio};
2261    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
2262    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
2263    /// #
2264    /// # #[derive(Debug)]
2265    /// # struct MemoryTransport(DuplexStream);
2266    /// #
2267    /// # impl Transport for MemoryTransport {
2268    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
2269    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2270    /// #     }
2271    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
2272    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2273    /// #     }
2274    /// # }
2275    /// #
2276    /// # impl AsyncRead for MemoryTransport {
2277    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
2278    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
2279    /// #     }
2280    /// # }
2281    /// #
2282    /// # impl AsyncWrite for MemoryTransport {
2283    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
2284    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
2285    /// #     }
2286    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2287    /// #         Pin::new(&mut self.0).poll_flush(cx)
2288    /// #     }
2289    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2290    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
2291    /// #     }
2292    /// # }
2293    ///
2294    /// struct MyConnectedHook;
2295    ///
2296    /// impl ServerHook for MyConnectedHook {
2297    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
2298    ///         Self
2299    ///     }
2300    ///
2301    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
2302    ///         ctx.set_attribute("connected", true);
2303    ///         Status::Continue
2304    ///     }
2305    /// }
2306    ///
2307    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
2308    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
2309    /// # let mut ctx: Context = Context::default();
2310    /// // Register the hook with the stream and context for this connection.
2311    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
2312    ///     .set_connected_hook::<MyConnectedHook>();
2313    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
2314    /// # runtime.block_on(async {
2315    /// #     let hook = config.get_connected_hook().clone();
2316    /// #     let (stream, context) = config.take_parts();
2317    /// #     let status: Status = hook(stream, context).await;
2318    /// #     assert!(matches!(status, Status::Continue));
2319    /// #     assert!(context.get_attribute::<bool, _>("connected"));
2320    /// # });
2321    /// ```
2322    #[inline(always)]
2323    pub fn set_connected_hook<S>(mut self) -> Self
2324    where
2325        S: ServerHook,
2326    {
2327        self.connected_hook = Hook::factory::<S>();
2328        self
2329    }
2330
2331    /// Sets the request hook handler.
2332    ///
2333    /// This hook is executed when a new request is received on the WebSocket.
2334    ///
2335    /// # Type Parameters
2336    ///
2337    /// - `S`: The hook type, which must implement `ServerHook`.
2338    ///
2339    /// # Returns
2340    ///
2341    /// The modified `WebSocketConfig` instance.
2342    ///
2343    /// # Examples
2344    ///
2345    /// ```rust
2346    /// use hyperlane::{Context, ServerHook, Status, Stream};
2347    /// use hyperlane_plugin_websocket::WebSocketConfig;
2348    /// # use hyperlane::{RequestConfig, Transport, tokio};
2349    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
2350    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
2351    /// #
2352    /// # #[derive(Debug)]
2353    /// # struct MemoryTransport(DuplexStream);
2354    /// #
2355    /// # impl Transport for MemoryTransport {
2356    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
2357    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2358    /// #     }
2359    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
2360    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2361    /// #     }
2362    /// # }
2363    /// #
2364    /// # impl AsyncRead for MemoryTransport {
2365    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
2366    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
2367    /// #     }
2368    /// # }
2369    /// #
2370    /// # impl AsyncWrite for MemoryTransport {
2371    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
2372    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
2373    /// #     }
2374    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2375    /// #         Pin::new(&mut self.0).poll_flush(cx)
2376    /// #     }
2377    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2378    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
2379    /// #     }
2380    /// # }
2381    ///
2382    /// struct MyRequestHook;
2383    ///
2384    /// impl ServerHook for MyRequestHook {
2385    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
2386    ///         Self
2387    ///     }
2388    ///
2389    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
2390    ///         ctx.set_attribute("request_received", true);
2391    ///         Status::Continue
2392    ///     }
2393    /// }
2394    ///
2395    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
2396    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
2397    /// # let mut ctx: Context = Context::default();
2398    /// // Register the hook with the stream and context for this connection.
2399    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
2400    ///     .set_request_hook::<MyRequestHook>();
2401    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
2402    /// # runtime.block_on(async {
2403    /// #     let hook = config.get_request_hook().clone();
2404    /// #     let (stream, context) = config.take_parts();
2405    /// #     let status: Status = hook(stream, context).await;
2406    /// #     assert!(matches!(status, Status::Continue));
2407    /// #     assert!(context.get_attribute::<bool, _>("request_received"));
2408    /// # });
2409    /// ```
2410    #[inline(always)]
2411    pub fn set_request_hook<S>(mut self) -> Self
2412    where
2413        S: ServerHook,
2414    {
2415        self.request_hook = Hook::factory::<S>();
2416        self
2417    }
2418
2419    /// Sets the sended hook handler.
2420    ///
2421    /// This hook is executed after a message has been successfully sent over the WebSocket.
2422    ///
2423    /// # Type Parameters
2424    ///
2425    /// - `S`: The hook type, which must implement `ServerHook`.
2426    ///
2427    /// # Returns
2428    ///
2429    /// The modified `WebSocketConfig` instance.
2430    ///
2431    /// # Examples
2432    ///
2433    /// ```rust
2434    /// use hyperlane::{Context, ServerHook, Status, Stream};
2435    /// use hyperlane_plugin_websocket::WebSocketConfig;
2436    /// # use hyperlane::{RequestConfig, Transport, tokio};
2437    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
2438    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
2439    /// #
2440    /// # #[derive(Debug)]
2441    /// # struct MemoryTransport(DuplexStream);
2442    /// #
2443    /// # impl Transport for MemoryTransport {
2444    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
2445    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2446    /// #     }
2447    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
2448    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2449    /// #     }
2450    /// # }
2451    /// #
2452    /// # impl AsyncRead for MemoryTransport {
2453    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
2454    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
2455    /// #     }
2456    /// # }
2457    /// #
2458    /// # impl AsyncWrite for MemoryTransport {
2459    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
2460    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
2461    /// #     }
2462    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2463    /// #         Pin::new(&mut self.0).poll_flush(cx)
2464    /// #     }
2465    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2466    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
2467    /// #     }
2468    /// # }
2469    ///
2470    /// struct MySendedHook;
2471    ///
2472    /// impl ServerHook for MySendedHook {
2473    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
2474    ///         Self
2475    ///     }
2476    ///
2477    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
2478    ///         ctx.set_attribute("message_sent", true);
2479    ///         Status::Continue
2480    ///     }
2481    /// }
2482    ///
2483    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
2484    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
2485    /// # let mut ctx: Context = Context::default();
2486    /// // Register the hook with the stream and context for this connection.
2487    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
2488    ///     .set_sended_hook::<MySendedHook>();
2489    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
2490    /// # runtime.block_on(async {
2491    /// #     let hook = config.get_sended_hook().clone();
2492    /// #     let (stream, context) = config.take_parts();
2493    /// #     let status: Status = hook(stream, context).await;
2494    /// #     assert!(matches!(status, Status::Continue));
2495    /// #     assert!(context.get_attribute::<bool, _>("message_sent"));
2496    /// # });
2497    /// ```
2498    #[inline(always)]
2499    pub fn set_sended_hook<S>(mut self) -> Self
2500    where
2501        S: ServerHook,
2502    {
2503        self.sended_hook = Hook::factory::<S>();
2504        self
2505    }
2506
2507    /// Sets the closed hook handler.
2508    ///
2509    /// This hook is executed when the WebSocket connection is closed.
2510    ///
2511    /// # Type Parameters
2512    ///
2513    /// - `S`: The hook type, which must implement `ServerHook`.
2514    ///
2515    /// # Returns
2516    ///
2517    /// The modified `WebSocketConfig` instance.
2518    ///
2519    /// # Examples
2520    ///
2521    /// ```rust
2522    /// use hyperlane::{Context, ServerHook, Status, Stream};
2523    /// use hyperlane_plugin_websocket::WebSocketConfig;
2524    /// # use hyperlane::{RequestConfig, Transport, tokio};
2525    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
2526    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
2527    /// #
2528    /// # #[derive(Debug)]
2529    /// # struct MemoryTransport(DuplexStream);
2530    /// #
2531    /// # impl Transport for MemoryTransport {
2532    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
2533    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2534    /// #     }
2535    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
2536    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
2537    /// #     }
2538    /// # }
2539    /// #
2540    /// # impl AsyncRead for MemoryTransport {
2541    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
2542    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
2543    /// #     }
2544    /// # }
2545    /// #
2546    /// # impl AsyncWrite for MemoryTransport {
2547    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
2548    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
2549    /// #     }
2550    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2551    /// #         Pin::new(&mut self.0).poll_flush(cx)
2552    /// #     }
2553    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
2554    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
2555    /// #     }
2556    /// # }
2557    ///
2558    /// struct MyClosedHook;
2559    ///
2560    /// impl ServerHook for MyClosedHook {
2561    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
2562    ///         Self
2563    ///     }
2564    ///
2565    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
2566    ///         ctx.set_attribute("closed", true);
2567    ///         Status::Continue
2568    ///     }
2569    /// }
2570    ///
2571    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
2572    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
2573    /// # let mut ctx: Context = Context::default();
2574    /// // Register the hook with the stream and context for this connection.
2575    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
2576    ///     .set_closed_hook::<MyClosedHook>();
2577    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
2578    /// # runtime.block_on(async {
2579    /// #     let hook = config.get_closed_hook().clone();
2580    /// #     let (stream, context) = config.take_parts();
2581    /// #     let status: Status = hook(stream, context).await;
2582    /// #     assert!(matches!(status, Status::Continue));
2583    /// #     assert!(context.get_attribute::<bool, _>("closed"));
2584    /// # });
2585    /// ```
2586    #[inline(always)]
2587    pub fn set_closed_hook<S>(mut self) -> Self
2588    where
2589        S: ServerHook,
2590    {
2591        self.closed_hook = Hook::factory::<S>();
2592        self
2593    }
2594}
2595
2596/// Implements [`Hasher`] for [`WsKeyHasher`] with zero allocations and 8-byte word mixing.
2597impl Hasher for WsKeyHasher {
2598    /// Finalizes the 64-bit hash digest.
2599    ///
2600    /// # Returns
2601    ///
2602    /// - `u64` - Finalized 64-bit hash value.
2603    #[inline(always)]
2604    fn finish(&self) -> u64 {
2605        let Self { state } = *self;
2606        state
2607    }
2608
2609    /// Mixes `bytes` into the hash state 8 bytes at a time without allocating.
2610    ///
2611    /// # Arguments
2612    ///
2613    /// - `&[u8]` - Input room key bytes.
2614    #[inline(always)]
2615    fn write(&mut self, bytes: &[u8]) {
2616        let Self { state } = self;
2617        let mut h: u64 = *state;
2618        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
2619        for chunk in chunks {
2620            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(WS_FX_HASH_K);
2621        }
2622        let mut tail: &[u8] = rem;
2623        if tail.len() >= 4 {
2624            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
2625            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(WS_FX_HASH_K);
2626            tail = &tail[4..];
2627        }
2628        if tail.len() >= 2 {
2629            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
2630            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(WS_FX_HASH_K);
2631            tail = &tail[2..];
2632        }
2633        if let Some(&b) = tail.first() {
2634            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(WS_FX_HASH_K);
2635        }
2636        *state = h;
2637    }
2638
2639    /// Mixes a single byte directly into the hash state.
2640    ///
2641    /// # Arguments
2642    ///
2643    /// - `u8` - Input byte.
2644    #[inline(always)]
2645    fn write_u8(&mut self, i: u8) {
2646        let Self { state } = self;
2647        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(WS_FX_HASH_K);
2648    }
2649}
2650
2651/// Recycles the borrowed WebSocket coalesce buffer back to the worker pool on drop.
2652impl Drop for WsScratchBuf {
2653    /// Returns the owned scratch buffer to the worker-local pool.
2654    fn drop(&mut self) {
2655        let Self { buf } = self;
2656        return_ws_coalesce_buf(take(buf));
2657    }
2658}
2659
2660/// Inherent implementation of [`WsRoomRing`].
2661impl WsRoomRing {
2662    /// Creates an empty, zero-allocation bounded frame ring capped at `capacity`.
2663    ///
2664    /// # Arguments
2665    ///
2666    /// - `usize` - Maximum unread frames retained before evicting oldest entries.
2667    ///
2668    /// # Returns
2669    ///
2670    /// - `Self` - Empty room ring retaining zero heap bytes while idle.
2671    #[inline]
2672    pub(crate) fn new(capacity: usize) -> Self {
2673        Self {
2674            entries: VecDeque::new(),
2675            head_seq: 0,
2676            next_seq: 0,
2677            subscribers: 0,
2678            capacity: capacity.max(1),
2679            closed: false,
2680        }
2681    }
2682
2683    /// Reclaims leading frames consumed by every subscriber and releases empty backing storage.
2684    #[inline]
2685    fn reclaim_consumed_front(&mut self) {
2686        let Self {
2687            entries,
2688            head_seq,
2689            next_seq,
2690            ..
2691        } = self;
2692        while entries
2693            .front()
2694            .is_some_and(|entry: &WsRoomEntry| entry.unread == 0)
2695        {
2696            let _: Option<WsRoomEntry> = entries.pop_front();
2697        }
2698        *head_seq = entries
2699            .front()
2700            .map_or(*next_seq, |entry: &WsRoomEntry| entry.seq);
2701        if entries.is_empty() && entries.capacity() > 0 {
2702            *entries = VecDeque::new();
2703        }
2704    }
2705
2706    /// Registers a new connection positioned at the current room tail.
2707    ///
2708    /// # Returns
2709    ///
2710    /// - `u64` - Initial delivery cursor for future room broadcasts.
2711    #[inline]
2712    pub(crate) fn subscribe(&mut self) -> u64 {
2713        let Self {
2714            subscribers,
2715            next_seq,
2716            ..
2717        } = self;
2718        *subscribers += 1;
2719        *next_seq
2720    }
2721
2722    /// Appends one pre-framed RFC 6455 message when active subscribers exist and returns receiver count.
2723    ///
2724    /// # Arguments
2725    ///
2726    /// - `Arc<[u8]>` - Shared pre-framed RFC 6455 wire message.
2727    ///
2728    /// # Returns
2729    ///
2730    /// - `usize` - Number of active subscribers enqueued for delivery (`0` when closed or empty).
2731    #[inline]
2732    pub(crate) fn push(&mut self, frame: Arc<[u8]>) -> usize {
2733        let Self {
2734            entries,
2735            head_seq,
2736            next_seq,
2737            subscribers,
2738            capacity,
2739            closed,
2740        } = self;
2741        if *subscribers == 0 || *closed {
2742            return 0;
2743        }
2744        if entries.len() >= *capacity {
2745            let _: Option<WsRoomEntry> = entries.pop_front();
2746            *head_seq = entries
2747                .front()
2748                .map_or(*next_seq, |entry: &WsRoomEntry| entry.seq);
2749        }
2750        let seq: u64 = *next_seq;
2751        if entries.is_empty() {
2752            *head_seq = seq;
2753        }
2754        let receiver_count: usize = *subscribers;
2755        entries.push_back(WsRoomEntry {
2756            seq,
2757            frame,
2758            unread: receiver_count,
2759        });
2760        *next_seq = seq + 1;
2761        receiver_count
2762    }
2763
2764    /// Pops the next pre-framed message for `cursor`, reporting lag or closure when applicable.
2765    ///
2766    /// # Arguments
2767    ///
2768    /// - `&mut u64` - Subscriber delivery cursor advanced on read or lag recovery.
2769    ///
2770    /// # Returns
2771    ///
2772    /// - `Option<WsRoomRecv>` - Ready frame/event, or `None` when caught up.
2773    #[inline]
2774    pub(crate) fn try_pop(&mut self, cursor: &mut u64) -> Option<WsRoomRecv> {
2775        let Self {
2776            entries,
2777            head_seq,
2778            next_seq,
2779            closed,
2780            ..
2781        } = self;
2782        if *cursor < *head_seq {
2783            *cursor = *head_seq;
2784            return Some(WsRoomRecv::Lagged);
2785        }
2786        if *cursor >= *next_seq {
2787            if *closed {
2788                return Some(WsRoomRecv::Closed);
2789            }
2790            return None;
2791        }
2792        let offset: usize = (*cursor - *head_seq) as usize;
2793        let frame: Arc<[u8]> = Arc::clone(&entries[offset].frame);
2794        entries[offset].unread = entries[offset].unread.saturating_sub(1);
2795        *cursor += 1;
2796        if offset == 0 && entries[0].unread == 0 {
2797            self.reclaim_consumed_front();
2798        }
2799        Some(WsRoomRecv::Frame(frame))
2800    }
2801
2802    /// Unregisters a disconnecting subscriber and releases unread references it will never read.
2803    ///
2804    /// # Arguments
2805    ///
2806    /// - `u64` - Subscriber's last unconsumed delivery cursor.
2807    #[inline]
2808    pub(crate) fn unsubscribe(&mut self, cursor: u64) {
2809        let Self {
2810            entries,
2811            head_seq,
2812            next_seq,
2813            subscribers,
2814            ..
2815        } = self;
2816        *subscribers = subscribers.saturating_sub(1);
2817        let start_seq: u64 = cursor.max(*head_seq);
2818        if start_seq < *next_seq {
2819            let start_idx: usize = (start_seq - *head_seq) as usize;
2820            for entry in entries.iter_mut().skip(start_idx) {
2821                entry.unread = entry.unread.saturating_sub(1);
2822            }
2823            self.reclaim_consumed_front();
2824        }
2825    }
2826}
2827
2828/// Inherent implementation of [`SparseWsHubInner`].
2829impl SparseWsHubInner {
2830    /// Creates an empty 64-shard sparse WebSocket room registry.
2831    ///
2832    /// # Returns
2833    ///
2834    /// - `Self` - Ready sharded sparse room registry.
2835    pub(crate) fn new() -> Self {
2836        let shards: Box<[WsShard; WS_SHARD_COUNT]> = Box::new(from_fn(|_: usize| WsShard {
2837            map: RwLock::new(HashMap::default()),
2838        }));
2839        Self { shards }
2840    }
2841
2842    /// Clones a point-in-time snapshot of existing room handles matching [`BroadcastMap`] clone semantics.
2843    ///
2844    /// # Returns
2845    ///
2846    /// - `Self` - Independent shard map sharing existing rooms but isolating later insertions.
2847    pub(crate) fn clone_snapshot(&self) -> Self {
2848        let Self { shards } = self;
2849        let cloned: Box<[WsShard; WS_SHARD_COUNT]> = Box::new(from_fn(|idx: usize| {
2850            let entries: WsShardMap = shards[idx]
2851                .map
2852                .read()
2853                .map(|guard: RwLockReadGuard<'_, WsShardMap>| guard.clone())
2854                .unwrap_or_default();
2855            WsShard {
2856                map: RwLock::new(entries),
2857            }
2858        }));
2859        Self { shards: cloned }
2860    }
2861
2862    /// Subscribes a connection to `key`, creating a zero-ring room on demand.
2863    ///
2864    /// # Arguments
2865    ///
2866    /// - `&Arc<Self>` - Shared sparse hub interior.
2867    /// - `&str` - Room key.
2868    /// - `usize` - Maximum unread message capacity for newly created rooms.
2869    ///
2870    /// # Returns
2871    ///
2872    /// - `SparseWsSubscription` - Active subscription handle.
2873    pub(crate) fn subscribe(self: &Arc<Self>, key: &str, capacity: usize) -> SparseWsSubscription {
2874        let Self { shards } = self.as_ref();
2875        let shard_idx: usize = ws_shard_index(key);
2876        let shard: &RwLock<WsShardMap> = &shards[shard_idx].map;
2877        let (room_key, room): (Arc<str>, Arc<WsRoom>) = if let Ok(read_map) = shard.read()
2878            && let Some((existing_key, existing_room)) = read_map.get_key_value(key)
2879        {
2880            (Arc::clone(existing_key), Arc::clone(existing_room))
2881        } else if let Ok(mut write_map) = shard.write() {
2882            if let Some((existing_key, existing_room)) = write_map.get_key_value(key) {
2883                (Arc::clone(existing_key), Arc::clone(existing_room))
2884            } else {
2885                let created_key: Arc<str> = Arc::from(key);
2886                let created_room: Arc<WsRoom> = Arc::new(WsRoom {
2887                    subscribers: AtomicUsize::new(0),
2888                    notify: Notify::new(),
2889                    ring: Mutex::new(WsRoomRing::new(capacity)),
2890                });
2891                let _: Option<Arc<WsRoom>> =
2892                    write_map.insert(Arc::clone(&created_key), Arc::clone(&created_room));
2893                (created_key, created_room)
2894            }
2895        } else {
2896            let created_key: Arc<str> = Arc::from(key);
2897            let created_room: Arc<WsRoom> = Arc::new(WsRoom {
2898                subscribers: AtomicUsize::new(0),
2899                notify: Notify::new(),
2900                ring: Mutex::new(WsRoomRing::new(capacity)),
2901            });
2902            (created_key, created_room)
2903        };
2904        let cursor: u64 = room
2905            .ring
2906            .lock()
2907            .map(|mut ring: MutexGuard<'_, WsRoomRing>| ring.subscribe())
2908            .unwrap_or(0);
2909        room.subscribers.fetch_add(1, Ordering::Release);
2910        SparseWsSubscription {
2911            key: room_key,
2912            room,
2913            hub: Arc::clone(self),
2914            cursor,
2915        }
2916    }
2917
2918    /// Returns the number of active sparse-hub connections in `key`.
2919    ///
2920    /// # Arguments
2921    ///
2922    /// - `&str` - Room key to inspect.
2923    ///
2924    /// # Returns
2925    ///
2926    /// - `usize` - Active connection count (`0` when room does not exist).
2927    #[inline]
2928    pub(crate) fn receiver_count(&self, key: &str) -> usize {
2929        let Self { shards } = self;
2930        let shard_idx: usize = ws_shard_index(key);
2931        shards[shard_idx]
2932            .map
2933            .read()
2934            .ok()
2935            .and_then(|map: RwLockReadGuard<'_, WsShardMap>| {
2936                map.get(key)
2937                    .map(|room: &Arc<WsRoom>| room.subscribers.load(Ordering::Acquire))
2938            })
2939            .unwrap_or(0)
2940    }
2941
2942    /// Encodes `payload` once into RFC 6455 wire frames and fans out zero-copy to `key` if present.
2943    ///
2944    /// # Arguments
2945    ///
2946    /// - `&str` - Target room key.
2947    /// - `&[u8]` - Raw payload bytes to frame once and broadcast.
2948    ///
2949    /// # Returns
2950    ///
2951    /// - `Option<usize>` - `Some(receiver_count)` when delivered, or `None` if no active room exists.
2952    #[inline]
2953    pub(crate) fn try_send_payload(&self, key: &str, payload: &[u8]) -> Option<usize> {
2954        let Self { shards } = self;
2955        let shard_idx: usize = ws_shard_index(key);
2956        let room: Arc<WsRoom> = shards[shard_idx]
2957            .map
2958            .read()
2959            .ok()
2960            .and_then(|map: RwLockReadGuard<'_, WsShardMap>| map.get(key).cloned())?;
2961        if room.subscribers.load(Ordering::Acquire) == 0 {
2962            return None;
2963        }
2964        let frame: Arc<[u8]> = build_ws_server_frames(payload);
2965        let delivered: usize = room
2966            .ring
2967            .lock()
2968            .map(|mut ring: MutexGuard<'_, WsRoomRing>| ring.push(frame))
2969            .unwrap_or(0);
2970        if delivered > 0 {
2971            room.notify.notify_waiters();
2972            return Some(delivered);
2973        }
2974        None
2975    }
2976
2977    /// Counts total active rooms across all shards for diagnostics.
2978    ///
2979    /// # Returns
2980    ///
2981    /// - `usize` - Number of active sparse rooms.
2982    pub(crate) fn room_count(&self) -> usize {
2983        let Self { shards } = self;
2984        let mut total: usize = 0;
2985        for shard in shards.iter() {
2986            if let Ok(map) = shard.map.read() {
2987                total += map.len();
2988            }
2989        }
2990        total
2991    }
2992}
2993
2994/// Snapshot-cloning implementation for [`SparseWsHub`].
2995impl Clone for SparseWsHub {
2996    /// Clones existing room entries while keeping future insertions independent.
2997    ///
2998    /// # Returns
2999    ///
3000    /// - `Self` - Snapshot clone of this sparse hub.
3001    fn clone(&self) -> Self {
3002        let Self { inner } = self;
3003        let next: OnceLock<Arc<SparseWsHubInner>> = OnceLock::new();
3004        if let Some(existing) = inner.get() {
3005            let _: Result<(), Arc<SparseWsHubInner>> =
3006                next.set(Arc::new(existing.clone_snapshot()));
3007        }
3008        Self { inner: next }
3009    }
3010}
3011
3012/// Inherent implementation of [`SparseWsHub`].
3013impl SparseWsHub {
3014    /// Subscribes to `key`, lazily initializing the 64-shard hub on first use.
3015    ///
3016    /// # Arguments
3017    ///
3018    /// - `&str` - Room key.
3019    /// - `usize` - Bounded unread capacity for newly created rooms.
3020    ///
3021    /// # Returns
3022    ///
3023    /// - `SparseWsSubscription` - Active sparse subscription handle.
3024    #[inline]
3025    pub(crate) fn subscribe(&self, key: &str, capacity: usize) -> SparseWsSubscription {
3026        let Self { inner } = self;
3027        let hub: &Arc<SparseWsHubInner> = inner.get_or_init(|| Arc::new(SparseWsHubInner::new()));
3028        hub.subscribe(key, capacity)
3029    }
3030
3031    /// Returns active connection count in `key` without initializing the hub if unused.
3032    ///
3033    /// # Arguments
3034    ///
3035    /// - `&str` - Room key.
3036    ///
3037    /// # Returns
3038    ///
3039    /// - `usize` - Active connection count.
3040    #[inline]
3041    pub(crate) fn receiver_count(&self, key: &str) -> usize {
3042        let Self { inner } = self;
3043        inner
3044            .get()
3045            .map_or(0, |hub: &Arc<SparseWsHubInner>| hub.receiver_count(key))
3046    }
3047
3048    /// Broadcasts `payload` to `key` if the sparse hub has active subscribers for that room.
3049    ///
3050    /// # Arguments
3051    ///
3052    /// - `&str` - Target room key.
3053    /// - `&[u8]` - Raw payload bytes.
3054    ///
3055    /// # Returns
3056    ///
3057    /// - `Option<usize>` - Delivered receiver count, or `None` when absent.
3058    #[inline]
3059    pub(crate) fn try_send_payload(&self, key: &str, payload: &[u8]) -> Option<usize> {
3060        let Self { inner } = self;
3061        inner
3062            .get()
3063            .and_then(|hub: &Arc<SparseWsHubInner>| hub.try_send_payload(key, payload))
3064    }
3065
3066    /// Returns total active sparse rooms for debug formatting.
3067    ///
3068    /// # Returns
3069    ///
3070    /// - `usize` - Active sparse room count.
3071    pub(crate) fn room_count(&self) -> usize {
3072        let Self { inner } = self;
3073        inner
3074            .get()
3075            .map_or(0, |hub: &Arc<SparseWsHubInner>| hub.room_count())
3076    }
3077}
3078
3079/// Inherent implementation of [`SparseWsSubscription`].
3080impl SparseWsSubscription {
3081    /// Attempts to receive one ready pre-framed message without awaiting.
3082    ///
3083    /// # Returns
3084    ///
3085    /// - `Option<WsRoomRecv>` - Next frame/event, or `None` when caught up.
3086    #[inline]
3087    pub(crate) fn try_recv(&mut self) -> Option<WsRoomRecv> {
3088        let Self { room, cursor, .. } = self;
3089        match room.ring.lock() {
3090            Ok(mut ring) => ring.try_pop(cursor),
3091            Err(_) => Some(WsRoomRecv::Closed),
3092        }
3093    }
3094
3095    /// Awaits the next pre-framed message using zero-lost-wakeup notification.
3096    ///
3097    /// # Returns
3098    ///
3099    /// - `WsRoomRecv` - Next pre-framed message, lag marker, or closure.
3100    pub(crate) async fn recv(&mut self) -> WsRoomRecv {
3101        loop {
3102            if let Some(item) = self.try_recv() {
3103                return item;
3104            }
3105            let Self { room, cursor, .. } = self;
3106            let notified: Notified<'_> = room.notify.notified();
3107            let mut pinned: Pin<&mut Notified<'_>> = pin!(notified);
3108            pinned.as_mut().enable();
3109            if let Some(item) = match room.ring.lock() {
3110                Ok(mut ring) => ring.try_pop(cursor),
3111                Err(_) => Some(WsRoomRecv::Closed),
3112            } {
3113                return item;
3114            }
3115            pinned.await;
3116        }
3117    }
3118
3119    /// Drains additional ready pre-framed messages into `out` under one ring lock up to `max_bytes`.
3120    ///
3121    /// # Arguments
3122    ///
3123    /// - `&mut Vec<u8>` - Destination coalesced wire buffer.
3124    /// - `usize` - Maximum total bytes to accumulate in `out`.
3125    ///
3126    /// # Returns
3127    ///
3128    /// - `bool` - `true` if the room closed after draining, `false` otherwise.
3129    #[inline]
3130    pub(crate) fn drain_queued_into(&mut self, out: &mut Vec<u8>, max_bytes: usize) -> bool {
3131        let Self { room, cursor, .. } = self;
3132        let Ok(mut ring) = room.ring.lock() else {
3133            return true;
3134        };
3135        while out.len() < max_bytes {
3136            match ring.try_pop(cursor) {
3137                Some(WsRoomRecv::Frame(frame)) => out.extend_from_slice(&frame),
3138                Some(WsRoomRecv::Lagged) => continue,
3139                Some(WsRoomRecv::Closed) => return true,
3140                None => break,
3141            }
3142        }
3143        false
3144    }
3145}
3146
3147/// Releases unread ring entries and evicts empty rooms when the last subscriber disconnects.
3148impl Drop for SparseWsSubscription {
3149    /// Decrements room occupancy and removes empty rooms from the shard map.
3150    fn drop(&mut self) {
3151        let Self {
3152            key,
3153            room,
3154            hub,
3155            cursor,
3156        } = self;
3157        if let Ok(mut ring) = room.ring.lock() {
3158            ring.unsubscribe(*cursor);
3159        }
3160        if room.subscribers.fetch_sub(1, Ordering::AcqRel) > 1 {
3161            return;
3162        }
3163        let shard_idx: usize = ws_shard_index(key);
3164        if let Ok(mut write_map) = hub.shards[shard_idx].map.write()
3165            && let Some(current) = write_map.get(key.as_ref())
3166            && Arc::ptr_eq(current, room)
3167            && current.subscribers.load(Ordering::Acquire) == 0
3168        {
3169            let _: Option<Arc<WsRoom>> = write_map.remove(key.as_ref());
3170        }
3171    }
3172}
3173
3174/// Snapshot-cloning implementation for [`WebSocket`].
3175impl Clone for WebSocket {
3176    /// Clones both the legacy broadcast map and sparse room hub snapshots.
3177    ///
3178    /// # Returns
3179    ///
3180    /// - `Self` - Snapshot clone preserving existing rooms while isolating future insertions.
3181    fn clone(&self) -> Self {
3182        let Self {
3183            broadcast_map,
3184            sparse_hub,
3185        } = self;
3186        Self {
3187            broadcast_map: broadcast_map.clone(),
3188            sparse_hub: sparse_hub.clone(),
3189        }
3190    }
3191}
3192
3193/// Debug formatting for [`WebSocket`].
3194impl Debug for WebSocket {
3195    /// Formats the inner broadcast map and active sparse room count.
3196    ///
3197    /// # Arguments
3198    ///
3199    /// - `&mut Formatter<'_>` - Destination formatter.
3200    ///
3201    /// # Returns
3202    ///
3203    /// - `fmt::Result` - Formatting outcome.
3204    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
3205        let Self {
3206            broadcast_map,
3207            sparse_hub,
3208        } = self;
3209        formatter
3210            .debug_struct(WS_DEBUG_STRUCT_NAME)
3211            .field(WS_DEBUG_BROADCAST_FIELD, broadcast_map)
3212            .field(WS_DEBUG_SPARSE_ROOMS_FIELD, &sparse_hub.room_count())
3213            .finish()
3214    }
3215}
3216
3217/// Inherent implementation of [`WebSocket`].
3218impl WebSocket {
3219    /// Creates a new WebSocket instance.
3220    ///
3221    /// Initializes with a default broadcast map.
3222    ///
3223    /// # Returns
3224    ///
3225    /// - `WebSocket` - A new WebSocket instance.
3226    #[inline(always)]
3227    pub fn new() -> Self {
3228        Self::default()
3229    }
3230
3231    /// Retrieves the current receiver count for a given broadcast type.
3232    ///
3233    /// # Type Parameters
3234    ///
3235    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3236    ///
3237    /// # Arguments
3238    ///
3239    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
3240    ///
3241    /// # Returns
3242    ///
3243    /// - `usize` - The number of active receivers for the broadcast type, or 0 if not found.
3244    #[inline(always)]
3245    pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> usize
3246    where
3247        B: BroadcastTypeTrait,
3248    {
3249        let Self {
3250            broadcast_map,
3251            sparse_hub,
3252        } = self;
3253        broadcast_type.with_key(|key: &str| {
3254            sparse_hub
3255                .receiver_count(key)
3256                .saturating_add(broadcast_map.receiver_count(key).unwrap_or(0))
3257        })
3258    }
3259
3260    /// Calculates the receiver count before a connection is established.
3261    ///
3262    /// Ensures the count does not exceed the maximum allowed value minus one.
3263    ///
3264    /// # Type Parameters
3265    ///
3266    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3267    ///
3268    /// # Arguments
3269    ///
3270    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
3271    ///
3272    /// # Returns
3273    ///
3274    /// - `usize` - The receiver count after the connection is established.
3275    #[inline(always)]
3276    pub fn receiver_count_before_connected<B>(&self, broadcast_type: BroadcastType<B>) -> usize
3277    where
3278        B: BroadcastTypeTrait,
3279    {
3280        let count: usize = self.receiver_count(broadcast_type);
3281        count.clamp(0, usize::MAX - 1) + 1
3282    }
3283
3284    /// Calculates the receiver count after a connection is closed.
3285    ///
3286    /// Ensures the count does not go below 0.
3287    ///
3288    /// # Type Parameters
3289    ///
3290    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3291    ///
3292    /// # Arguments
3293    ///
3294    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
3295    ///
3296    /// # Returns
3297    ///
3298    /// - `usize` - The receiver count after the connection is closed.
3299    #[inline(always)]
3300    pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> usize
3301    where
3302        B: BroadcastTypeTrait,
3303    {
3304        let count: usize = self.receiver_count(broadcast_type);
3305        count.clamp(1, usize::MAX) - 1
3306    }
3307
3308    /// Sends raw owned bytes to both the sparse room hub and legacy broadcast map for `key`.
3309    ///
3310    /// # Arguments
3311    ///
3312    /// - `&str` - Pre-formatted room key.
3313    /// - `Vec<u8>` - Owned payload bytes.
3314    ///
3315    /// # Returns
3316    ///
3317    /// - `Result<Option<usize>, SendError<Vec<u8>>>` - Delivered receiver count, `None`, or `SendError`.
3318    #[inline]
3319    fn try_send_by_key(
3320        &self,
3321        key: &str,
3322        data: Vec<u8>,
3323    ) -> Result<Option<usize>, SendError<Vec<u8>>> {
3324        let Self {
3325            broadcast_map,
3326            sparse_hub,
3327        } = self;
3328        let sparse_sent: Option<usize> = sparse_hub.try_send_payload(key, &data);
3329        let legacy_exists: bool = broadcast_map.receiver_count(key).is_some();
3330        if !legacy_exists {
3331            return Ok(sparse_sent);
3332        }
3333        match broadcast_map.try_send(key, data) {
3334            Ok(Some(legacy_count)) => Ok(Some(sparse_sent.unwrap_or(0) + legacy_count)),
3335            Ok(None) => Ok(sparse_sent),
3336            Err(err) => match sparse_sent {
3337                Some(sparse_count) => Ok(Some(sparse_count)),
3338                None => Err(err),
3339            },
3340        }
3341    }
3342
3343    /// Sends a borrowed payload slice to `key` without cloning when no legacy broadcast channel exists.
3344    ///
3345    /// # Arguments
3346    ///
3347    /// - `&str` - Pre-formatted room key.
3348    /// - `&[u8]` - Borrowed payload bytes.
3349    ///
3350    /// # Returns
3351    ///
3352    /// - `Result<Option<usize>, SendError<Vec<u8>>>` - Delivered receiver count, `None`, or `SendError`.
3353    #[inline]
3354    fn try_send_slice(&self, key: &str, data: &[u8]) -> Result<Option<usize>, SendError<Vec<u8>>> {
3355        let Self {
3356            broadcast_map,
3357            sparse_hub,
3358        } = self;
3359        let sparse_sent: Option<usize> = sparse_hub.try_send_payload(key, data);
3360        if broadcast_map.receiver_count(key).is_none() {
3361            return Ok(sparse_sent);
3362        }
3363        match broadcast_map.try_send(key, data.to_vec()) {
3364            Ok(Some(legacy_count)) => Ok(Some(sparse_sent.unwrap_or(0) + legacy_count)),
3365            Ok(None) => Ok(sparse_sent),
3366            Err(err) => match sparse_sent {
3367                Some(sparse_count) => Ok(Some(sparse_count)),
3368                None => Err(err),
3369            },
3370        }
3371    }
3372
3373    /// Sends data to all active receivers for a given broadcast type.
3374    ///
3375    /// # Type Parameters
3376    ///
3377    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
3378    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3379    ///
3380    /// # Arguments
3381    ///
3382    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
3383    /// - `T` - The data to send.
3384    ///
3385    /// # Returns
3386    ///
3387    /// - `Result<Option<usize>, SendError<Vec<u8>>>` - A result indicating the success or failure of the send operation.
3388    #[inline(always)]
3389    pub fn try_send<T, B>(
3390        &self,
3391        broadcast_type: BroadcastType<B>,
3392        data: T,
3393    ) -> Result<Option<usize>, SendError<Vec<u8>>>
3394    where
3395        T: Into<Vec<u8>>,
3396        B: BroadcastTypeTrait,
3397    {
3398        broadcast_type.with_key(|key: &str| self.try_send_by_key(key, data.into()))
3399    }
3400
3401    /// Sends data to all active receivers for a given broadcast type.
3402    ///
3403    /// This method panics if the send operation fails.
3404    ///
3405    /// # Type Parameters
3406    ///
3407    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
3408    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3409    ///
3410    /// # Arguments
3411    ///
3412    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
3413    /// - `T` - The data to send.
3414    ///
3415    /// # Returns
3416    ///
3417    /// - `Option<usize>` - The receiver count if the send operation succeeds.
3418    ///
3419    /// # Panics
3420    ///
3421    /// Panics if the send operation fails.
3422    #[inline(always)]
3423    pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<usize>
3424    where
3425        T: Into<Vec<u8>>,
3426        B: BroadcastTypeTrait,
3427    {
3428        self.try_send(broadcast_type, data).unwrap()
3429    }
3430
3431    /// Runs the legacy broadcast-map loop when an external caller pre-created the room in `broadcast_map`.
3432    ///
3433    /// Kept cold and boxed out of [`Self::run`] so normal sparse connections never reserve space for
3434    /// `tokio::sync::broadcast::Receiver` inside their idle task future, and without double-registering
3435    /// the connection in `sparse_hub`.
3436    ///
3437    /// # Arguments
3438    ///
3439    /// - `&mut Stream` - Active WebSocket client stream.
3440    /// - `&mut Context` - Active connection context.
3441    /// - `String` - Room key owned for cleanup after the receiver drops.
3442    /// - `Receiver<Vec<u8>>` - Pre-existing legacy broadcast receiver.
3443    /// - `ServerHookHandler` - Connected hook handler.
3444    /// - `(ServerHookHandler, ServerHookHandler, ServerHookHandler)` - Request, sended, and closed hooks.
3445    #[cold]
3446    async fn run_legacy_connection(
3447        &self,
3448        stream: &mut Stream,
3449        ctx: &mut Context,
3450        key: String,
3451        mut legacy_rx: Receiver<Vec<u8>>,
3452        connected_hook: ServerHookHandler,
3453        hooks: (ServerHookHandler, ServerHookHandler, ServerHookHandler),
3454    ) {
3455        let (request_hook, sended_hook, closed_hook): (
3456            ServerHookHandler,
3457            ServerHookHandler,
3458            ServerHookHandler,
3459        ) = hooks;
3460        let Self { broadcast_map, .. } = self;
3461        let mut closed_called: bool = false;
3462        let connected: bool = connected_hook(stream, ctx).await.is_continue();
3463        drop(connected_hook);
3464        if connected {
3465            loop {
3466                tokio::select! {
3467                    request_res = stream.try_get_websocket_request() => {
3468                        if let Ok(body) = request_res {
3469                            ctx.get_mut_request().set_body(body);
3470                            let is_reject: bool = request_hook(stream, ctx).await.is_reject();
3471                            let is_err: bool =
3472                                self.try_send_slice(&key, ctx.get_response().get_body()).is_err();
3473                            if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
3474                                break;
3475                            }
3476                        } else {
3477                            closed_called = true;
3478                            ctx.get_mut_response().get_mut_body().clear();
3479                            closed_hook(stream, ctx).await;
3480                            if !ctx.get_response().get_body().is_empty() {
3481                                let _: Result<Option<usize>, SendError<Vec<u8>>> =
3482                                    self.try_send_slice(&key, ctx.get_response().get_body());
3483                                let _: Status = sended_hook(stream, ctx).await;
3484                            }
3485                            break;
3486                        }
3487                    },
3488                    msg_res = legacy_rx.recv() => {
3489                        match msg_res {
3490                            Ok(raw) => {
3491                                if !send_legacy_ws_frames(stream, &mut legacy_rx, raw).await {
3492                                    break;
3493                                }
3494                            }
3495                            Err(RecvError::Lagged(_)) => continue,
3496                            Err(RecvError::Closed) => break,
3497                        }
3498                    }
3499                }
3500            }
3501        }
3502        if !closed_called {
3503            ctx.get_mut_response().get_mut_body().clear();
3504            closed_hook(stream, ctx).await;
3505            if !ctx.get_response().get_body().is_empty() {
3506                let body: Vec<u8> = take(ctx.get_mut_response().get_mut_body());
3507                let _: Result<Option<usize>, SendError<Vec<u8>>> = self.try_send_by_key(&key, body);
3508            }
3509        }
3510        drop(legacy_rx);
3511        if broadcast_map.receiver_count(&key) == Some(0) {
3512            let _: Option<Broadcast<Vec<u8>>> = broadcast_map.unsubscribe(&key);
3513        }
3514        stream.set_closed(true);
3515    }
3516
3517    /// Runs the primary zero-idle-ring WebSocket loop without retaining legacy broadcast channel state.
3518    ///
3519    /// # Arguments
3520    ///
3521    /// - `&mut Stream` - Active WebSocket client stream.
3522    /// - `&mut Context` - Active connection context.
3523    /// - `&mut SparseWsSubscription` - Sparse room subscription.
3524    /// - `(&ServerHookHandler, &ServerHookHandler, &ServerHookHandler)` - Request, sended, and closed hooks.
3525    ///
3526    /// # Returns
3527    ///
3528    /// - `bool` - `true` when `closed_hook` was already invoked inside the loop.
3529    async fn run_sparse_loop(
3530        &self,
3531        stream: &mut Stream,
3532        ctx: &mut Context,
3533        sub: &mut SparseWsSubscription,
3534        hooks: (&ServerHookHandler, &ServerHookHandler, &ServerHookHandler),
3535    ) -> bool {
3536        let (request_hook, sended_hook, closed_hook): (
3537            &ServerHookHandler,
3538            &ServerHookHandler,
3539            &ServerHookHandler,
3540        ) = hooks;
3541        loop {
3542            tokio::select! {
3543                request_res = stream.try_get_websocket_request() => {
3544                    if let Ok(body) = request_res {
3545                        ctx.get_mut_request().set_body(body);
3546                        let is_reject: bool = request_hook(stream, ctx).await.is_reject();
3547                        let is_err: bool = self
3548                            .try_send_slice(&sub.key, ctx.get_response().get_body())
3549                            .is_err();
3550                        if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
3551                            return false;
3552                        }
3553                    } else {
3554                        ctx.get_mut_response().get_mut_body().clear();
3555                        closed_hook(stream, ctx).await;
3556                        if !ctx.get_response().get_body().is_empty() {
3557                            let _: Result<Option<usize>, SendError<Vec<u8>>> =
3558                                self.try_send_slice(&sub.key, ctx.get_response().get_body());
3559                            let _: Status = sended_hook(stream, ctx).await;
3560                        }
3561                        return true;
3562                    }
3563                },
3564                recv_step = sub.recv() => {
3565                    match recv_step {
3566                        WsRoomRecv::Frame(frame) => {
3567                            if !send_sparse_ws_frame(stream, sub, frame).await {
3568                                return false;
3569                            }
3570                        }
3571                        WsRoomRecv::Lagged => continue,
3572                        WsRoomRecv::Closed => return false,
3573                    }
3574                }
3575            }
3576        }
3577    }
3578
3579    /// Runs the WebSocket connection, handling incoming requests and outgoing messages.
3580    ///
3581    /// This asynchronous function continuously monitors for new WebSocket requests
3582    /// and incoming broadcast messages, processing them according to the configured hooks.
3583    /// When the broadcast type is `BroadcastType::Unknown`, the stream is closed and
3584    /// the function returns without panicking.
3585    ///
3586    /// # Type Parameters
3587    ///
3588    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
3589    ///
3590    /// # Arguments
3591    ///
3592    /// - `WebSocketConfig<'_, B>` - The WebSocket configuration containing the configuration for this WebSocket instance.
3593    pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
3594    where
3595        B: BroadcastTypeTrait,
3596    {
3597        let WebSocketConfig {
3598            stream,
3599            context: ctx,
3600            capacity,
3601            broadcast_type,
3602            connected_hook,
3603            request_hook,
3604            sended_hook,
3605            closed_hook,
3606        }: WebSocketConfig<'_, B> = websocket_config;
3607        if matches!(broadcast_type, BroadcastType::Unknown) {
3608            stream.set_closed(true);
3609            return;
3610        }
3611        let Self {
3612            broadcast_map,
3613            sparse_hub,
3614        } = self;
3615        let legacy_choice: Option<(String, Receiver<Vec<u8>>)> =
3616            broadcast_type.with_key(|key: &str| {
3617                broadcast_map
3618                    .subscribe(key)
3619                    .map(|rx: Receiver<Vec<u8>>| (key.to_owned(), rx))
3620            });
3621        if let Some((legacy_key, legacy_rx)) = legacy_choice {
3622            drop(broadcast_type);
3623            Box::pin(self.run_legacy_connection(
3624                stream,
3625                ctx,
3626                legacy_key,
3627                legacy_rx,
3628                connected_hook,
3629                (request_hook, sended_hook, closed_hook),
3630            ))
3631            .await;
3632            return;
3633        }
3634        let mut sub: SparseWsSubscription =
3635            broadcast_type.with_key(|key: &str| sparse_hub.subscribe(key, capacity));
3636        drop(broadcast_type);
3637        let mut closed_called: bool = false;
3638        let connected: bool = connected_hook(stream, ctx).await.is_continue();
3639        drop(connected_hook);
3640        if connected {
3641            closed_called = self
3642                .run_sparse_loop(
3643                    stream,
3644                    ctx,
3645                    &mut sub,
3646                    (&request_hook, &sended_hook, &closed_hook),
3647                )
3648                .await;
3649        }
3650        if !closed_called {
3651            ctx.get_mut_response().get_mut_body().clear();
3652            closed_hook(stream, ctx).await;
3653            if !ctx.get_response().get_body().is_empty() {
3654                let body: Vec<u8> = take(ctx.get_mut_response().get_mut_body());
3655                let _: Result<Option<usize>, SendError<Vec<u8>>> =
3656                    self.try_send_by_key(&sub.key, body);
3657            }
3658        }
3659        let key: Arc<str> = Arc::clone(&sub.key);
3660        drop(sub);
3661        if broadcast_map.receiver_count(key.as_ref()) == Some(0) {
3662            let _: Option<Broadcast<Vec<u8>>> = broadcast_map.unsubscribe(key.as_ref());
3663        }
3664        stream.set_closed(true);
3665    }
3666}
3667
3668/// Inherent implementation of [`WebSocketPlugin`].
3669impl WebSocketPlugin {
3670    /// Initializes the global [`WebSocketPlugin`] once with `websocket`.
3671    ///
3672    /// # Arguments
3673    ///
3674    /// - `WebSocket` - Shared WebSocket broadcast hub.
3675    ///
3676    /// # Returns
3677    ///
3678    /// - `&'static Self` - Reference to the initialized global plugin.
3679    pub fn init(websocket: WebSocket) -> &'static Self {
3680        WEBSOCKET_PLUGIN.get_or_init(|| Self { websocket })
3681    }
3682
3683    /// Initializes the global [`WebSocketPlugin`] once with a default [`WebSocket`] hub.
3684    ///
3685    /// # Returns
3686    ///
3687    /// - `&'static Self` - Reference to the initialized global plugin.
3688    pub fn init_default() -> &'static Self {
3689        WEBSOCKET_PLUGIN.get_or_init(Self::default)
3690    }
3691
3692    /// Returns the initialized global [`WebSocketPlugin`], if initialized.
3693    ///
3694    /// # Returns
3695    ///
3696    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
3697    pub fn get() -> Option<&'static Self> {
3698        WEBSOCKET_PLUGIN.get()
3699    }
3700
3701    /// Returns the shared [`WebSocket`] broadcast hub.
3702    ///
3703    /// # Returns
3704    ///
3705    /// - `&WebSocket` - Shared WebSocket hub.
3706    pub fn get_websocket(&self) -> &WebSocket {
3707        &self.websocket
3708    }
3709}