use std::sync::atomic::{AtomicU32, Ordering};
use crate::protocol::dds::types::guid::EntityId;
static ENTITY_COUNTER: AtomicU32 = AtomicU32::new(1);
pub struct EntityIdAllocator;
impl EntityIdAllocator {
pub fn next_writer() -> EntityId {
let n = ENTITY_COUNTER.fetch_add(1, Ordering::Relaxed);
let bytes = n.to_le_bytes(); EntityId {
entity_key: [bytes[0], bytes[1], bytes[2]],
entity_kind: 0x02, }
}
pub fn next_reader() -> EntityId {
let n = ENTITY_COUNTER.fetch_add(1, Ordering::Relaxed);
let bytes = n.to_le_bytes();
EntityId {
entity_key: [bytes[0], bytes[1], bytes[2]],
entity_kind: 0x07, }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writer_ids_are_unique() {
let a = EntityIdAllocator::next_writer();
let b = EntityIdAllocator::next_writer();
assert_ne!(a.entity_key, b.entity_key);
assert_eq!(a.entity_kind, 0x02);
assert_eq!(b.entity_kind, 0x02);
}
#[test]
fn reader_ids_are_unique() {
let a = EntityIdAllocator::next_reader();
let b = EntityIdAllocator::next_reader();
assert_ne!(a.entity_key, b.entity_key);
assert_eq!(a.entity_kind, 0x07);
}
#[test]
fn writer_reader_kind_differs() {
let w = EntityIdAllocator::next_writer();
let r = EntityIdAllocator::next_reader();
assert_eq!(w.entity_kind, 0x02);
assert_eq!(r.entity_kind, 0x07);
}
}