use crate::model::channel::Channel;
use crate::model::guild::Guild;
use crate::model::id::{ChannelId, GuildId};
use crate::model::user::User;
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(Debug, Clone)]
pub struct Cache {
inner: Arc<CacheInner>,
}
#[derive(Debug)]
struct CacheInner {
guilds: RwLock<HashMap<GuildId, Guild>>,
channels: RwLock<HashMap<ChannelId, Channel>>,
current_user: RwLock<Option<User>>,
}
impl Cache {
pub fn new() -> Self {
Self {
inner: Arc::new(CacheInner {
guilds: RwLock::new(HashMap::new()),
channels: RwLock::new(HashMap::new()),
current_user: RwLock::new(None),
}),
}
}
pub async fn guild(&self, id: GuildId) -> Option<Guild> {
self.inner.guilds.read().await.get(&id).cloned()
}
pub async fn channel(&self, id: ChannelId) -> Option<Channel> {
self.inner.channels.read().await.get(&id).cloned()
}
pub async fn current_user(&self) -> Option<User> {
self.inner.current_user.read().await.clone()
}
pub(crate) async fn set_current_user(&self, user: User) {
*self.inner.current_user.write().await = Some(user);
}
pub(crate) async fn insert_guild(&self, guild: Guild) {
self.inner.guilds.write().await.insert(guild.id, guild);
}
pub(crate) async fn remove_guild(&self, id: GuildId) {
self.inner.guilds.write().await.remove(&id);
}
pub(crate) async fn insert_channel(&self, channel: Channel) {
self.inner
.channels
.write()
.await
.insert(channel.id, channel);
}
pub(crate) async fn remove_channel(&self, id: ChannelId) {
self.inner.channels.write().await.remove(&id);
}
}
impl Default for Cache {
fn default() -> Self {
Self::new()
}
}