use std::sync::atomic::{AtomicU8, Ordering};
#[derive(Debug, Default)]
pub(crate) struct InvokeIdAllocator {
next: AtomicU8,
}
impl InvokeIdAllocator {
pub(crate) fn new() -> Self {
Self {
next: AtomicU8::new(0),
}
}
pub(crate) fn next_id(&self) -> u8 {
self.next.fetch_add(1, Ordering::Relaxed)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn allocates_sequentially() {
let alloc = InvokeIdAllocator::new();
assert_eq!(alloc.next_id(), 0);
assert_eq!(alloc.next_id(), 1);
assert_eq!(alloc.next_id(), 2);
}
#[test]
fn wraps_at_byte_boundary() {
let alloc = InvokeIdAllocator::new();
for _ in 0..255 {
alloc.next_id();
}
assert_eq!(alloc.next_id(), 255);
assert_eq!(alloc.next_id(), 0);
}
}