hyperlane_broadcast/broadcast/
impl.rs

1use crate::*;
2
3/// Implements the `BroadcastTrait` for any type that also implements `Clone` and `Debug`.
4/// This blanket implementation allows any clonable and debuggable type to be used in the broadcast system.
5impl<T: Clone + Debug> BroadcastTrait for T {}
6
7/// Provides a default implementation for `Broadcast` instances.
8///
9/// The default broadcast channel is initialized with a predefined sender capacity.
10impl<T: BroadcastTrait> Default for Broadcast<T> {
11    /// Creates a new `Broadcast` instance with default settings.
12    ///
13    /// # Returns
14    ///
15    /// A `Broadcast` instance with a sender initialized to `DEFAULT_BROADCAST_SENDER_CAPACITY`
16    /// and a capacity of 0.
17    fn default() -> Self {
18        let sender: BroadcastSender<T> = BroadcastSender::new(DEFAULT_BROADCAST_SENDER_CAPACITY);
19        Broadcast {
20            capacity: 0,
21            sender,
22        }
23    }
24}
25
26/// Implements core functionalities for the `Broadcast` struct.
27impl<T: BroadcastTrait> Broadcast<T> {
28    /// Creates a new `Broadcast` instance with a specified capacity.
29    ///
30    /// # Arguments
31    ///
32    /// - `capacity` - The maximum number of messages that can be buffered in the broadcast channel.
33    ///
34    /// # Returns
35    ///
36    /// A new `Broadcast` instance configured with the given capacity.
37    pub fn new(capacity: Capacity) -> Self {
38        let sender: BroadcastSender<T> = BroadcastSender::new(capacity);
39        let mut broadcast: Broadcast<T> = Broadcast::default();
40        broadcast.sender = sender;
41        broadcast.capacity = capacity;
42        broadcast
43    }
44
45    /// Retrieves the current number of active receivers subscribed to this broadcast channel.
46    ///
47    /// # Returns
48    ///
49    /// The total count of active receivers.
50    pub fn receiver_count(&self) -> ReceiverCount {
51        self.sender.receiver_count()
52    }
53
54    /// Subscribes a new receiver to the broadcast channel.
55    ///
56    /// # Returns
57    ///
58    /// A `BroadcastReceiver` that can be used to receive messages sent through this broadcast channel.
59    pub fn subscribe(&self) -> BroadcastReceiver<T> {
60        self.sender.subscribe()
61    }
62
63    /// Sends a message to all active receivers subscribed to this broadcast channel.
64    ///
65    /// # Arguments
66    ///
67    /// - `data` - The message to be broadcasted.
68    ///
69    /// # Returns
70    ///
71    /// A `BroadcastSendResult` indicating the number of receivers the message was sent to,
72    /// or a `BroadcastSendError` if the send operation failed.
73    pub fn send(&self, data: T) -> BroadcastSendResult<T> {
74        self.sender.send(data)
75    }
76}