use std::{
cell::RefCell,
num::NonZeroUsize,
time::{Duration, Instant},
};
pub(crate) enum PolicyInner {
OnDropOnly,
OnCountOperations {
max_operations: usize,
current_operations: RefCell<usize>,
},
LessOften {
duration: Duration,
last_collect: RefCell<Instant>,
},
}
impl Clone for PolicyInner {
fn clone(&self) -> Self {
match self {
Self::OnDropOnly => Self::OnDropOnly,
Self::OnCountOperations { max_operations, .. } => Self::OnCountOperations {
max_operations: *max_operations,
current_operations: RefCell::new(0),
},
Self::LessOften { duration, .. } => Self::LessOften {
duration: *duration,
last_collect: RefCell::new(Instant::now()),
},
}
}
}
#[derive(Clone)]
pub struct Policy {
pub(crate) inner: PolicyInner,
}
impl Policy {
pub fn on_drop_only() -> Self {
Self {
inner: PolicyInner::OnDropOnly,
}
}
pub fn on_count_operations(max_operations: NonZeroUsize) -> Self {
Self {
inner: PolicyInner::OnCountOperations {
max_operations: max_operations.get(),
current_operations: RefCell::new(0),
},
}
}
pub fn less_often(duration: Duration) -> Self {
Self {
inner: PolicyInner::LessOften {
duration,
last_collect: RefCell::new(Instant::now()),
},
}
}
}