use std::collections::HashSet;
use tokio::sync::RwLock;
pub(crate) fn user_part(jid: &str) -> &str {
let jid = jid.split('/').next().unwrap_or(jid);
jid.split('@').next().unwrap_or(jid)
}
#[derive(Default)]
pub(crate) struct Blocklist {
users: RwLock<HashSet<String>>,
}
impl Blocklist {
pub async fn replace(&self, jids: impl IntoIterator<Item = String>) {
let fresh: HashSet<String> = jids
.into_iter()
.map(|j| user_part(&j).to_string())
.collect();
*self.users.write().await = fresh;
}
pub async fn insert(&self, jid: &str) {
self.users.write().await.insert(user_part(jid).to_string());
}
pub async fn remove(&self, jid: &str) {
self.users.write().await.remove(user_part(jid));
}
pub async fn contains(&self, jid: &str) -> bool {
self.users.read().await.contains(user_part(jid))
}
pub async fn blocks_either(&self, sender: &str, alt: Option<&str>) -> bool {
if self.contains(sender).await {
return true;
}
match alt {
Some(alt) => self.contains(alt).await,
None => false,
}
}
#[cfg(test)]
pub async fn len(&self) -> usize {
self.users.read().await.len()
}
}