use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct RunId(pub Uuid);
impl RunId {
pub fn new() -> Self {
Self(Uuid::now_v7())
}
}
impl Default for RunId {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Display for RunId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::str::FromStr for RunId {
type Err = uuid::Error;
fn from_str(text: &str) -> Result<Self, Self::Err> {
Uuid::parse_str(text).map(Self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn run_id_round_trips_through_text() {
let id = RunId::new();
assert_eq!(id.to_string().parse::<RunId>().unwrap(), id);
assert!("not-a-run".parse::<RunId>().is_err());
}
#[test]
fn ids_are_unique_and_time_ordered() {
let a = RunId::new();
let b = RunId::new();
assert_ne!(a, b);
assert!(a.to_string() < b.to_string());
let back: RunId = serde_json::from_str(&serde_json::to_string(&a).unwrap()).unwrap();
assert_eq!(back, a);
}
}