From 65e908e36c2f9f9badc235de7a40e15836c77a8c Mon Sep 17 00:00:00 2001
From: cel 🌸 <cel@bunny.garden>
Date: Tue, 25 Feb 2025 18:43:12 +0000
Subject: implement Into<Cow> for &JID

---
 jid/src/lib.rs | 44 ++++++++++++++++++++++++++++----------------
 1 file changed, 28 insertions(+), 16 deletions(-)

(limited to 'jid')

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<String>,
 }
 
+impl<'a> Into<Cow<'a, str>> 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<Sqlite> for JID {
     fn type_info() -> <Sqlite as sqlx::Database>::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::*;
-- 
cgit