tokio_broadcast/broadcast_map/impl.rs
1use super::*;
2
3/// Constructs compact hasher state seeded with `HASH_SECRET_0`.
4impl Default for BroadcastMapHasher {
5 /// Initializes compact 64-bit hash state without allocating or zeroing a streaming buffer.
6 ///
7 /// # Returns
8 ///
9 /// - `BroadcastMapHasher` - A hasher seeded for `BroadcastMap` lookups.
10 #[inline(always)]
11 fn default() -> Self {
12 Self(HASH_SECRET_0)
13 }
14}
15
16/// Implements high-avalanche 64-bit hashing with a single-pass `write_str` fast path.
17impl Hasher for BroadcastMapHasher {
18 /// Appends bytes to the hash state.
19 ///
20 /// # Arguments
21 ///
22 /// - `&[u8]` - Bytes included in the hash.
23 #[inline(always)]
24 fn write(&mut self, input: &[u8]) {
25 self.0 = hash_bytes(self.0, input);
26 }
27
28 /// Mixes a single trailing byte (such as `str::hash`'s `0xff` delimiter) in O(1).
29 ///
30 /// # Arguments
31 ///
32 /// - `u8` - Single byte to incorporate into the hash state.
33 #[inline(always)]
34 fn write_u8(&mut self, i: u8) {
35 self.0 = self.0.rotate_left(5) ^ (i as u64);
36 }
37
38 /// Returns the finalized 64-bit digest.
39 ///
40 /// # Returns
41 ///
42 /// - `u64` - The 64-bit hash value.
43 #[inline(always)]
44 fn finish(&self) -> u64 {
45 self.0
46 }
47}
48
49/// Implements the `BroadcastMapTrait` for any type that also implements `Clone` and `Debug`.
50/// This blanket implementation allows any clonable and debuggable type to be used as a value in the broadcast map system.
51impl<T: Clone + Debug> BroadcastMapTrait for T {}
52
53/// Provides a default implementation for `BroadcastMap` instances.
54///
55/// The default broadcast map is initialized as an empty `DashMap`.
56impl<T: BroadcastMapTrait> Default for BroadcastMap<T> {
57 /// Creates a new, empty `BroadcastMap` instance.
58 ///
59 /// # Returns
60 ///
61 /// - `BroadcastMap<T>` - An empty broadcast map.
62 #[inline(always)]
63 fn default() -> Self {
64 Self(DashMap::with_hasher(BuildHasherDefault::default()))
65 }
66}
67
68/// Implements core functionalities for the `BroadcastMap` struct.
69impl<T: BroadcastMapTrait> BroadcastMap<T> {
70 /// Creates a new, empty `BroadcastMap` instance.
71 ///
72 /// This is a convenience constructor that simply calls `default()`.
73 ///
74 /// # Returns
75 ///
76 /// - `BroadcastMap<T>` - An empty broadcast map.
77 #[inline(always)]
78 pub fn new() -> Self {
79 Self::default()
80 }
81
82 /// Retrieves an immutable reference to the private channel storage.
83 ///
84 /// This private helper method provides direct access to the internal map.
85 ///
86 /// # Returns
87 ///
88 /// - `&BroadcastMapStorage<T>` - Reference to the internal map.
89 #[inline(always)]
90 fn get(&self) -> &BroadcastMapStorage<T> {
91 &self.0
92 }
93
94 /// Inserts a new broadcast channel into the map with a specified key and capacity.
95 ///
96 /// If a broadcast channel with the given key already exists, it will be replaced.
97 ///
98 /// # Arguments
99 ///
100 /// - `K` - Key convertible to `str`.
101 /// - `usize` - Maximum number of buffered messages.
102 ///
103 /// # Returns
104 ///
105 /// - `Option<Broadcast<T>>` - Previous broadcast channel if replaced.
106 #[inline(always)]
107 pub fn insert<K>(&self, key: K, capacity: usize) -> Option<Broadcast<T>>
108 where
109 K: AsRef<str>,
110 {
111 let broadcast: Broadcast<T> = Broadcast::new(capacity);
112 self.get().insert(key.as_ref().to_owned(), broadcast)
113 }
114
115 /// Retrieves the number of active receivers for the broadcast channel associated with the given key.
116 ///
117 /// # Arguments
118 ///
119 /// - `K` - Key convertible to `str`.
120 ///
121 /// # Returns
122 ///
123 /// - `Option<usize>` - Number of receivers if channel exists.
124 #[inline(always)]
125 pub fn receiver_count<K>(&self, key: K) -> Option<usize>
126 where
127 K: AsRef<str>,
128 {
129 self.get()
130 .get(key.as_ref())
131 .map(|receiver: Ref<'_, String, Broadcast<T>>| receiver.receiver_count())
132 }
133
134 /// Subscribes a new receiver to the broadcast channel associated with the given key.
135 ///
136 /// # Arguments
137 ///
138 /// - `K` - Key convertible to `str`.
139 ///
140 /// # Returns
141 ///
142 /// - `Option<Receiver<T>>` - New receiver if channel exists.
143 #[inline(always)]
144 pub fn subscribe<K>(&self, key: K) -> Option<Receiver<T>>
145 where
146 K: AsRef<str>,
147 {
148 self.get()
149 .get(key.as_ref())
150 .map(|receiver: Ref<'_, String, Broadcast<T>>| receiver.subscribe())
151 }
152
153 /// Subscribes a new receiver to the broadcast channel associated with the given key.
154 /// If the channel does not exist, it will be created with the specified capacity before subscribing.
155 ///
156 /// # Arguments
157 ///
158 /// - `K` - Key convertible to `str`.
159 /// - `usize` - Capacity for new channel if needed.
160 ///
161 /// # Returns
162 ///
163 /// - `Receiver<T>` - New receiver for the channel.
164 #[inline(always)]
165 pub fn subscribe_or_insert<K>(&self, key: K, capacity: usize) -> Receiver<T>
166 where
167 K: AsRef<str>,
168 {
169 let key_ref: &str = key.as_ref();
170 if let Some(sender) = self.get().get(key_ref) {
171 return sender.subscribe();
172 }
173 self.get()
174 .entry(key_ref.to_owned())
175 .or_insert_with(|| Broadcast::new(capacity))
176 .subscribe()
177 }
178
179 /// Attempts to send a message to the broadcast channel associated with the given key.
180 ///
181 /// # Arguments
182 ///
183 /// - `K` - Key convertible to `str`.
184 /// - `T` - Message to broadcast.
185 ///
186 /// # Returns
187 ///
188 /// - `Result<Option<usize>, SendError<T>>` - Send result with receiver count or error.
189 #[inline(always)]
190 pub fn try_send<K>(&self, key: K, data: T) -> Result<Option<usize>, SendError<T>>
191 where
192 K: AsRef<str>,
193 {
194 match self.get().get(key.as_ref()) {
195 Some(sender) => sender.send(data).map(Some),
196 None => Ok(None),
197 }
198 }
199
200 /// Sends a message to the broadcast channel associated with the given key.
201 ///
202 /// # Arguments
203 ///
204 /// - `K` - Key convertible to `str`.
205 /// - `T` - Message to broadcast.
206 ///
207 /// # Returns
208 ///
209 /// - `Option<usize>` - The receiver count if the channel exists.
210 ///
211 /// # Panics
212 ///
213 /// Panics if the send operation fails (e.g., if the channel is closed).
214 #[inline(always)]
215 pub fn send<K>(&self, key: K, data: T) -> Option<usize>
216 where
217 K: AsRef<str>,
218 {
219 self.try_send(key, data).unwrap()
220 }
221
222 /// Unsubscribes and removes the broadcast channel associated with the given key from the map.
223 ///
224 /// This operation effectively cancels all subscriptions to the channel by removing it from the map.
225 /// Any existing receivers will no longer receive new messages, and the channel will be dropped.
226 ///
227 /// # Arguments
228 ///
229 /// - `K` - Key convertible to `str`.
230 ///
231 /// # Returns
232 ///
233 /// - `Option<Broadcast<T>>` - The removed broadcast channel if it existed, or `None` if no channel was associated with the key.
234 #[inline(always)]
235 pub fn unsubscribe<K>(&self, key: K) -> Option<Broadcast<T>>
236 where
237 K: AsRef<str>,
238 {
239 self.get()
240 .remove(key.as_ref())
241 .map(|(_, broadcast): (String, Broadcast<T>)| broadcast)
242 }
243}