use crate::id::Id;
use serde::{Deserialize, Serialize};
use std::fmt;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SessionId(pub Id);
impl SessionId {
pub fn new() -> Self {
Self(Id::new())
}
pub fn parse(s: &str) -> Result<Self, crate::id::IdError> {
Id::parse(s).map(Self)
}
}
impl Default for SessionId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for SessionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn session_id_roundtrip() {
let a = SessionId::new();
let s = a.to_string();
let b = SessionId::parse(&s).unwrap();
assert_eq!(a, b);
}
#[test]
fn session_id_serde() {
let a = SessionId::new();
let s = serde_json::to_string(&a).unwrap();
let b: SessionId = serde_json::from_str(&s).unwrap();
assert_eq!(a, b);
}
#[test]
fn session_id_parse_invalid_empty() {
assert!(SessionId::parse("").is_err());
}
#[test]
fn session_id_parse_invalid_characters() {
assert!(SessionId::parse("0OIl").is_err());
}
#[test]
fn session_id_parse_too_short() {
assert!(SessionId::parse("abc").is_err());
}
#[test]
fn session_id_display_format() {
let a = SessionId::new();
let s = format!("{a}");
assert!(!s.is_empty());
assert!(
(21..=22).contains(&s.len()),
"expected a 21- or 22-char BASE58 id, got {} chars: {s}",
s.len()
);
}
}