jid: Add optional quote support

Maxime “pep” Buquet created

Signed-off-by: Maxime “pep” Buquet <pep@bouah.net>

Change summary

jid/Cargo.toml |  5 +++++
jid/src/lib.rs | 33 +++++++++++++++++++++++++++++++++
2 files changed, 38 insertions(+)

Detailed changes

jid/Cargo.toml 🔗

@@ -23,7 +23,12 @@ memchr = "2.5"
 minidom = { version = "0.15", optional = true }
 serde = { version = "1.0", features = ["derive"], optional = true }
 stringprep = "0.1.3"
+quote = { version = "1.0", optional = true }
+proc-macro2 = { version = "1.0", optional = true }
 
 [dev-dependencies]
 serde_test = "1"
 jid = { path = ".", features = [ "serde" ] }
+
+[features]
+quote = ["dep:quote", "dep:proc-macro2"]

jid/src/lib.rs 🔗

@@ -38,6 +38,11 @@ use std::str::FromStr;
 #[cfg(feature = "serde")]
 use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
 
+#[cfg(feature = "quote")]
+use proc_macro2::TokenStream;
+#[cfg(feature = "quote")]
+use quote::{quote, ToTokens};
+
 mod error;
 pub use crate::error::Error;
 
@@ -369,6 +374,34 @@ impl<'de> Deserialize<'de> for BareJid {
     }
 }
 
+#[cfg(feature = "quote")]
+impl ToTokens for Jid {
+    fn to_tokens(&self, tokens: &mut TokenStream) {
+        tokens.extend(match self {
+            Jid::Full(full) => quote! { Jid::Full(#full) },
+            Jid::Bare(bare) => quote! { Jid::Bare(#bare) },
+        });
+    }
+}
+
+#[cfg(feature = "quote")]
+impl ToTokens for FullJid {
+    fn to_tokens(&self, tokens: &mut TokenStream) {
+        let inner = &self.inner.normalized;
+        let t = quote! { FullJid::new(#inner).unwrap() };
+        tokens.extend(t);
+    }
+}
+
+#[cfg(feature = "quote")]
+impl ToTokens for BareJid {
+    fn to_tokens(&self, tokens: &mut TokenStream) {
+        let inner = &self.inner.normalized;
+        let t = quote! { BareJid::new(#inner).unwrap() };
+        tokens.extend(t);
+    }
+}
+
 impl FullJid {
     /// Constructs a full Jabber ID containing all three components. This is of the form
     /// `node@domain/resource`, where node part is optional.