From dd62efa24c66eaec87b0cbb99fc48d6bf8441801 Mon Sep 17 00:00:00 2001 From: Alex Auvolat Date: Wed, 1 Jun 2022 00:02:27 +0200 Subject: [PATCH] Implement FromStr for MailUuid --- src/mail_uuid.rs | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/mail_uuid.rs b/src/mail_uuid.rs index b784e78..647238f 100644 --- a/src/mail_uuid.rs +++ b/src/mail_uuid.rs @@ -1,4 +1,5 @@ use std::sync::atomic::{AtomicU64, Ordering}; +use std::str::FromStr; use lazy_static::lazy_static; use rand::prelude::*; @@ -54,15 +55,7 @@ impl<'de> Deserialize<'de> for MailUuid { D: Deserializer<'de>, { let v = String::deserialize(d)?; - let bytes = hex::decode(v).map_err(|_| D::Error::custom("invalid hex"))?; - - if bytes.len() != 24 { - return Err(D::Error::custom("bad length")); - } - - let mut tmp = [0u8; 24]; - tmp[..].copy_from_slice(&bytes); - Ok(Self(tmp)) + MailUuid::from_str(&v).map_err(D::Error::custom) } } @@ -80,3 +73,19 @@ impl ToString for MailUuid { hex::encode(self.0) } } + +impl FromStr for MailUuid { + type Err = &'static str; + + fn from_str(s: &str) -> Result { + 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)) + } +}