use std::fmt::Display;
use std::sync::atomic::AtomicU64;
#[derive(Debug, Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
pub enum ActorId {
Local(u64),
Remote {
node_id: u64,
pid: u64,
},
}
impl ActorId {
pub const fn is_local(&self) -> bool {
matches!(self, ActorId::Local(_))
}
pub const fn pid(&self) -> u64 {
match self {
ActorId::Local(pid) => *pid,
ActorId::Remote { pid, .. } => *pid,
}
}
pub const fn node(&self) -> u64 {
match self {
ActorId::Local(_) => 0,
ActorId::Remote { node_id, .. } => *node_id,
}
}
}
impl Display for ActorId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ActorId::Local(id) => write!(f, "0.{id}"),
ActorId::Remote { node_id, pid } => write!(f, "{node_id}.{pid}"),
}
}
}
static ACTOR_ID_ALLOCATOR: AtomicU64 = AtomicU64::new(0u64);
pub(crate) fn get_new_local_id() -> ActorId {
ActorId::Local(ACTOR_ID_ALLOCATOR.fetch_add(1, std::sync::atomic::Ordering::AcqRel))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_pid() {
let actor_id = ActorId::Local(123);
assert_eq!(123, actor_id.pid());
let actor_id = ActorId::Remote {
node_id: 1,
pid: 123,
};
assert_eq!(123, actor_id.pid());
}
#[test]
fn test_is_local() {
let actor_id = ActorId::Local(123);
assert!(actor_id.is_local());
let actor_id = ActorId::Remote {
node_id: 1,
pid: 123,
};
assert!(!actor_id.is_local());
}
}