wordval-actor 1.0.5

Wordval actor system: high-performance message foundation for drone ground stations
Documentation
//! Actor 寻址 —— 唯一 ID 与命名标识。

use std::fmt;
use std::sync::Arc;

/// Actor 的唯一标识符,由 [`ActorSystem`](crate::ActorSystem) 单调递增分配。
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ActorId(u64);

impl ActorId {
    /// 从原始数值构造(供持久化恢复等场景使用)。
    ///
    /// 注意:ID 由各 [`ActorSystem`](crate::ActorSystem) 实例从 1 起
    /// **独立**分配 —— 跨实例不可复用,按旧实例持久化的 ID 恢复会静默
    /// 别名到新实例的另一个 Actor。跨进程/跨重启的稳定寻址请使用
    /// [`ActorName`](`find` / `resolve_name` / `stop_named`)。
    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)
    }
}

/// Actor 的名称标识(不可变共享字符串 newtype)。
///
/// 名称在 [`ActorSystem`](crate::ActorSystem) 注册表内唯一,
/// 重名 spawn 会返回 [`ActorError::DuplicateName`](crate::ActorError::DuplicateName)。
#[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
    }
}

/// 支持以 `&str` 直查 `ActorName` 键的映射(如 `find` / `resolve_name`
/// 的 `DashMap<ActorName, _>::get(name)`),省去每次查询的分配。
///
/// 契约成立:`ActorName` 的 `Hash`/`Eq` 由 `Arc<str>` 派生,与 `str`
/// 的同值哈希/相等语义一致(`Borrow` 要求)。
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);
    }
}