use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NodeId(String);
impl NodeId {
pub fn new(name: impl Into<String>) -> Self {
Self(name.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_start(&self) -> bool {
self.0 == START_NAME
}
pub fn is_end(&self) -> bool {
self.0 == END_NAME
}
pub fn is_sentinel(&self) -> bool {
self.is_start() || self.is_end()
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl From<&str> for NodeId {
fn from(s: &str) -> Self {
Self(s.to_string())
}
}
impl From<String> for NodeId {
fn from(s: String) -> Self {
Self(s)
}
}
impl From<&String> for NodeId {
fn from(s: &String) -> Self {
Self(s.clone())
}
}
impl AsRef<str> for NodeId {
fn as_ref(&self) -> &str {
&self.0
}
}
impl PartialEq<str> for NodeId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for NodeId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
impl PartialEq<String> for NodeId {
fn eq(&self, other: &String) -> bool {
&self.0 == other
}
}
const START_NAME: &str = "__start__";
const END_NAME: &str = "__end__";
pub static START: NodeId = NodeId(String::new());
pub static END: NodeId = NodeId(String::new());
#[inline]
pub fn start() -> NodeId {
NodeId::new(START_NAME)
}
#[inline]
pub fn end() -> NodeId {
NodeId::new(END_NAME)
}
pub const START_NODE: &str = START_NAME;
pub const END_NODE: &str = END_NAME;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_node_id_creation() {
let id = NodeId::new("agent");
assert_eq!(id.as_str(), "agent");
}
#[test]
fn test_node_id_from_str() {
let id: NodeId = "tools".into();
assert_eq!(id.as_str(), "tools");
}
#[test]
fn test_node_id_equality() {
let id1 = NodeId::new("agent");
let id2: NodeId = "agent".into();
assert_eq!(id1, id2);
assert_eq!(id1, "agent");
}
#[test]
fn test_sentinel_nodes() {
let start = start();
let end = end();
assert!(start.is_start());
assert!(!start.is_end());
assert!(start.is_sentinel());
assert!(end.is_end());
assert!(!end.is_start());
assert!(end.is_sentinel());
}
#[test]
fn test_regular_node_not_sentinel() {
let id = NodeId::new("agent");
assert!(!id.is_sentinel());
assert!(!id.is_start());
assert!(!id.is_end());
}
#[test]
fn test_node_id_display() {
let id = NodeId::new("my_agent");
assert_eq!(format!("{}", id), "my_agent");
}
#[test]
fn test_node_id_serialization() {
let id = NodeId::new("agent");
let json = serde_json::to_string(&id).unwrap();
assert_eq!(json, "\"agent\"");
let parsed: NodeId = serde_json::from_str(&json).unwrap();
assert_eq!(parsed, id);
}
}