Implement FromStr for MailUuid

This commit is contained in:
Alex 2022-06-01 00:02:27 +02:00
parent 553a15a82a
commit dd62efa24c
Signed by: lx
GPG key ID: 0E496D15096376BE

View file

@ -1,4 +1,5 @@
use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::atomic::{AtomicU64, Ordering};
use std::str::FromStr;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use rand::prelude::*; use rand::prelude::*;
@ -54,15 +55,7 @@ impl<'de> Deserialize<'de> for MailUuid {
D: Deserializer<'de>, D: Deserializer<'de>,
{ {
let v = String::deserialize(d)?; let v = String::deserialize(d)?;
let bytes = hex::decode(v).map_err(|_| D::Error::custom("invalid hex"))?; MailUuid::from_str(&v).map_err(D::Error::custom)
if bytes.len() != 24 {
return Err(D::Error::custom("bad length"));
}
let mut tmp = [0u8; 24];
tmp[..].copy_from_slice(&bytes);
Ok(Self(tmp))
} }
} }
@ -80,3 +73,19 @@ impl ToString for MailUuid {
hex::encode(self.0) hex::encode(self.0)
} }
} }
impl FromStr for MailUuid {
type Err = &'static str;
fn from_str(s: &str) -> Result<MailUuid, &'static str> {
let bytes = hex::decode(s).map_err(|_| "invalid hex")?;
if bytes.len() != 24 {
return Err("bad length");
}
let mut tmp = [0u8; 24];
tmp[..].copy_from_slice(&bytes);
Ok(MailUuid(tmp))
}
}