use std::sync::{Mutex, PoisonError};
#[derive(Debug, Default)]
pub struct Nonces {
next: Mutex<Option<u64>>,
}
impl Nonces {
#[must_use]
pub const fn new() -> Nonces {
Nonces { next: Mutex::new(None) }
}
#[must_use]
pub fn kept(&self) -> Option<u64> {
*self.next.lock().unwrap_or_else(PoisonError::into_inner)
}
pub fn read(&self, count: u64) -> u64 {
let mut next = self.next.lock().unwrap_or_else(PoisonError::into_inner);
let nonce = next.map_or(count, |kept| kept.max(count));
*next = Some(nonce);
nonce
}
pub fn sent(&self, nonce: u64) {
let mut next = self.next.lock().unwrap_or_else(PoisonError::into_inner);
let after = nonce.saturating_add(1);
*next = Some(next.map_or(after, |kept| kept.max(after)));
}
pub fn forget(&self) {
*self.next.lock().unwrap_or_else(PoisonError::into_inner) = None;
}
}
#[cfg(test)]
#[path = "tests/nonce.rs"]
mod tests;