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