1use crate::id::Id;
6use serde::{Deserialize, Serialize};
7use std::fmt;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(transparent)]
12pub struct SessionId(pub Id);
13
14impl SessionId {
15 pub fn new() -> Self {
17 Self(Id::new())
18 }
19 pub fn parse(s: &str) -> Result<Self, crate::id::IdError> {
21 Id::parse(s).map(Self)
22 }
23}
24
25impl Default for SessionId {
26 fn default() -> Self {
27 Self::new()
28 }
29}
30
31impl fmt::Display for SessionId {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 self.0.fmt(f)
34 }
35}
36
37#[cfg(test)]
38mod tests {
39 use super::*;
40
41 #[test]
42 fn session_id_roundtrip() {
43 let a = SessionId::new();
44 let s = a.to_string();
45 let b = SessionId::parse(&s).unwrap();
46 assert_eq!(a, b);
47 }
48
49 #[test]
50 fn session_id_serde() {
51 let a = SessionId::new();
52 let s = serde_json::to_string(&a).unwrap();
53 let b: SessionId = serde_json::from_str(&s).unwrap();
54 assert_eq!(a, b);
55 }
56
57 #[test]
58 fn session_id_parse_invalid_empty() {
59 assert!(SessionId::parse("").is_err());
60 }
61
62 #[test]
63 fn session_id_parse_invalid_characters() {
64 assert!(SessionId::parse("0OIl").is_err());
66 }
67
68 #[test]
69 fn session_id_parse_too_short() {
70 assert!(SessionId::parse("abc").is_err());
72 }
73
74 #[test]
75 fn session_id_display_format() {
76 let a = SessionId::new();
77 let s = format!("{a}");
78 assert!(!s.is_empty());
79 assert!(
83 (21..=22).contains(&s.len()),
84 "expected a 21- or 22-char BASE58 id, got {} chars: {s}",
85 s.len()
86 );
87 }
88}