#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct NonceCounter {
next: Option<u64>,
}
impl NonceCounter {
#[must_use]
pub const fn unknown() -> Self {
NonceCounter { next: None }
}
#[must_use]
pub const fn at(next: u64) -> Self {
NonceCounter { next: Some(next) }
}
#[must_use]
pub const fn next(&self) -> Option<u64> {
self.next
}
pub fn take(&mut self) -> Option<u64> {
let nonce = self.next?;
self.next = Some(nonce.saturating_add(1));
Some(nonce)
}
pub fn set(&mut self, next: u64) {
self.next = Some(next);
}
pub fn forget(&mut self) {
self.next = None;
}
pub fn take_run(&mut self, count: u64) -> Option<u64> {
let first = self.next?;
self.next = Some(first.saturating_add(count));
Some(first)
}
pub fn give_back(&mut self, first: u64, count: u64) {
self.next = match self.next == Some(first.saturating_add(count)) {
true => Some(first),
false => None,
};
}
}
#[cfg(test)]
#[path = "tests/nonce.rs"]
mod tests;