use std::sync::{Mutex, PoisonError};
use crate::utils::ClientOrderIndex;
use crate::utils::ids::WIDTH_48;
#[derive(Debug, Default)]
pub struct ClientIndices {
last: Mutex<u64>,
}
impl ClientIndices {
#[must_use]
pub const fn new() -> ClientIndices {
ClientIndices { last: Mutex::new(0) }
}
pub fn next(&self, now_ms: u64) -> ClientOrderIndex {
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
let clock = if now_ms <= WIDTH_48 { now_ms } else { 0 };
let next = clock.max(last.saturating_add(1));
let next = if next > WIDTH_48 { 1 } else { next };
*last = next;
ClientOrderIndex::new(next).unwrap_or(ClientOrderIndex::of::<1>())
}
pub fn observe(&self, used: ClientOrderIndex) {
let mut last = self.last.lock().unwrap_or_else(PoisonError::into_inner);
*last = (*last).max(used.get());
}
}
#[cfg(test)]
#[path = "tests/client_index.rs"]
mod tests;