diff --git a/jid/src/lib.rs b/jid/src/lib.rs index 543d1ba..878b6f7 100644 --- a/jid/src/lib.rs +++ b/jid/src/lib.rs @@ -1,4 +1,9 @@ -use std::{error::Error, fmt::Display, str::FromStr}; +use std::{ + borrow::Cow, + error::Error, + fmt::{Display, Write}, + str::FromStr, +}; use sqlx::Sqlite; @@ -10,6 +15,28 @@ pub struct JID { pub resourcepart: Option, } +impl<'a> Into> for &'a JID { + fn into(self) -> Cow<'a, str> { + let a = self.to_string(); + Cow::Owned(a) + } +} + +impl Display for JID { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + if let Some(localpart) = &self.localpart { + f.write_str(localpart)?; + f.write_str("@")?; + } + f.write_str(&self.domainpart)?; + if let Some(resourcepart) = &self.resourcepart { + f.write_str("/")?; + f.write_str(resourcepart)?; + } + Ok(()) + } +} + // TODO: feature gate impl sqlx::Type for JID { fn type_info() -> ::TypeInfo { @@ -147,21 +174,6 @@ impl TryFrom<&str> for JID { } } -impl std::fmt::Display for JID { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "{}{}{}", - self.localpart.clone().map(|l| l + "@").unwrap_or_default(), - self.domainpart, - self.resourcepart - .clone() - .map(|r| "/".to_owned() + &r) - .unwrap_or_default() - ) - } -} - #[cfg(test)] mod tests { use super::*;