misplib/src/v1/schemas/sighting_id.rs
2023-07-12 00:21:51 +02:00

58 lines
No EOL
1.2 KiB
Rust

use regex_macro::regex;
default_derive!{
pub struct SightingId {
id: String
}
}
impl TryFrom<&str> for SightingId {
type Error = &'static str;
fn try_from(value: &str) -> Result<Self, Self::Error> {
let re = regex!("^[[:digit:]]+$");
if value.len() <= 10 && re.is_match(value) {
Ok(SightingId { id: value.to_string() })
}
else {
Err("Failed to parse SightingId")
}
}
}
impl Into<String> for SightingId {
fn into(self) -> String {
self.id
}
}
#[test]
fn empty() {
let id: Result<SightingId, _> = "".try_into();
assert!(id.is_err())
}
#[test]
fn oversized() {
let id: Result<SightingId, _> = "12345678910".try_into();
assert!(id.is_err())
}
#[test]
fn forbidden_char() {
let id: Result<SightingId, _> = "1954a".try_into();
assert!(id.is_err())
}
#[test]
fn valid1() {
let id: Result<SightingId, _> = "12345".try_into();
assert_eq!(id, Ok(SightingId { id: "12345".to_string() }))
}
#[test]
fn valid2() {
let id: Result<SightingId, _> = "0123456789".try_into();
assert_eq!(id, Ok(SightingId { id: "0123456789".to_string() }))
}