use std::fmt;
use std::sync::Arc;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ActorId(u64);
impl ActorId {
pub const fn new(raw: u64) -> Self {
Self(raw)
}
pub const fn raw(self) -> u64 {
self.0
}
}
impl fmt::Display for ActorId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{}", self.0)
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ActorName(Arc<str>);
impl ActorName {
pub fn new(name: impl AsRef<str>) -> Self {
Self(Arc::from(name.as_ref()))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for ActorName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "\"{}\"", self.0)
}
}
impl fmt::Display for ActorName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl AsRef<str> for ActorName {
fn as_ref(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for ActorName {
fn borrow(&self) -> &str {
&self.0
}
}
impl From<&str> for ActorName {
fn from(s: &str) -> Self {
Self::new(s)
}
}
impl From<String> for ActorName {
fn from(s: String) -> Self {
Self(Arc::from(s))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn id_ordering_and_display() {
assert!(ActorId::new(1) < ActorId::new(2));
assert_eq!(ActorId::new(42).raw(), 42);
assert_eq!(ActorId::new(7).to_string(), "#7");
}
#[test]
fn name_equality_across_repr() {
let a: ActorName = "uav-1".into();
let b: ActorName = String::from("uav-1").into();
assert_eq!(a, b);
assert_eq!(a.as_str(), "uav-1");
}
#[test]
fn name_borrow_str_lookup() {
use std::collections::HashMap;
let mut map: HashMap<ActorName, u32> = HashMap::new();
map.insert("uav-1".into(), 1);
assert_eq!(map.get("uav-1"), Some(&1), "Borrow<str> 须支持 &str 直查");
assert_eq!(map.get("uav-2"), None);
}
}