use std::collections::HashMap;
use parking_lot::Mutex;
use crate::{bucket::RateLimiter, storage::RateLimitStore};
pub struct InMemoryStore<L: RateLimiter> {
buckets: Mutex<HashMap<String, L>>,
factory: Box<dyn Fn() -> L + Send + Sync>,
}
impl<L> InMemoryStore<L>
where
L: RateLimiter,
{
pub fn new(factory: impl Fn() -> L + Send + Sync + 'static) -> Self {
Self {
buckets: Mutex::new(HashMap::new()),
factory: Box::new(factory),
}
}
}
impl<L> RateLimitStore for InMemoryStore<L>
where
L: RateLimiter,
{
fn allow(&self, key: &str) -> bool {
let mut map = self.buckets.lock();
let limiter = map
.entry(key.to_string())
.or_insert_with(|| (self.factory)());
limiter.allow()
}
}