use crate::estimator::Estimator;
use crate::{hash, RandomState};
use std::hash::Hash;
use std::sync::Arc;
pub struct Inflight {
estimator: Arc<Estimator>,
hasher: RandomState,
}
const HASHES: usize = 4;
const SLOTS: usize = 8192;
impl Inflight {
pub fn new() -> Self {
Inflight {
estimator: Arc::new(Estimator::new(HASHES, SLOTS)),
hasher: RandomState::new(),
}
}
pub fn incr<T: Hash>(&self, key: T, value: isize) -> (Guard, isize) {
let guard = Guard {
estimator: self.estimator.clone(),
id: hash(key, &self.hasher),
value,
};
let estimation = guard.incr();
(guard, estimation)
}
}
pub struct Guard {
estimator: Arc<Estimator>,
id: u64,
value: isize,
}
impl Guard {
pub fn incr(&self) -> isize {
self.estimator.incr(self.id, self.value)
}
pub fn get(&self) -> isize {
self.estimator.get(self.id)
}
}
impl Drop for Guard {
fn drop(&mut self) {
self.estimator.decr(self.id, self.value)
}
}
impl std::fmt::Debug for Guard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Guard")
.field("id", &self.id)
.field("value", &self.value)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn inflight_count() {
let inflight = Inflight::new();
let (g1, v) = inflight.incr("a", 1);
assert_eq!(v, 1);
let (g2, v) = inflight.incr("a", 2);
assert_eq!(v, 3);
drop(g1);
assert_eq!(g2.get(), 2);
drop(g2);
let (_, v) = inflight.incr("a", 1);
assert_eq!(v, 1);
}
}