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    /// Writes this `char` directly without allocating.
85    ///
86    /// # Arguments
87    ///
88    /// - `&mut dyn Write` - Destination formatting writer.
89    ///
90    /// # Returns
91    ///
92    /// - `fmt::Result` - Formatting outcome.
93    #[inline]
94    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
95        f.write_char(*self)
96    }
97}
98
99/// Allows `bool` to be used as a broadcast identifier.
100impl BroadcastTypeTrait for bool {
101    /// Writes this `bool` directly without allocating.
102    ///
103    /// # Arguments
104    ///
105    /// - `&mut dyn Write` - Destination formatting writer.
106    ///
107    /// # Returns
108    ///
109    /// - `fmt::Result` - Formatting outcome.
110    #[inline]
111    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
112        write!(f, "{self}")
113    }
114}
115
116/// Allows `i8` to be used as a broadcast identifier.
117impl BroadcastTypeTrait for i8 {
118    /// Writes this integer directly without allocating.
119    ///
120    /// # Arguments
121    ///
122    /// - `&mut dyn Write` - Destination formatting writer.
123    ///
124    /// # Returns
125    ///
126    /// - `fmt::Result` - Formatting outcome.
127    #[inline]
128    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
129        write!(f, "{self}")
130    }
131}
132
133/// Allows `i16` to be used as a broadcast identifier.
134impl BroadcastTypeTrait for i16 {
135    /// Writes this integer directly without allocating.
136    ///
137    /// # Arguments
138    ///
139    /// - `&mut dyn Write` - Destination formatting writer.
140    ///
141    /// # Returns
142    ///
143    /// - `fmt::Result` - Formatting outcome.
144    #[inline]
145    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
146        write!(f, "{self}")
147    }
148}
149
150/// Allows `i32` to be used as a broadcast identifier.
151impl BroadcastTypeTrait for i32 {
152    /// Writes this integer directly without allocating.
153    ///
154    /// # Arguments
155    ///
156    /// - `&mut dyn Write` - Destination formatting writer.
157    ///
158    /// # Returns
159    ///
160    /// - `fmt::Result` - Formatting outcome.
161    #[inline]
162    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
163        write!(f, "{self}")
164    }
165}
166
167/// Allows `i64` to be used as a broadcast identifier.
168impl BroadcastTypeTrait for i64 {
169    /// Writes this integer directly without allocating.
170    ///
171    /// # Arguments
172    ///
173    /// - `&mut dyn Write` - Destination formatting writer.
174    ///
175    /// # Returns
176    ///
177    /// - `fmt::Result` - Formatting outcome.
178    #[inline]
179    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
180        write!(f, "{self}")
181    }
182}
183
184/// Allows `i128` to be used as a broadcast identifier.
185impl BroadcastTypeTrait for i128 {
186    /// Writes this integer directly without allocating.
187    ///
188    /// # Arguments
189    ///
190    /// - `&mut dyn Write` - Destination formatting writer.
191    ///
192    /// # Returns
193    ///
194    /// - `fmt::Result` - Formatting outcome.
195    #[inline]
196    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
197        write!(f, "{self}")
198    }
199}
200
201/// Allows `isize` to be used as a broadcast identifier.
202impl BroadcastTypeTrait for isize {
203    /// Writes this integer directly without allocating.
204    ///
205    /// # Arguments
206    ///
207    /// - `&mut dyn Write` - Destination formatting writer.
208    ///
209    /// # Returns
210    ///
211    /// - `fmt::Result` - Formatting outcome.
212    #[inline]
213    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
214        write!(f, "{self}")
215    }
216}
217
218/// Allows `u8` to be used as a broadcast identifier.
219impl BroadcastTypeTrait for u8 {
220    /// Writes this integer directly without allocating.
221    ///
222    /// # Arguments
223    ///
224    /// - `&mut dyn Write` - Destination formatting writer.
225    ///
226    /// # Returns
227    ///
228    /// - `fmt::Result` - Formatting outcome.
229    #[inline]
230    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
231        write!(f, "{self}")
232    }
233}
234
235/// Allows `u16` to be used as a broadcast identifier.
236impl BroadcastTypeTrait for u16 {
237    /// Writes this integer directly without allocating.
238    ///
239    /// # Arguments
240    ///
241    /// - `&mut dyn Write` - Destination formatting writer.
242    ///
243    /// # Returns
244    ///
245    /// - `fmt::Result` - Formatting outcome.
246    #[inline]
247    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
248        write!(f, "{self}")
249    }
250}
251
252/// Allows `u32` to be used as a broadcast identifier.
253impl BroadcastTypeTrait for u32 {
254    /// Writes this integer directly without allocating.
255    ///
256    /// # Arguments
257    ///
258    /// - `&mut dyn Write` - Destination formatting writer.
259    ///
260    /// # Returns
261    ///
262    /// - `fmt::Result` - Formatting outcome.
263    #[inline]
264    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
265        write!(f, "{self}")
266    }
267}
268
269/// Allows `u64` to be used as a broadcast identifier.
270impl BroadcastTypeTrait for u64 {
271    /// Writes this integer directly without allocating.
272    ///
273    /// # Arguments
274    ///
275    /// - `&mut dyn Write` - Destination formatting writer.
276    ///
277    /// # Returns
278    ///
279    /// - `fmt::Result` - Formatting outcome.
280    #[inline]
281    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
282        write!(f, "{self}")
283    }
284}
285
286/// Allows `u128` to be used as a broadcast identifier.
287impl BroadcastTypeTrait for u128 {
288    /// Writes this integer directly without allocating.
289    ///
290    /// # Arguments
291    ///
292    /// - `&mut dyn Write` - Destination formatting writer.
293    ///
294    /// # Returns
295    ///
296    /// - `fmt::Result` - Formatting outcome.
297    #[inline]
298    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
299        write!(f, "{self}")
300    }
301}
302
303/// Allows `usize` to be used as a broadcast identifier.
304impl BroadcastTypeTrait for usize {
305    /// Writes this integer directly without allocating.
306    ///
307    /// # Arguments
308    ///
309    /// - `&mut dyn Write` - Destination formatting writer.
310    ///
311    /// # Returns
312    ///
313    /// - `fmt::Result` - Formatting outcome.
314    #[inline]
315    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
316        write!(f, "{self}")
317    }
318}
319
320/// Allows `f32` to be used as a broadcast identifier.
321impl BroadcastTypeTrait for f32 {
322    /// Writes this float directly without allocating.
323    ///
324    /// # Arguments
325    ///
326    /// - `&mut dyn Write` - Destination formatting writer.
327    ///
328    /// # Returns
329    ///
330    /// - `fmt::Result` - Formatting outcome.
331    #[inline]
332    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
333        write!(f, "{self}")
334    }
335}
336
337/// Allows `f64` to be used as a broadcast identifier.
338impl BroadcastTypeTrait for f64 {
339    /// Writes this float directly without allocating.
340    ///
341    /// # Arguments
342    ///
343    /// - `&mut dyn Write` - Destination formatting writer.
344    ///
345    /// # Returns
346    ///
347    /// - `fmt::Result` - Formatting outcome.
348    #[inline]
349    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
350        write!(f, "{self}")
351    }
352}
353
354/// Allows `IpAddr` to be used as a broadcast identifier.
355impl BroadcastTypeTrait for IpAddr {
356    /// Writes this IP address directly without allocating.
357    ///
358    /// # Arguments
359    ///
360    /// - `&mut dyn Write` - Destination formatting writer.
361    ///
362    /// # Returns
363    ///
364    /// - `fmt::Result` - Formatting outcome.
365    #[inline]
366    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
367        write!(f, "{self}")
368    }
369}
370
371/// Allows `Ipv4Addr` to be used as a broadcast identifier.
372impl BroadcastTypeTrait for Ipv4Addr {
373    /// Writes this IPv4 address directly without allocating.
374    ///
375    /// # Arguments
376    ///
377    /// - `&mut dyn Write` - Destination formatting writer.
378    ///
379    /// # Returns
380    ///
381    /// - `fmt::Result` - Formatting outcome.
382    #[inline]
383    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
384        write!(f, "{self}")
385    }
386}
387
388/// Allows `Ipv6Addr` to be used as a broadcast identifier.
389impl BroadcastTypeTrait for Ipv6Addr {
390    /// Writes this IPv6 address directly without allocating.
391    ///
392    /// # Arguments
393    ///
394    /// - `&mut dyn Write` - Destination formatting writer.
395    ///
396    /// # Returns
397    ///
398    /// - `fmt::Result` - Formatting outcome.
399    #[inline]
400    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
401        write!(f, "{self}")
402    }
403}
404
405/// Allows `SocketAddr` to be used as a broadcast identifier.
406impl BroadcastTypeTrait for SocketAddr {
407    /// Writes this socket address directly without allocating.
408    ///
409    /// # Arguments
410    ///
411    /// - `&mut dyn Write` - Destination formatting writer.
412    ///
413    /// # Returns
414    ///
415    /// - `fmt::Result` - Formatting outcome.
416    #[inline]
417    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
418        write!(f, "{self}")
419    }
420}
421
422/// Allows `NonZeroU8` to be used as a broadcast identifier.
423impl BroadcastTypeTrait for NonZeroU8 {
424    /// Writes this non-zero integer directly without allocating.
425    ///
426    /// # Arguments
427    ///
428    /// - `&mut dyn Write` - Destination formatting writer.
429    ///
430    /// # Returns
431    ///
432    /// - `fmt::Result` - Formatting outcome.
433    #[inline]
434    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
435        write!(f, "{self}")
436    }
437}
438
439/// Allows `NonZeroU16` to be used as a broadcast identifier.
440impl BroadcastTypeTrait for NonZeroU16 {
441    /// Writes this non-zero integer directly without allocating.
442    ///
443    /// # Arguments
444    ///
445    /// - `&mut dyn Write` - Destination formatting writer.
446    ///
447    /// # Returns
448    ///
449    /// - `fmt::Result` - Formatting outcome.
450    #[inline]
451    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
452        write!(f, "{self}")
453    }
454}
455
456/// Allows `NonZeroU32` to be used as a broadcast identifier.
457impl BroadcastTypeTrait for NonZeroU32 {
458    /// Writes this non-zero integer directly without allocating.
459    ///
460    /// # Arguments
461    ///
462    /// - `&mut dyn Write` - Destination formatting writer.
463    ///
464    /// # Returns
465    ///
466    /// - `fmt::Result` - Formatting outcome.
467    #[inline]
468    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
469        write!(f, "{self}")
470    }
471}
472
473/// Allows `NonZeroU64` to be used as a broadcast identifier.
474impl BroadcastTypeTrait for NonZeroU64 {
475    /// Writes this non-zero integer directly without allocating.
476    ///
477    /// # Arguments
478    ///
479    /// - `&mut dyn Write` - Destination formatting writer.
480    ///
481    /// # Returns
482    ///
483    /// - `fmt::Result` - Formatting outcome.
484    #[inline]
485    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
486        write!(f, "{self}")
487    }
488}
489
490/// Allows `NonZeroU128` to be used as a broadcast identifier.
491impl BroadcastTypeTrait for NonZeroU128 {
492    /// Writes this non-zero integer directly without allocating.
493    ///
494    /// # Arguments
495    ///
496    /// - `&mut dyn Write` - Destination formatting writer.
497    ///
498    /// # Returns
499    ///
500    /// - `fmt::Result` - Formatting outcome.
501    #[inline]
502    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
503        write!(f, "{self}")
504    }
505}
506
507/// Allows `NonZeroUsize` to be used as a broadcast identifier.
508impl BroadcastTypeTrait for NonZeroUsize {
509    /// Writes this non-zero integer directly without allocating.
510    ///
511    /// # Arguments
512    ///
513    /// - `&mut dyn Write` - Destination formatting writer.
514    ///
515    /// # Returns
516    ///
517    /// - `fmt::Result` - Formatting outcome.
518    #[inline]
519    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
520        write!(f, "{self}")
521    }
522}
523
524/// Allows `NonZeroI8` to be used as a broadcast identifier.
525impl BroadcastTypeTrait for NonZeroI8 {
526    /// Writes this non-zero integer directly without allocating.
527    ///
528    /// # Arguments
529    ///
530    /// - `&mut dyn Write` - Destination formatting writer.
531    ///
532    /// # Returns
533    ///
534    /// - `fmt::Result` - Formatting outcome.
535    #[inline]
536    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
537        write!(f, "{self}")
538    }
539}
540
541/// Allows `NonZeroI16` to be used as a broadcast identifier.
542impl BroadcastTypeTrait for NonZeroI16 {
543    /// Writes this non-zero integer directly without allocating.
544    ///
545    /// # Arguments
546    ///
547    /// - `&mut dyn Write` - Destination formatting writer.
548    ///
549    /// # Returns
550    ///
551    /// - `fmt::Result` - Formatting outcome.
552    #[inline]
553    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
554        write!(f, "{self}")
555    }
556}
557
558/// Allows `NonZeroI32` to be used as a broadcast identifier.
559impl BroadcastTypeTrait for NonZeroI32 {
560    /// Writes this non-zero integer directly without allocating.
561    ///
562    /// # Arguments
563    ///
564    /// - `&mut dyn Write` - Destination formatting writer.
565    ///
566    /// # Returns
567    ///
568    /// - `fmt::Result` - Formatting outcome.
569    #[inline]
570    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
571        write!(f, "{self}")
572    }
573}
574
575/// Allows `NonZeroI64` to be used as a broadcast identifier.
576impl BroadcastTypeTrait for NonZeroI64 {
577    /// Writes this non-zero integer directly without allocating.
578    ///
579    /// # Arguments
580    ///
581    /// - `&mut dyn Write` - Destination formatting writer.
582    ///
583    /// # Returns
584    ///
585    /// - `fmt::Result` - Formatting outcome.
586    #[inline]
587    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
588        write!(f, "{self}")
589    }
590}
591
592/// Allows `NonZeroI128` to be used as a broadcast identifier.
593impl BroadcastTypeTrait for NonZeroI128 {
594    /// Writes this non-zero integer directly without allocating.
595    ///
596    /// # Arguments
597    ///
598    /// - `&mut dyn Write` - Destination formatting writer.
599    ///
600    /// # Returns
601    ///
602    /// - `fmt::Result` - Formatting outcome.
603    #[inline]
604    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
605        write!(f, "{self}")
606    }
607}
608
609/// Allows `NonZeroIsize` to be used as a broadcast identifier.
610impl BroadcastTypeTrait for NonZeroIsize {
611    /// Writes this non-zero integer directly without allocating.
612    ///
613    /// # Arguments
614    ///
615    /// - `&mut dyn Write` - Destination formatting writer.
616    ///
617    /// # Returns
618    ///
619    /// - `fmt::Result` - Formatting outcome.
620    #[inline]
621    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
622        write!(f, "{self}")
623    }
624}
625
626/// Allows `Infallible` to be used as a broadcast identifier.
627impl BroadcastTypeTrait for Infallible {}
628
629/// Allows references to `String` to be used as broadcast identifiers.
630impl BroadcastTypeTrait for &String {
631    /// Returns the referenced string slice directly without formatting or allocation.
632    ///
633    /// # Returns
634    ///
635    /// - `Option<&str>` - Always `Some(self.as_str())`.
636    #[inline(always)]
637    fn as_broadcast_str(&self) -> Option<&str> {
638        Some(self.as_str())
639    }
640
641    /// Writes the referenced string directly without allocating.
642    ///
643    /// # Arguments
644    ///
645    /// - `&mut dyn Write` - Destination formatting writer.
646    ///
647    /// # Returns
648    ///
649    /// - `fmt::Result` - Formatting outcome.
650    #[inline]
651    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
652        f.write_str(self)
653    }
654}
655
656/// Allows double references to string slices to be used as broadcast identifiers.
657impl BroadcastTypeTrait for &&str {
658    /// Returns the referenced string slice directly without formatting or allocation.
659    ///
660    /// # Returns
661    ///
662    /// - `Option<&str>` - Always `Some(self)`.
663    #[inline(always)]
664    fn as_broadcast_str(&self) -> Option<&str> {
665        Some(self)
666    }
667
668    /// Writes the referenced string slice directly without allocating.
669    ///
670    /// # Arguments
671    ///
672    /// - `&mut dyn Write` - Destination formatting writer.
673    ///
674    /// # Returns
675    ///
676    /// - `fmt::Result` - Formatting outcome.
677    #[inline]
678    fn write_broadcast_key(&self, f: &mut dyn Write) -> fmt::Result {
679        f.write_str(self)
680    }
681}
682
683/// Allows references to `char` to be used as broadcast identifiers.
684impl BroadcastTypeTrait for &char {}
685
686/// Allows references to `bool` to be used as broadcast identifiers.
687impl BroadcastTypeTrait for &bool {}
688
689/// Allows references to `i8` to be used as broadcast identifiers.
690impl BroadcastTypeTrait for &i8 {}
691
692/// Allows references to `i16` to be used as broadcast identifiers.
693impl BroadcastTypeTrait for &i16 {}
694
695/// Allows references to `i32` to be used as broadcast identifiers.
696impl BroadcastTypeTrait for &i32 {}
697
698/// Allows references to `i64` to be used as broadcast identifiers.
699impl BroadcastTypeTrait for &i64 {}
700
701/// Allows references to `i128` to be used as broadcast identifiers.
702impl BroadcastTypeTrait for &i128 {}
703
704/// Allows references to `isize` to be used as broadcast identifiers.
705impl BroadcastTypeTrait for &isize {}
706
707/// Allows references to `u8` to be used as broadcast identifiers.
708impl BroadcastTypeTrait for &u8 {}
709
710/// Allows references to `u16` to be used as broadcast identifiers.
711impl BroadcastTypeTrait for &u16 {}
712
713/// Allows references to `u32` to be used as broadcast identifiers.
714impl BroadcastTypeTrait for &u32 {}
715
716/// Implements `BroadcastTypeTrait` for `&u64`.
717///
718/// This allows references to `u64` to be used as a broadcast identifier.
719impl BroadcastTypeTrait for &u64 {}
720
721/// Implements `BroadcastTypeTrait` for `&u128`.
722///
723/// This allows references to `u128` to be used as a broadcast identifier.
724impl BroadcastTypeTrait for &u128 {}
725
726/// Implements `BroadcastTypeTrait` for `&usize`.
727///
728/// This allows references to `usize` to be used as a broadcast identifier.
729impl BroadcastTypeTrait for &usize {}
730
731/// Implements `BroadcastTypeTrait` for `&f32`.
732///
733/// This allows references to `f32` to be used as a broadcast identifier.
734impl BroadcastTypeTrait for &f32 {}
735
736/// Implements `BroadcastTypeTrait` for `&f64`.
737///
738/// This allows references to `f64` to be used as a broadcast identifier.
739impl BroadcastTypeTrait for &f64 {}
740
741/// Implements `BroadcastTypeTrait` for `&IpAddr`.
742///
743/// This allows references to `IpAddr` to be used as a broadcast identifier.
744impl BroadcastTypeTrait for &IpAddr {}
745
746/// Implements `BroadcastTypeTrait` for `&Ipv4Addr`.
747///
748/// This allows references to `Ipv4Addr` to be used as a broadcast identifier.
749impl BroadcastTypeTrait for &Ipv4Addr {}
750
751/// Implements `BroadcastTypeTrait` for `&Ipv6Addr`.
752///
753/// This allows references to `Ipv6Addr` to be used as a broadcast identifier.
754impl BroadcastTypeTrait for &Ipv6Addr {}
755
756/// Implements `BroadcastTypeTrait` for `&SocketAddr`.
757///
758/// This allows references to `SocketAddr` to be used as a broadcast identifier.
759impl BroadcastTypeTrait for &SocketAddr {}
760
761/// Implements `BroadcastTypeTrait` for `&NonZeroU8`.
762///
763/// This allows references to `NonZeroU8` to be used as a broadcast identifier.
764impl BroadcastTypeTrait for &NonZeroU8 {}
765
766/// Implements `BroadcastTypeTrait` for `&NonZeroU16`.
767///
768/// This allows references to `NonZeroU16` to be used as a broadcast identifier.
769impl BroadcastTypeTrait for &NonZeroU16 {}
770
771/// Implements `BroadcastTypeTrait` for `&NonZeroU32`.
772///
773/// This allows references to `NonZeroU32` to be used as a broadcast identifier.
774impl BroadcastTypeTrait for &NonZeroU32 {}
775
776/// Implements `BroadcastTypeTrait` for `&NonZeroU64`.
777///
778/// This allows references to `NonZeroU64` to be used as a broadcast identifier.
779impl BroadcastTypeTrait for &NonZeroU64 {}
780
781/// Implements `BroadcastTypeTrait` for `&NonZeroU128`.
782///
783/// This allows references to `NonZeroU128` to be used as a broadcast identifier.
784impl BroadcastTypeTrait for &NonZeroU128 {}
785
786/// Implements `BroadcastTypeTrait` for `&NonZeroUsize`.
787///
788/// This allows references to `NonZeroUsize` to be used as a broadcast identifier.
789impl BroadcastTypeTrait for &NonZeroUsize {}
790
791/// Implements `BroadcastTypeTrait` for `&NonZeroI8`.
792///
793/// This allows references to `NonZeroI8` to be used as a broadcast identifier.
794impl BroadcastTypeTrait for &NonZeroI8 {}
795
796/// Implements `BroadcastTypeTrait` for `&NonZeroI16`.
797///
798/// This allows references to `NonZeroI16` to be used as a broadcast identifier.
799impl BroadcastTypeTrait for &NonZeroI16 {}
800
801/// Implements `BroadcastTypeTrait` for `&NonZeroI32`.
802///
803/// This allows references to `NonZeroI32` to be used as a broadcast identifier.
804impl BroadcastTypeTrait for &NonZeroI32 {}
805
806/// Implements `BroadcastTypeTrait` for `&NonZeroI64`.
807///
808/// This allows references to `NonZeroI64` to be used as a broadcast identifier.
809impl BroadcastTypeTrait for &NonZeroI64 {}
810
811/// Implements `BroadcastTypeTrait` for `&NonZeroI128`.
812///
813/// This allows references to `NonZeroI128` to be used as a broadcast identifier.
814impl BroadcastTypeTrait for &NonZeroI128 {}
815
816/// Implements `BroadcastTypeTrait` for `&NonZeroIsize`.
817///
818/// This allows references to `NonZeroIsize` to be used as a broadcast identifier.
819impl BroadcastTypeTrait for &NonZeroIsize {}
820
821/// Implements `BroadcastTypeTrait` for `&Infallible`.
822///
823/// This allows references to `Infallible` to be used as a broadcast identifier.
824impl BroadcastTypeTrait for &Infallible {}
825
826/// Implements the `Default` trait for `BroadcastType`.
827///
828/// The default value is `BroadcastType::Unknown`.
829///
830/// # Type Parameters
831///
832/// - `BroadcastTypeTrait`: The type parameter for `BroadcastType`, which must implement `BroadcastTypeTrait`.
833impl<B> Default for BroadcastType<B>
834where
835    B: BroadcastTypeTrait,
836{
837    /// Returns the default `BroadcastType`, which is `BroadcastType::Unknown`.
838    #[inline(always)]
839    fn default() -> Self {
840        BroadcastType::Unknown
841    }
842}
843
844impl<B> BroadcastType<B>
845where
846    B: BroadcastTypeTrait,
847{
848    /// Slow-path formatter handling non-string identifiers or keys exceeding [`STACK_KEY_BUF_LEN`].
849    ///
850    /// # Arguments
851    ///
852    /// - `F` - Closure receiving the formatted room key.
853    ///
854    /// # Returns
855    ///
856    /// - `R` - Value returned by `op`.
857    #[cold]
858    #[inline(never)]
859    fn with_key_slow<R, F>(&self, op: F) -> R
860    where
861        F: FnOnce(&str) -> R,
862    {
863        match self {
864            BroadcastType::PointToPoint(key1, key2) => {
865                let (first_key, second_key): (&B, &B) = if key1 <= key2 {
866                    (key1, key2)
867                } else {
868                    (key2, key1)
869                };
870                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
871                let mut writer: StackKeyWriter<'_> = StackKeyWriter {
872                    buf: &mut stack,
873                    len: 0,
874                };
875                let fits: bool = writer.write_str(POINT_TO_POINT_PREFIX).is_ok()
876                    && first_key.write_broadcast_key(&mut writer).is_ok()
877                    && writer.write_char('-').is_ok()
878                    && second_key.write_broadcast_key(&mut writer).is_ok();
879                if fits {
880                    let written: usize = writer.len;
881                    if let Ok(key) = from_utf8(&stack[..written]) {
882                        return op(key);
883                    }
884                }
885                let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
886                key.push_str(POINT_TO_POINT_PREFIX);
887                let _: fmt::Result = first_key.write_broadcast_key(&mut key);
888                key.push('-');
889                let _: fmt::Result = second_key.write_broadcast_key(&mut key);
890                op(&key)
891            }
892            BroadcastType::PointToGroup(group_key) => {
893                let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
894                let mut writer: StackKeyWriter<'_> = StackKeyWriter {
895                    buf: &mut stack,
896                    len: 0,
897                };
898                let fits: bool = writer.write_str(POINT_TO_GROUP_PREFIX).is_ok()
899                    && group_key.write_broadcast_key(&mut writer).is_ok();
900                if fits {
901                    let written: usize = writer.len;
902                    if let Ok(key) = from_utf8(&stack[..written]) {
903                        return op(key);
904                    }
905                }
906                let mut key: String = String::with_capacity(STACK_KEY_BUF_LEN * 2);
907                key.push_str(POINT_TO_GROUP_PREFIX);
908                let _: fmt::Result = group_key.write_broadcast_key(&mut key);
909                op(&key)
910            }
911            BroadcastType::Unknown => op(EMPTY_STR),
912        }
913    }
914
915    /// Formats this broadcast type's key into a stack buffer when it fits and passes the `&str` to `op`.
916    ///
917    /// # Arguments
918    ///
919    /// - `F` - Closure receiving the borrowed formatted room key.
920    ///
921    /// # Returns
922    ///
923    /// - `R` - Value returned by `op`.
924    #[inline(always)]
925    pub(crate) fn with_key<R, F>(&self, op: F) -> R
926    where
927        F: FnOnce(&str) -> R,
928    {
929        match self {
930            BroadcastType::PointToGroup(group_key) => {
931                if let Some(group_str) = group_key.as_broadcast_str() {
932                    let prefix: &[u8] = POINT_TO_GROUP_PREFIX.as_bytes();
933                    let group_bytes: &[u8] = group_str.as_bytes();
934                    let total: usize = prefix.len() + group_bytes.len();
935                    if total <= STACK_KEY_BUF_LEN {
936                        let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
937                        stack[..prefix.len()].copy_from_slice(prefix);
938                        stack[prefix.len()..total].copy_from_slice(group_bytes);
939                        if let Ok(key) = from_utf8(&stack[..total]) {
940                            return op(key);
941                        }
942                    }
943                }
944                self.with_key_slow(op)
945            }
946            BroadcastType::PointToPoint(key1, key2) => {
947                let (first_key, second_key): (&B, &B) = if key1 <= key2 {
948                    (key1, key2)
949                } else {
950                    (key2, key1)
951                };
952                if let (Some(first_str), Some(second_str)) =
953                    (first_key.as_broadcast_str(), second_key.as_broadcast_str())
954                {
955                    let prefix: &[u8] = POINT_TO_POINT_PREFIX.as_bytes();
956                    let a: &[u8] = first_str.as_bytes();
957                    let b: &[u8] = second_str.as_bytes();
958                    let total: usize = prefix.len() + a.len() + 1 + b.len();
959                    if total <= STACK_KEY_BUF_LEN {
960                        let mut stack: [u8; STACK_KEY_BUF_LEN] = [0u8; STACK_KEY_BUF_LEN];
961                        let p1: usize = prefix.len();
962                        let p2: usize = p1 + a.len();
963                        stack[..p1].copy_from_slice(prefix);
964                        stack[p1..p2].copy_from_slice(a);
965                        stack[p2] = b'-';
966                        stack[p2 + 1..total].copy_from_slice(b);
967                        if let Ok(key) = from_utf8(&stack[..total]) {
968                            return op(key);
969                        }
970                    }
971                }
972                self.with_key_slow(op)
973            }
974            BroadcastType::Unknown => op(EMPTY_STR),
975        }
976    }
977
978    /// Generates a unique key string for a given broadcast type.
979    ///
980    /// For point-to-point types, the keys are sorted to ensure consistent key generation
981    /// regardless of the order of the input keys.
982    ///
983    /// # Arguments
984    ///
985    /// - `BroadcastType<B>` - The broadcast type for which to generate the key.
986    ///
987    /// # Returns
988    ///
989    /// - `String` - The unique key string for the broadcast type.
990    #[inline(always)]
991    pub fn get_key(broadcast_type: BroadcastType<B>) -> String {
992        match &broadcast_type {
993            BroadcastType::PointToGroup(group_key) => {
994                if let Some(group_str) = group_key.as_broadcast_str() {
995                    let mut key: String =
996                        String::with_capacity(POINT_TO_GROUP_PREFIX.len() + group_str.len());
997                    key.push_str(POINT_TO_GROUP_PREFIX);
998                    key.push_str(group_str);
999                    return key;
1000                }
1001                broadcast_type.with_key_slow(|key: &str| key.to_owned())
1002            }
1003            BroadcastType::PointToPoint(key1, key2) => {
1004                let (first_key, second_key): (&B, &B) = if key1 <= key2 {
1005                    (key1, key2)
1006                } else {
1007                    (key2, key1)
1008                };
1009                if let (Some(first_str), Some(second_str)) =
1010                    (first_key.as_broadcast_str(), second_key.as_broadcast_str())
1011                {
1012                    let mut key: String = String::with_capacity(
1013                        POINT_TO_POINT_PREFIX.len() + first_str.len() + second_str.len() + 1,
1014                    );
1015                    key.push_str(POINT_TO_POINT_PREFIX);
1016                    key.push_str(first_str);
1017                    key.push('-');
1018                    key.push_str(second_str);
1019                    return key;
1020                }
1021                broadcast_type.with_key_slow(|key: &str| key.to_owned())
1022            }
1023            BroadcastType::Unknown => String::new(),
1024        }
1025    }
1026}
1027
1028impl<'a, B> WebSocketConfig<'a, B>
1029where
1030    B: BroadcastTypeTrait,
1031{
1032    /// Creates a new WebSocket configuration with the given context.
1033    ///
1034    /// # Arguments
1035    ///
1036    /// - `&'a mut Stream` - The stream object serving this WebSocket.
1037    /// - `&'a mut Context` - The context object to associate with the WebSocket.
1038    ///
1039    /// # Returns
1040    ///
1041    /// - `WebSocketConfig<B>` - A new WebSocket configuration instance.
1042    #[inline(always)]
1043    pub fn new(stream: &'a mut Stream, context: &'a mut Context) -> Self {
1044        Self {
1045            stream,
1046            context,
1047            capacity: DEFAULT_BROADCAST_SENDER_CAPACITY,
1048            broadcast_type: BroadcastType::default(),
1049            connected_hook: Hook::default_handler(),
1050            request_hook: Hook::default_handler(),
1051            sended_hook: Hook::default_handler(),
1052            closed_hook: Hook::default_handler(),
1053        }
1054    }
1055
1056    /// Hands out the stream and the context together.
1057    ///
1058    /// The two borrows live in the same configuration, so they have to be
1059    /// taken together: a caller that wants to run a hook needs both, and the
1060    /// borrow checker will not let it take them one at a time.
1061    ///
1062    /// # Returns
1063    ///
1064    /// - `(&'a mut Stream, &'a mut Context)` - The stream and the context.
1065    #[inline(always)]
1066    pub fn take_parts(self) -> (&'a mut Stream, &'a mut Context) {
1067        // The destructuring pattern is the ยง17.13 escape hatch: it is not
1068        // `self.field` access, and it hands out the two borrows together
1069        // with the lifetime the struct holds them under.
1070        let Self {
1071            stream, context, ..
1072        } = self;
1073        (stream, context)
1074    }
1075}
1076
1077impl<'a, B> WebSocketConfig<'a, B>
1078where
1079    B: BroadcastTypeTrait,
1080{
1081    /// Sets the capacity for the broadcast sender.
1082    ///
1083    /// # Arguments
1084    ///
1085    /// - `Capacity` - The desired capacity.
1086    ///
1087    /// # Returns
1088    ///
1089    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
1090    #[inline(always)]
1091    pub fn set_capacity(mut self, capacity: Capacity) -> Self {
1092        self.capacity = capacity;
1093        self
1094    }
1095
1096    /// Sets the context for the WebSocket connection.
1097    ///
1098    /// # Arguments
1099    ///
1100    /// - `&'a mut Context` - The context object to associate with the WebSocket.
1101    ///
1102    /// # Returns
1103    ///
1104    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
1105    #[inline(always)]
1106    pub fn set_context(mut self, context: &'a mut Context) -> Self {
1107        self.context = context;
1108        self
1109    }
1110
1111    /// Sets the broadcast type for the WebSocket connection.
1112    ///
1113    /// # Arguments
1114    ///
1115    /// - `BroadcastType<B>` - The broadcast type to use for this WebSocket.
1116    ///
1117    /// # Returns
1118    ///
1119    /// - `WebSocketConfig<B>` - The modified WebSocket configuration instance.
1120    #[inline(always)]
1121    pub fn set_broadcast_type(mut self, broadcast_type: BroadcastType<B>) -> Self {
1122        self.broadcast_type = broadcast_type;
1123        self
1124    }
1125
1126    /// Sets the connected hook handler.
1127    ///
1128    /// This hook is executed when the WebSocket connection is established.
1129    ///
1130    /// # Type Parameters
1131    ///
1132    /// - `S`: The hook type, which must implement `ServerHook`.
1133    ///
1134    /// # Returns
1135    ///
1136    /// The modified `WebSocketConfig` instance.
1137    ///
1138    /// # Examples
1139    ///
1140    /// ```rust
1141    /// use hyperlane::{Context, ServerHook, Status, Stream};
1142    /// use hyperlane_plugin_websocket::WebSocketConfig;
1143    /// # use hyperlane::{RequestConfig, Transport, tokio};
1144    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
1145    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
1146    /// #
1147    /// # #[derive(Debug)]
1148    /// # struct MemoryTransport(DuplexStream);
1149    /// #
1150    /// # impl Transport for MemoryTransport {
1151    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
1152    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1153    /// #     }
1154    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
1155    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1156    /// #     }
1157    /// # }
1158    /// #
1159    /// # impl AsyncRead for MemoryTransport {
1160    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1161    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
1162    /// #     }
1163    /// # }
1164    /// #
1165    /// # impl AsyncWrite for MemoryTransport {
1166    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1167    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
1168    /// #     }
1169    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1170    /// #         Pin::new(&mut self.0).poll_flush(cx)
1171    /// #     }
1172    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1173    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
1174    /// #     }
1175    /// # }
1176    ///
1177    /// struct MyConnectedHook;
1178    ///
1179    /// impl ServerHook for MyConnectedHook {
1180    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
1181    ///         Self
1182    ///     }
1183    ///
1184    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
1185    ///         ctx.set_attribute("connected", true);
1186    ///         Status::Continue
1187    ///     }
1188    /// }
1189    ///
1190    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
1191    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
1192    /// # let mut ctx: Context = Context::default();
1193    /// // Register the hook with the stream and context for this connection.
1194    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
1195    ///     .set_connected_hook::<MyConnectedHook>();
1196    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
1197    /// # runtime.block_on(async {
1198    /// #     let hook = config.get_connected_hook().clone();
1199    /// #     let (stream, context) = config.take_parts();
1200    /// #     let status: Status = hook(stream, context).await;
1201    /// #     assert!(matches!(status, Status::Continue));
1202    /// #     assert!(context.get_attribute::<bool, _>("connected"));
1203    /// # });
1204    /// ```
1205    #[inline(always)]
1206    pub fn set_connected_hook<S>(mut self) -> Self
1207    where
1208        S: ServerHook,
1209    {
1210        self.connected_hook = Hook::factory::<S>();
1211        self
1212    }
1213
1214    /// Sets the request hook handler.
1215    ///
1216    /// This hook is executed when a new request is received on the WebSocket.
1217    ///
1218    /// # Type Parameters
1219    ///
1220    /// - `S`: The hook type, which must implement `ServerHook`.
1221    ///
1222    /// # Returns
1223    ///
1224    /// The modified `WebSocketConfig` instance.
1225    ///
1226    /// # Examples
1227    ///
1228    /// ```rust
1229    /// use hyperlane::{Context, ServerHook, Status, Stream};
1230    /// use hyperlane_plugin_websocket::WebSocketConfig;
1231    /// # use hyperlane::{RequestConfig, Transport, tokio};
1232    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
1233    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
1234    /// #
1235    /// # #[derive(Debug)]
1236    /// # struct MemoryTransport(DuplexStream);
1237    /// #
1238    /// # impl Transport for MemoryTransport {
1239    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
1240    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1241    /// #     }
1242    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
1243    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1244    /// #     }
1245    /// # }
1246    /// #
1247    /// # impl AsyncRead for MemoryTransport {
1248    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1249    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
1250    /// #     }
1251    /// # }
1252    /// #
1253    /// # impl AsyncWrite for MemoryTransport {
1254    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1255    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
1256    /// #     }
1257    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1258    /// #         Pin::new(&mut self.0).poll_flush(cx)
1259    /// #     }
1260    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1261    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
1262    /// #     }
1263    /// # }
1264    ///
1265    /// struct MyRequestHook;
1266    ///
1267    /// impl ServerHook for MyRequestHook {
1268    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
1269    ///         Self
1270    ///     }
1271    ///
1272    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
1273    ///         ctx.set_attribute("request_received", true);
1274    ///         Status::Continue
1275    ///     }
1276    /// }
1277    ///
1278    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
1279    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
1280    /// # let mut ctx: Context = Context::default();
1281    /// // Register the hook with the stream and context for this connection.
1282    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
1283    ///     .set_request_hook::<MyRequestHook>();
1284    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
1285    /// # runtime.block_on(async {
1286    /// #     let hook = config.get_request_hook().clone();
1287    /// #     let (stream, context) = config.take_parts();
1288    /// #     let status: Status = hook(stream, context).await;
1289    /// #     assert!(matches!(status, Status::Continue));
1290    /// #     assert!(context.get_attribute::<bool, _>("request_received"));
1291    /// # });
1292    /// ```
1293    #[inline(always)]
1294    pub fn set_request_hook<S>(mut self) -> Self
1295    where
1296        S: ServerHook,
1297    {
1298        self.request_hook = Hook::factory::<S>();
1299        self
1300    }
1301
1302    /// Sets the sended hook handler.
1303    ///
1304    /// This hook is executed after a message has been successfully sent over the WebSocket.
1305    ///
1306    /// # Type Parameters
1307    ///
1308    /// - `S`: The hook type, which must implement `ServerHook`.
1309    ///
1310    /// # Returns
1311    ///
1312    /// The modified `WebSocketConfig` instance.
1313    ///
1314    /// # Examples
1315    ///
1316    /// ```rust
1317    /// use hyperlane::{Context, ServerHook, Status, Stream};
1318    /// use hyperlane_plugin_websocket::WebSocketConfig;
1319    /// # use hyperlane::{RequestConfig, Transport, tokio};
1320    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
1321    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
1322    /// #
1323    /// # #[derive(Debug)]
1324    /// # struct MemoryTransport(DuplexStream);
1325    /// #
1326    /// # impl Transport for MemoryTransport {
1327    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
1328    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1329    /// #     }
1330    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
1331    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1332    /// #     }
1333    /// # }
1334    /// #
1335    /// # impl AsyncRead for MemoryTransport {
1336    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1337    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
1338    /// #     }
1339    /// # }
1340    /// #
1341    /// # impl AsyncWrite for MemoryTransport {
1342    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1343    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
1344    /// #     }
1345    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1346    /// #         Pin::new(&mut self.0).poll_flush(cx)
1347    /// #     }
1348    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1349    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
1350    /// #     }
1351    /// # }
1352    ///
1353    /// struct MySendedHook;
1354    ///
1355    /// impl ServerHook for MySendedHook {
1356    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
1357    ///         Self
1358    ///     }
1359    ///
1360    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
1361    ///         ctx.set_attribute("message_sent", true);
1362    ///         Status::Continue
1363    ///     }
1364    /// }
1365    ///
1366    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
1367    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
1368    /// # let mut ctx: Context = Context::default();
1369    /// // Register the hook with the stream and context for this connection.
1370    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
1371    ///     .set_sended_hook::<MySendedHook>();
1372    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
1373    /// # runtime.block_on(async {
1374    /// #     let hook = config.get_sended_hook().clone();
1375    /// #     let (stream, context) = config.take_parts();
1376    /// #     let status: Status = hook(stream, context).await;
1377    /// #     assert!(matches!(status, Status::Continue));
1378    /// #     assert!(context.get_attribute::<bool, _>("message_sent"));
1379    /// # });
1380    /// ```
1381    #[inline(always)]
1382    pub fn set_sended_hook<S>(mut self) -> Self
1383    where
1384        S: ServerHook,
1385    {
1386        self.sended_hook = Hook::factory::<S>();
1387        self
1388    }
1389
1390    /// Sets the closed hook handler.
1391    ///
1392    /// This hook is executed when the WebSocket connection is closed.
1393    ///
1394    /// # Type Parameters
1395    ///
1396    /// - `S`: The hook type, which must implement `ServerHook`.
1397    ///
1398    /// # Returns
1399    ///
1400    /// The modified `WebSocketConfig` instance.
1401    ///
1402    /// # Examples
1403    ///
1404    /// ```rust
1405    /// use hyperlane::{Context, ServerHook, Status, Stream};
1406    /// use hyperlane_plugin_websocket::WebSocketConfig;
1407    /// # use hyperlane::{RequestConfig, Transport, tokio};
1408    /// # use std::{io, net::SocketAddr, pin::Pin, task::{Context as TaskContext, Poll}};
1409    /// # use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf};
1410    /// #
1411    /// # #[derive(Debug)]
1412    /// # struct MemoryTransport(DuplexStream);
1413    /// #
1414    /// # impl Transport for MemoryTransport {
1415    /// #     fn peer_addr(&self) -> io::Result<SocketAddr> {
1416    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1417    /// #     }
1418    /// #     fn local_addr(&self) -> io::Result<SocketAddr> {
1419    /// #         Err(io::ErrorKind::AddrNotAvailable.into())
1420    /// #     }
1421    /// # }
1422    /// #
1423    /// # impl AsyncRead for MemoryTransport {
1424    /// #     fn poll_read(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &mut ReadBuf<'_>) -> Poll<io::Result<()>> {
1425    /// #         Pin::new(&mut self.0).poll_read(cx, buf)
1426    /// #     }
1427    /// # }
1428    /// #
1429    /// # impl AsyncWrite for MemoryTransport {
1430    /// #     fn poll_write(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buf: &[u8]) -> Poll<io::Result<usize>> {
1431    /// #         Pin::new(&mut self.0).poll_write(cx, buf)
1432    /// #     }
1433    /// #     fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1434    /// #         Pin::new(&mut self.0).poll_flush(cx)
1435    /// #     }
1436    /// #     fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<io::Result<()>> {
1437    /// #         Pin::new(&mut self.0).poll_shutdown(cx)
1438    /// #     }
1439    /// # }
1440    ///
1441    /// struct MyClosedHook;
1442    ///
1443    /// impl ServerHook for MyClosedHook {
1444    ///     async fn new(_stream: &mut Stream, _ctx: &mut Context) -> Self {
1445    ///         Self
1446    ///     }
1447    ///
1448    ///     async fn handle(self, _stream: &mut Stream, ctx: &mut Context) -> Status {
1449    ///         ctx.set_attribute("closed", true);
1450    ///         Status::Continue
1451    ///     }
1452    /// }
1453    ///
1454    /// # let (transport, _peer): (DuplexStream, DuplexStream) = tokio::io::duplex(64);
1455    /// # let mut stream: Stream = Stream::from_transport(MemoryTransport(transport), RequestConfig::default(), false);
1456    /// # let mut ctx: Context = Context::default();
1457    /// // Register the hook with the stream and context for this connection.
1458    /// let mut config: WebSocketConfig<'_, String> = WebSocketConfig::new(&mut stream, &mut ctx)
1459    ///     .set_closed_hook::<MyClosedHook>();
1460    /// # let runtime: tokio::runtime::Runtime = tokio::runtime::Builder::new_current_thread().build().unwrap();
1461    /// # runtime.block_on(async {
1462    /// #     let hook = config.get_closed_hook().clone();
1463    /// #     let (stream, context) = config.take_parts();
1464    /// #     let status: Status = hook(stream, context).await;
1465    /// #     assert!(matches!(status, Status::Continue));
1466    /// #     assert!(context.get_attribute::<bool, _>("closed"));
1467    /// # });
1468    /// ```
1469    #[inline(always)]
1470    pub fn set_closed_hook<S>(mut self) -> Self
1471    where
1472        S: ServerHook,
1473    {
1474        self.closed_hook = Hook::factory::<S>();
1475        self
1476    }
1477}
1478
1479/// Inherent implementation of [`WebSocket`].
1480impl WebSocket {
1481    /// Creates a new WebSocket instance.
1482    ///
1483    /// Initializes with a default broadcast map.
1484    ///
1485    /// # Returns
1486    ///
1487    /// - `WebSocket` - A new WebSocket instance.
1488    #[inline(always)]
1489    pub fn new() -> Self {
1490        Self::default()
1491    }
1492
1493    /// Retrieves the current receiver count for a given broadcast type.
1494    ///
1495    /// # Type Parameters
1496    ///
1497    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1498    ///
1499    /// # Arguments
1500    ///
1501    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
1502    ///
1503    /// # Returns
1504    ///
1505    /// - `ReceiverCount` - The number of active receivers for the broadcast type, or 0 if not found.
1506    #[inline(always)]
1507    pub fn receiver_count<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
1508    where
1509        B: BroadcastTypeTrait,
1510    {
1511        broadcast_type
1512            .with_key(|key: &str| self.get_broadcast_map().receiver_count(key).unwrap_or(0))
1513    }
1514
1515    /// Calculates the receiver count before a connection is established.
1516    ///
1517    /// Ensures the count does not exceed the maximum allowed value minus one.
1518    ///
1519    /// # Type Parameters
1520    ///
1521    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1522    ///
1523    /// # Arguments
1524    ///
1525    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
1526    ///
1527    /// # Returns
1528    ///
1529    /// - `ReceiverCount` - The receiver count after the connection is established.
1530    #[inline(always)]
1531    pub fn receiver_count_before_connected<B>(
1532        &self,
1533        broadcast_type: BroadcastType<B>,
1534    ) -> ReceiverCount
1535    where
1536        B: BroadcastTypeTrait,
1537    {
1538        let count: ReceiverCount = self.receiver_count(broadcast_type);
1539        count.clamp(0, ReceiverCount::MAX - 1) + 1
1540    }
1541
1542    /// Calculates the receiver count after a connection is closed.
1543    ///
1544    /// Ensures the count does not go below 0.
1545    ///
1546    /// # Type Parameters
1547    ///
1548    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1549    ///
1550    /// # Arguments
1551    ///
1552    /// - `BroadcastType<B>` - The broadcast type for which to get the receiver count.
1553    ///
1554    /// # Returns
1555    ///
1556    /// - `ReceiverCount` - The receiver count after the connection is closed.
1557    #[inline(always)]
1558    pub fn receiver_count_after_closed<B>(&self, broadcast_type: BroadcastType<B>) -> ReceiverCount
1559    where
1560        B: BroadcastTypeTrait,
1561    {
1562        let count: ReceiverCount = self.receiver_count(broadcast_type);
1563        count.clamp(1, ReceiverCount::MAX) - 1
1564    }
1565
1566    /// Sends data to all active receivers for a given broadcast type.
1567    ///
1568    /// # Type Parameters
1569    ///
1570    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
1571    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1572    ///
1573    /// # Arguments
1574    ///
1575    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
1576    /// - `T` - The data to send.
1577    ///
1578    /// # Returns
1579    ///
1580    /// - `Result<Option<ReceiverCount>, SendError<Vec<u8>>>` - A result indicating the success or failure of the send operation.
1581    #[inline(always)]
1582    pub fn try_send<T, B>(
1583        &self,
1584        broadcast_type: BroadcastType<B>,
1585        data: T,
1586    ) -> Result<Option<ReceiverCount>, SendError<Vec<u8>>>
1587    where
1588        T: Into<Vec<u8>>,
1589        B: BroadcastTypeTrait,
1590    {
1591        broadcast_type.with_key(|key: &str| self.get_broadcast_map().try_send(key, data.into()))
1592    }
1593
1594    /// Sends data to all active receivers for a given broadcast type.
1595    ///
1596    /// This method panics if the send operation fails.
1597    ///
1598    /// # Type Parameters
1599    ///
1600    /// - `Into<Vec<u8>>`: The type of data to send, which must be convertible to `Vec<u8>`.
1601    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1602    ///
1603    /// # Arguments
1604    ///
1605    /// - `BroadcastType<B>` - The broadcast type to which to send the data.
1606    /// - `T` - The data to send.
1607    ///
1608    /// # Returns
1609    ///
1610    /// - `Option<ReceiverCount>` - The receiver count if the send operation succeeds.
1611    ///
1612    /// # Panics
1613    ///
1614    /// Panics if the send operation fails.
1615    #[inline(always)]
1616    pub fn send<T, B>(&self, broadcast_type: BroadcastType<B>, data: T) -> Option<ReceiverCount>
1617    where
1618        T: Into<Vec<u8>>,
1619        B: BroadcastTypeTrait,
1620    {
1621        self.try_send(broadcast_type, data).unwrap()
1622    }
1623
1624    /// Runs the WebSocket connection, handling incoming requests and outgoing messages.
1625    ///
1626    /// This asynchronous function continuously monitors for new WebSocket requests
1627    /// and incoming broadcast messages, processing them according to the configured hooks.
1628    /// When the broadcast type is `BroadcastType::Unknown`, the stream is closed and
1629    /// the function returns without panicking.
1630    ///
1631    /// # Type Parameters
1632    ///
1633    /// - `BroadcastTypeTrait`: The type implementing `BroadcastTypeTrait`.
1634    ///
1635    /// # Arguments
1636    ///
1637    /// - `WebSocketConfig<'_, B>` - The WebSocket configuration containing the configuration for this WebSocket instance.
1638    pub async fn run<B>(&self, websocket_config: WebSocketConfig<'_, B>)
1639    where
1640        B: BroadcastTypeTrait,
1641    {
1642        let WebSocketConfig {
1643            stream,
1644            context: ctx,
1645            capacity,
1646            broadcast_type,
1647            connected_hook,
1648            request_hook,
1649            sended_hook,
1650            closed_hook,
1651        }: WebSocketConfig<'_, B> = websocket_config;
1652        if matches!(broadcast_type, BroadcastType::Unknown) {
1653            stream.set_closed(true);
1654            return;
1655        }
1656        let key: String = BroadcastType::get_key(broadcast_type);
1657        let mut receiver: Receiver<Vec<u8>> =
1658            self.get_broadcast_map().subscribe_or_insert(&key, capacity);
1659        let mut closed_called: bool = false;
1660        if connected_hook(stream, ctx).await.is_continue() {
1661            loop {
1662                tokio::select! {
1663                    request_res = stream.try_get_websocket_request() => {
1664                        if let Ok(body) = request_res {
1665                            ctx.get_mut_request().set_body(body);
1666                            let is_reject: bool = request_hook(stream, ctx).await.is_reject();
1667                            let body: ResponseBody = ctx.get_response().get_body().clone();
1668                            let is_err: bool = self.get_broadcast_map().try_send(&key, body).is_err();
1669                            if is_err || sended_hook(stream, ctx).await.is_reject() || is_reject {
1670                                break;
1671                            }
1672                        } else {
1673                            closed_called = true;
1674                            ctx.get_mut_response().get_mut_body().clear();
1675                            closed_hook(stream, ctx).await;
1676                            if !ctx.get_response().get_body().is_empty() {
1677                                let body: ResponseBody = ctx.get_response().get_body().clone();
1678                                let _: Result<Option<ReceiverCount>, SendError<Vec<u8>>> =
1679                                    self.get_broadcast_map().try_send(&key, body);
1680                                let _: Status = sended_hook(stream, ctx).await;
1681                            }
1682                            break;
1683                        }
1684                    },
1685                    msg_res = receiver.recv() => {
1686                        match msg_res {
1687                            Ok(msg) => {
1688                                if stream.try_send_list(&WebSocketFrame::create_frame_list(&msg)).await.is_ok() {
1689                                    continue;
1690                                }
1691                                break;
1692                            }
1693                            Err(RecvError::Lagged(_)) => continue,
1694                            Err(RecvError::Closed) => break,
1695                        }
1696                    }
1697                }
1698            }
1699        }
1700        if !closed_called {
1701            ctx.get_mut_response().get_mut_body().clear();
1702            closed_hook(stream, ctx).await;
1703            if !ctx.get_response().get_body().is_empty() {
1704                let body: ResponseBody = take(ctx.get_mut_response().get_mut_body());
1705                let _: Result<Option<ReceiverCount>, SendError<Vec<u8>>> =
1706                    self.get_broadcast_map().try_send(&key, body);
1707            }
1708        }
1709        drop(receiver);
1710        if self.get_broadcast_map().receiver_count(&key) == Some(0) {
1711            let _: Option<Broadcast<Vec<u8>>> = self.get_broadcast_map().unsubscribe(&key);
1712        }
1713        stream.set_closed(true);
1714    }
1715}
1716
1717/// Inherent implementation of [`WebSocketPlugin`].
1718impl WebSocketPlugin {
1719    /// Initializes the global [`WebSocketPlugin`] once with `websocket`.
1720    ///
1721    /// # Arguments
1722    ///
1723    /// - `WebSocket` - Shared WebSocket broadcast hub.
1724    ///
1725    /// # Returns
1726    ///
1727    /// - `&'static Self` - Reference to the initialized global plugin.
1728    pub fn init(websocket: WebSocket) -> &'static Self {
1729        WEBSOCKET_PLUGIN.get_or_init(|| Self { websocket })
1730    }
1731
1732    /// Initializes the global [`WebSocketPlugin`] once with a default [`WebSocket`] hub.
1733    ///
1734    /// # Returns
1735    ///
1736    /// - `&'static Self` - Reference to the initialized global plugin.
1737    pub fn init_default() -> &'static Self {
1738        WEBSOCKET_PLUGIN.get_or_init(Self::default)
1739    }
1740
1741    /// Returns the initialized global [`WebSocketPlugin`], if initialized.
1742    ///
1743    /// # Returns
1744    ///
1745    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1746    pub fn get() -> Option<&'static Self> {
1747        WEBSOCKET_PLUGIN.get()
1748    }
1749
1750    /// Returns the shared [`WebSocket`] broadcast hub.
1751    ///
1752    /// # Returns
1753    ///
1754    /// - `&WebSocket` - Shared WebSocket hub.
1755    pub fn get_websocket(&self) -> &WebSocket {
1756        &self.websocket
1757    }
1758}