pjson_rs_domain/value_objects/
session_id.rs1use std::fmt;
7use uuid::Uuid;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct SessionId(Uuid);
15
16impl SessionId {
17 pub fn new() -> Self {
19 Self(Uuid::new_v4())
20 }
21
22 pub fn from_uuid(uuid: Uuid) -> Self {
24 Self(uuid)
25 }
26
27 pub fn from_string(s: &str) -> Result<Self, uuid::Error> {
29 Uuid::parse_str(s).map(Self)
30 }
31
32 pub fn as_uuid(&self) -> Uuid {
34 self.0
35 }
36
37 pub fn as_str(&self) -> String {
39 self.0.to_string()
40 }
41}
42
43impl Default for SessionId {
44 fn default() -> Self {
45 Self::new()
46 }
47}
48
49impl fmt::Display for SessionId {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 write!(f, "{}", self.0)
52 }
53}
54
55impl From<Uuid> for SessionId {
56 fn from(uuid: Uuid) -> Self {
57 Self(uuid)
58 }
59}
60
61impl From<SessionId> for Uuid {
62 fn from(id: SessionId) -> Self {
63 id.0
64 }
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 #[test]
72 fn test_session_id_creation() {
73 let id1 = SessionId::new();
74 let id2 = SessionId::new();
75
76 assert_ne!(id1, id2);
77 assert_eq!(id1.as_uuid().get_version_num(), 4);
78 }
79
80 #[test]
81 fn test_session_id_from_string() {
82 let uuid_str = "550e8400-e29b-41d4-a716-446655440000";
83 let id = SessionId::from_string(uuid_str).unwrap();
84 assert_eq!(id.as_str(), uuid_str);
85 }
86}