use std::fmt;
use std::str::FromStr;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
pub type AgentId = String;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct SnapshotId(pub Uuid);
impl SnapshotId {
pub fn new() -> Self {
Self(Uuid::new_v4())
}
pub fn as_filename(&self) -> String {
self.0.as_hyphenated().to_string()
}
}
impl Default for SnapshotId {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for SnapshotId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0.as_hyphenated())
}
}
impl FromStr for SnapshotId {
type Err = uuid::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Uuid::parse_str(s).map(SnapshotId)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn new_yields_unique_ids() {
let a = SnapshotId::new();
let b = SnapshotId::new();
assert_ne!(a, b);
}
#[test]
fn round_trip_via_filename_and_from_str() {
let id = SnapshotId::new();
let s = id.as_filename();
let back: SnapshotId = s.parse().unwrap();
assert_eq!(id, back);
}
#[test]
fn display_matches_filename() {
let id = SnapshotId::new();
assert_eq!(id.to_string(), id.as_filename());
}
#[test]
fn json_round_trip_uses_transparent_repr() {
let id = SnapshotId::new();
let json = serde_json::to_string(&id).unwrap();
assert!(json.starts_with('"') && json.ends_with('"'));
let back: SnapshotId = serde_json::from_str(&json).unwrap();
assert_eq!(id, back);
}
}