From 6434fd8c925797e293c0aaa653e2460e8b970f22 Mon Sep 17 00:00:00 2001 From: Jonas Platte Date: Thu, 14 Apr 2022 17:33:57 +0200 Subject: [PATCH] identifiers: Add conversions from strings to owned ID types --- crates/ruma-macros/src/identifiers.rs | 43 +++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/crates/ruma-macros/src/identifiers.rs b/crates/ruma-macros/src/identifiers.rs index 37e4d292..fd30c009 100644 --- a/crates/ruma-macros/src/identifiers.rs +++ b/crates/ruma-macros/src/identifiers.rs @@ -491,6 +491,31 @@ fn expand_checked_impls(input: &ItemStruct, validate: Path) -> TokenStream { <#id #ty_generics>::parse(s) } } + + impl #impl_generics std::str::FromStr for #owned #ty_generics { + type Err = crate::IdParseError; + + fn from_str(s: &str) -> Result { + <&#id #ty_generics as std::convert::TryFrom<_>>::try_from(s).map(Into::into) + } + } + + impl #impl_generics std::convert::TryFrom<&str> for #owned #ty_generics { + type Error = crate::IdParseError; + + fn try_from(s: &str) -> Result { + <&#id #ty_generics as std::convert::TryFrom<_>>::try_from(s).map(Into::into) + } + } + + impl #impl_generics std::convert::TryFrom for #owned #ty_generics { + type Error = crate::IdParseError; + + fn try_from(s: String) -> Result { + <&#id #ty_generics as std::convert::TryFrom<_>>::try_from(s.as_str()) + .map(Into::into) + } + } } } @@ -505,6 +530,24 @@ fn expand_unchecked_impls(input: &ItemStruct) -> TokenStream { } } + impl From<&str> for #owned { + fn from(s: &str) -> Self { + <&#id>::from(s).into() + } + } + + impl From> for #owned { + fn from(s: Box) -> Self { + <&#id>::from(&*s).into() + } + } + + impl From for #owned { + fn from(s: String) -> Self { + <&#id>::from(s.as_str()).into() + } + } + impl From<&str> for Box<#id> { fn from(s: &str) -> Self { #id::from_box(s.into())