use std::str::FromStr;
use uuid::Uuid;
use super::{Id, ParseIdError};
impl FromStr for Id {
type Err = ParseIdError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cleaned = s.trim();
let uuid_shaped = (cleaned.len() == 36 && cleaned.contains('-')) || cleaned.len() == 32;
if uuid_shaped {
if let Ok(uuid) = Uuid::parse_str(cleaned) {
return Ok(Id(uuid.as_u128()));
}
}
cleaned
.parse::<u128>()
.map(Id)
.map_err(|_| ParseIdError(s.to_string()))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_from_str_hyphenated_compact_and_decimal() {
let uuid = Uuid::new_v4();
let hyphenated: Id = uuid.to_string().parse().unwrap();
assert_eq!(hyphenated.to_uuid_v8(), uuid);
let compact: Id = uuid.simple().to_string().parse().unwrap();
assert_eq!(compact, hyphenated);
assert_eq!(compact.to_uuid_v8(), uuid);
let num: Id = "9876543210".parse().unwrap();
assert_eq!(num.as_u128(), 9876543210u128);
}
#[test]
fn test_from_str_rejects_garbage() {
assert!("not-an-id".parse::<Id>().is_err());
assert!("".parse::<Id>().is_err());
assert!("zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz".parse::<Id>().is_err());
}
}