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