use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct NetworkId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct LocalId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ClientId(pub u64);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ComponentKind(pub u16);
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[repr(C)]
pub struct Transform {
pub x: f32,
pub y: f32,
pub z: f32,
pub rotation: f32,
pub entity_type: u16,
}
use std::sync::atomic::{AtomicU64, Ordering};
use thiserror::Error;
#[derive(Debug, Error, PartialEq, Eq)]
pub enum AllocatorError {
#[error("NetworkId overflow (reached u64::MAX)")]
Overflow,
#[error("NetworkId allocator exhausted (reached limit)")]
Exhausted,
}
#[derive(Debug)]
pub struct NetworkIdAllocator {
start_id: u64,
next: AtomicU64,
}
impl Default for NetworkIdAllocator {
fn default() -> Self {
Self::new(1)
}
}
impl NetworkIdAllocator {
#[must_use]
pub fn new(start_id: u64) -> Self {
Self {
start_id,
next: AtomicU64::new(start_id),
}
}
pub fn allocate(&self) -> Result<NetworkId, AllocatorError> {
let val = self
.next
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |curr| {
if curr == u64::MAX {
None
} else {
Some(curr + 1)
}
})
.map_err(|_| AllocatorError::Overflow)?;
if val == 0 {
return Err(AllocatorError::Exhausted);
}
Ok(NetworkId(val))
}
pub fn reset(&self) {
self.next.store(self.start_id, Ordering::Relaxed);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_primitive_derives() {
let nid1 = NetworkId(42);
let nid2 = nid1;
assert_eq!(nid1, nid2);
let lid1 = LocalId(42);
let lid2 = LocalId(42);
assert_eq!(lid1, lid2);
let cid = ClientId(99);
assert_eq!(format!("{cid:?}"), "ClientId(99)");
let kind = ComponentKind(1);
assert_eq!(kind.0, 1);
}
}