claude_agent/session/state/
ids.rs1use std::str::FromStr;
4
5use serde::{Deserialize, Serialize};
6use uuid::Uuid;
7
8#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)]
9#[serde(transparent)]
10pub struct SessionId(pub Uuid);
11
12impl SessionId {
13 pub fn new() -> Self {
14 Self(Uuid::new_v4())
15 }
16
17 pub fn parse(s: &str) -> Option<Self> {
18 Uuid::parse_str(s).ok().map(Self)
19 }
20}
21
22impl Default for SessionId {
23 fn default() -> Self {
24 Self::new()
25 }
26}
27
28impl std::fmt::Display for SessionId {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 write!(f, "{}", self.0)
31 }
32}
33
34impl FromStr for SessionId {
35 type Err = uuid::Error;
36
37 fn from_str(s: &str) -> Result<Self, Self::Err> {
38 Uuid::parse_str(s).map(Self)
39 }
40}
41
42impl From<Uuid> for SessionId {
43 fn from(uuid: Uuid) -> Self {
44 Self(uuid)
45 }
46}
47
48impl From<&str> for SessionId {
49 fn from(s: &str) -> Self {
50 Self::parse(s).unwrap_or_default()
51 }
52}
53
54impl From<String> for SessionId {
55 fn from(s: String) -> Self {
56 Self::from(s.as_str())
57 }
58}
59
60#[derive(Clone, Debug, Hash, Eq, PartialEq, Serialize, Deserialize)]
61#[serde(transparent)]
62pub struct MessageId(pub String);
63
64impl MessageId {
65 pub fn new() -> Self {
66 Self(Uuid::new_v4().to_string())
67 }
68
69 pub fn from_string(s: impl Into<String>) -> Self {
70 Self(s.into())
71 }
72}
73
74impl Default for MessageId {
75 fn default() -> Self {
76 Self::new()
77 }
78}
79
80impl std::fmt::Display for MessageId {
81 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
82 write!(f, "{}", self.0)
83 }
84}
85
86impl FromStr for MessageId {
87 type Err = std::convert::Infallible;
88
89 fn from_str(s: &str) -> Result<Self, Self::Err> {
90 Ok(Self(s.to_string()))
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn test_session_id_generation() {
100 let id1 = SessionId::new();
101 let id2 = SessionId::new();
102 assert_ne!(id1, id2);
103 }
104
105 #[test]
106 fn test_session_id_parse() {
107 let id = SessionId::new();
108 let parsed = SessionId::parse(&id.to_string());
109 assert_eq!(parsed, Some(id));
110 }
111
112 #[test]
113 fn test_message_id_generation() {
114 let id1 = MessageId::new();
115 let id2 = MessageId::new();
116 assert_ne!(id1, id2);
117 }
118}