use crate::*;
impl<T: Clone + Debug> BroadcastMapTrait for T {}
impl<T: BroadcastMapTrait> Default for BroadcastMap<T> {
#[inline(always)]
fn default() -> Self {
Self(DashMap::with_hasher(BuildHasherDefault::default()))
}
}
impl<T: BroadcastMapTrait> BroadcastMap<T> {
#[inline(always)]
pub fn new() -> Self {
Self::default()
}
#[inline(always)]
fn get(&self) -> &DashMapStringBroadcast<T> {
&self.0
}
#[inline(always)]
pub fn insert<K>(&self, key: K, capacity: Capacity) -> Option<Broadcast<T>>
where
K: AsRef<str>,
{
let broadcast: Broadcast<T> = Broadcast::new(capacity);
self.get().insert(key.as_ref().to_owned(), broadcast)
}
#[inline(always)]
pub fn receiver_count<K>(&self, key: K) -> Option<ReceiverCount>
where
K: AsRef<str>,
{
self.get()
.get(key.as_ref())
.map(|receiver: Ref<'_, String, Broadcast<T>>| receiver.receiver_count())
}
#[inline(always)]
pub fn subscribe<K>(&self, key: K) -> Option<BroadcastMapReceiver<T>>
where
K: AsRef<str>,
{
self.get()
.get(key.as_ref())
.map(|receiver: Ref<'_, String, Broadcast<T>>| receiver.subscribe())
}
#[inline(always)]
pub fn subscribe_or_insert<K>(&self, key: K, capacity: Capacity) -> BroadcastMapReceiver<T>
where
K: AsRef<str>,
{
let key_ref: &str = key.as_ref();
match self.get().get(key_ref) {
Some(sender) => sender.subscribe(),
None => {
self.insert(key_ref, capacity);
self.subscribe_or_insert(key_ref, capacity)
}
}
}
#[inline(always)]
pub fn try_send<K>(&self, key: K, data: T) -> Result<Option<ReceiverCount>, SendError<T>>
where
K: AsRef<str>,
{
match self.get().get(key.as_ref()) {
Some(sender) => sender.send(data).map(Some),
None => Ok(None),
}
}
#[inline(always)]
pub fn send<K>(&self, key: K, data: T) -> Option<ReceiverCount>
where
K: AsRef<str>,
{
self.try_send(key, data).unwrap()
}
#[inline(always)]
pub fn unsubscribe<K>(&self, key: K) -> Option<Broadcast<T>>
where
K: AsRef<str>,
{
self.get()
.remove(key.as_ref())
.map(|(_, broadcast): (String, Broadcast<T>)| broadcast)
}
}