zestors/actor_type/
actor_id.rs

1use std::{
2    fmt::{Debug, Display},
3    sync::atomic::{AtomicU64, Ordering},
4};
5
6/// An actor-id is an incrementally-generated id, unique per actor.
7#[derive(PartialEq, Eq, Debug, PartialOrd, Ord, Hash, Clone, Copy)]
8pub struct ActorId(u64);
9
10impl ActorId {
11    /// Generate a new unique actor-id. 
12    /// 
13    /// This is the only way to create actor-id's. (Except for Clone/Copy)
14    pub fn generate() -> Self {
15        static NEXT_ACTOR_ID: AtomicU64 = AtomicU64::new(0);
16        ActorId(NEXT_ACTOR_ID.fetch_add(1, Ordering::AcqRel))
17    }
18
19    /// Convert the actor-id to a u64.
20    pub fn as_u64(self) -> u64 {
21        self.0
22    }
23}
24
25impl Display for ActorId {
26    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27        <Self as Debug>::fmt(&self, f)
28    }
29}
30
31#[cfg(test)]
32mod test {
33    use super::*;
34
35    #[test]
36    fn actor_ids_increase() {
37        let mut old_id = ActorId::generate();
38        for _ in 0..100 {
39            let id = ActorId::generate();
40            assert!(id > old_id);
41            old_id = id;
42        }
43    }
44}