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/// Inherent implementation of [`WebSocket`].
2597impl WebSocket {
2598 /// Creates a new WebSocket instance.
2599 ///
2600 /// Initializes with a default broadcast map.
2601 ///
2602 /// # Returns
2603 ///
2604 /// - `WebSocket` - A new WebSocket instance.
2605 #[inline(always)]
2606 pub fn new() -> Self {
2607 Self::default()
2608 }
2609
2610 /// Retrieves the current receiver count for a given broadcast type.
2611 ///
2612 /// # Type Parameters
2613 ///
2614 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2615 ///
2616 /// # Arguments
2617 ///
2618 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
2619 ///
2620 /// # Returns
2621 ///
2622 /// - `usize` - The number of active receivers for the broadcast type, or 0 if not found.
2623 #[inline(always)]
2624 pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> usize
2625 where
2626 B: BroadcastTypeTrait,
2627 {
2628 broadcast_type
2629 .with_key(|key: &str| self.get_broadcast_map().receiver_count(key).unwrap_or(0))
2630 }
2631
2632 /// Calculates the receiver count before a connection is established.
2633 ///
2634 /// Ensures the count does not exceed the maximum allowed value minus one.
2635 ///
2636 /// # Type Parameters
2637 ///
2638 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2639 ///
2640 /// # Arguments
2641 ///
2642 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
2643 ///
2644 /// # Returns
2645 ///
2646 /// - `usize` - The receiver count after the connection is established.
2647 #[inline(always)]
2648 pub fn receiver_count_before_connected<B>(&self, broadcast_type: BroadcastType<B>) -> usize
2649 where
2650 B: BroadcastTypeTrait,
2651 {
2652 let count: usize = self.receiver_count(broadcast_type);
2653 count.clamp(0, usize::MAX - 1) + 1
2654 }
2655
2656 /// Calculates the receiver count after a connection is closed.
2657 ///
2658 /// Ensures the count does not go below 0.
2659 ///
2660 /// # Type Parameters
2661 ///
2662 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2663 ///
2664 /// # Arguments
2665 ///
2666 /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
2667 ///
2668 /// # Returns
2669 ///
2670 /// - `usize` - The receiver count after the connection is closed.
2671 #[inline(always)]
2672 pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> usize
2673 where
2674 B: BroadcastTypeTrait,
2675 {
2676 let count: usize = self.receiver_count(broadcast_type);
2677 count.clamp(1, usize::MAX) - 1
2678 }
2679
2680 /// Sends data to all active receivers for a given broadcast type.
2681 ///
2682 /// # Type Parameters
2683 ///
2684 /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
2685 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2686 ///
2687 /// # Arguments
2688 ///
2689 /// - `BroadcastType<B>` - The broadcast type to which to send the data.
2690 /// - `T` - The data to send.
2691 ///
2692 /// # Returns
2693 ///
2694 /// - `Result<Option<usize>, SendError<Vec<u8>>>` - A result indicating the success or failure of the send operation.
2695 #[inline(always)]
2696 pub fn try_send<T, B>(
2697 &self,
2698 broadcast_type: BroadcastType<B>,
2699 data: T,
2700 ) -> Result<Option<usize>, SendError<Vec<u8>>>
2701 where
2702 T: Into<Vec<u8>>,
2703 B: BroadcastTypeTrait,
2704 {
2705 broadcast_type.with_key(|key: &str| self.get_broadcast_map().try_send(key, data.into()))
2706 }
2707
2708 /// Sends data to all active receivers for a given broadcast type.
2709 ///
2710 /// This method panics if the send operation fails.
2711 ///
2712 /// # Type Parameters
2713 ///
2714 /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
2715 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2716 ///
2717 /// # Arguments
2718 ///
2719 /// - `BroadcastType<B>` - The broadcast type to which to send the data.
2720 /// - `T` - The data to send.
2721 ///
2722 /// # Returns
2723 ///
2724 /// - `Option<usize>` - The receiver count if the send operation succeeds.
2725 ///
2726 /// # Panics
2727 ///
2728 /// Panics if the send operation fails.
2729 #[inline(always)]
2730 pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<usize>
2731 where
2732 T: Into<Vec<u8>>,
2733 B: BroadcastTypeTrait,
2734 {
2735 self.try_send(broadcast_type, data).unwrap()
2736 }
2737
2738 /// Runs the WebSocket connection, handling incoming requests and outgoing messages.
2739 ///
2740 /// This asynchronous function continuously monitors for new WebSocket requests
2741 /// and incoming broadcast messages, processing them according to the configured hooks.
2742 /// When the broadcast type is `BroadcastType::Unknown`, the stream is closed and
2743 /// the function returns without panicking.
2744 ///
2745 /// # Type Parameters
2746 ///
2747 /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
2748 ///
2749 /// # Arguments
2750 ///
2751 /// - `WebSocketConfig<'_, B>` - The WebSocket configuration containing the configuration for this WebSocket instance.
2752 pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
2753 where
2754 B: BroadcastTypeTrait,
2755 {
2756 let WebSocketConfig {
2757 stream,
2758 context: ctx,
2759 capacity,
2760 broadcast_type,
2761 connected_hook,
2762 request_hook,
2763 sended_hook,
2764 closed_hook,
2765 }: WebSocketConfig<'_, B> = websocket_config;
2766 if matches!(broadcast_type, BroadcastType::Unknown) {
2767 stream.set_closed(true);
2768 return;
2769 }
2770 let key: String = BroadcastType::get_key(broadcast_type);
2771 let mut receiver: Receiver<Vec<u8>> =
2772 self.get_broadcast_map().subscribe_or_insert(&key, capacity);
2773 let mut closed_called: bool = false;
2774 let mut frame_buf: Vec<u8> = Vec::new();
2775 if connected_hook(stream, ctx).await.is_continue() {
2776 loop {
2777 tokio::select! {
2778 request_res = stream.try_get_websocket_request() => {
2779 if let Ok(body) = request_res {
2780 ctx.get_mut_request().set_body(body);
2781 let is_reject: bool = request_hook(stream, ctx).await.is_reject();
2782 let body: Vec<u8> = ctx.get_response().get_body().clone();
2783 let is_err: bool = self.get_broadcast_map().try_send(&key, body).is_err();
2784 if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
2785 break;
2786 }
2787 } else {
2788 closed_called = true;
2789 ctx.get_mut_response().get_mut_body().clear();
2790 closed_hook(stream, ctx).await;
2791 if !ctx.get_response().get_body().is_empty() {
2792 let body: Vec<u8> = ctx.get_response().get_body().clone();
2793 let _: Result<Option<usize>, SendError<Vec<u8>>> =
2794 self.get_broadcast_map().try_send(&key, body);
2795 let _: Status = sended_hook(stream, ctx).await;
2796 }
2797 break;
2798 }
2799 },
2800 msg_res = receiver.recv() => {
2801 match msg_res {
2802 Ok(msg) => {
2803 frame_buf.clear();
2804 let queued: usize = receiver.len().min(WS_COALESCE_EST_MAX_MSGS);
2805 let est: usize = msg
2806 .len()
2807 .saturating_add(4)
2808 .saturating_mul(queued + 1)
2809 .min(WS_COALESCE_MAX_BYTES);
2810 if frame_buf.capacity() < est {
2811 frame_buf.reserve_exact(est);
2812 }
2813 append_ws_server_frames(&msg, &mut frame_buf);
2814 let mut closed_after_send: bool = false;
2815 while frame_buf.len() < WS_COALESCE_MAX_BYTES {
2816 match receiver.try_recv() {
2817 Ok(next_msg) => {
2818 append_ws_server_frames(&next_msg, &mut frame_buf);
2819 }
2820 Err(TryRecvError::Lagged(_)) => continue,
2821 Err(TryRecvError::Empty) => break,
2822 Err(TryRecvError::Closed) => {
2823 closed_after_send = true;
2824 break;
2825 }
2826 }
2827 }
2828 let send_ok: bool = stream.try_send(&frame_buf).await.is_ok();
2829 if frame_buf.capacity() > WS_FRAME_BUF_MAX_RETAIN {
2830 frame_buf = Vec::new();
2831 }
2832 if send_ok && !closed_after_send {
2833 continue;
2834 }
2835 break;
2836 }
2837 Err(RecvError::Lagged(_)) => continue,
2838 Err(RecvError::Closed) => break,
2839 }
2840 }
2841 }
2842 }
2843 }
2844 if !closed_called {
2845 ctx.get_mut_response().get_mut_body().clear();
2846 closed_hook(stream, ctx).await;
2847 if !ctx.get_response().get_body().is_empty() {
2848 let body: Vec<u8> = take(ctx.get_mut_response().get_mut_body());
2849 let _: Result<Option<usize>, SendError<Vec<u8>>> =
2850 self.get_broadcast_map().try_send(&key, body);
2851 }
2852 }
2853 drop(receiver);
2854 if self.get_broadcast_map().receiver_count(&key) == Some(0) {
2855 let _: Option<Broadcast<Vec<u8>>> = self.get_broadcast_map().unsubscribe(&key);
2856 }
2857 stream.set_closed(true);
2858 }
2859}
2860
2861/// Inherent implementation of [`WebSocketPlugin`].
2862impl WebSocketPlugin {
2863 /// Initializes the global [`WebSocketPlugin`] once with `websocket`.
2864 ///
2865 /// # Arguments
2866 ///
2867 /// - `WebSocket` - Shared WebSocket broadcast hub.
2868 ///
2869 /// # Returns
2870 ///
2871 /// - `&'static Self` - Reference to the initialized global plugin.
2872 pub fn init(websocket: WebSocket) -> &'static Self {
2873 WEBSOCKET_PLUGIN.get_or_init(|| Self { websocket })
2874 }
2875
2876 /// Initializes the global [`WebSocketPlugin`] once with a default [`WebSocket`] hub.
2877 ///
2878 /// # Returns
2879 ///
2880 /// - `&'static Self` - Reference to the initialized global plugin.
2881 pub fn init_default() -> &'static Self {
2882 WEBSOCKET_PLUGIN.get_or_init(Self::default)
2883 }
2884
2885 /// Returns the initialized global [`WebSocketPlugin`], if initialized.
2886 ///
2887 /// # Returns
2888 ///
2889 /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
2890 pub fn get() -> Option<&'static Self> {
2891 WEBSOCKET_PLUGIN.get()
2892 }
2893
2894 /// Returns the shared [`WebSocket`] broadcast hub.
2895 ///
2896 /// # Returns
2897 ///
2898 /// - `&WebSocket` - Shared WebSocket hub.
2899 pub fn get_websocket(&self) -> &WebSocket {
2900 &self.websocket
2901 }
2902}