parsers: add xso text trait implementations to types

Jonas Schäfer created

This allows them to be used as attribute in xso-proc derived structs.

Change summary

parsers/src/date.rs        | 17 ++++++++++++++++-
parsers/src/util/macros.rs | 20 ++++++++++++++++++++
2 files changed, 36 insertions(+), 1 deletion(-)

Detailed changes

parsers/src/date.rs 🔗

@@ -4,9 +4,12 @@
 // License, v. 2.0. If a copy of the MPL was not distributed with this
 // file, You can obtain one at http://mozilla.org/MPL/2.0/.
 
+use std::str::FromStr;
+
+use xso::{error::Error, FromXmlText, IntoXmlText};
+
 use chrono::{DateTime as ChronoDateTime, FixedOffset};
 use minidom::{IntoAttributeValue, Node};
-use std::str::FromStr;
 
 /// Implements the DateTime profile of XEP-0082, which represents a
 /// non-recurring moment in time, with an accuracy of seconds or fraction of
@@ -39,6 +42,18 @@ impl FromStr for DateTime {
     }
 }
 
+impl FromXmlText for DateTime {
+    fn from_xml_text(s: String) -> Result<Self, Error> {
+        s.parse().map_err(Error::text_parse_error)
+    }
+}
+
+impl IntoXmlText for DateTime {
+    fn into_xml_text(self) -> Result<String, Error> {
+        Ok(self.0.to_rfc3339())
+    }
+}
+
 impl IntoAttributeValue for DateTime {
     fn into_attribute_value(self) -> Option<String> {
         Some(self.0.to_rfc3339())

parsers/src/util/macros.rs 🔗

@@ -82,6 +82,11 @@ macro_rules! generate_attribute {
                 })
             }
         }
+        impl ::xso::FromXmlText for $elem {
+            fn from_xml_text(s: String) -> Result<$elem, xso::error::Error> {
+                s.parse().map_err(xso::error::Error::text_parse_error)
+            }
+        }
         impl std::fmt::Display for $elem {
             fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
                 write!(fmt, "{}", match self {
@@ -89,6 +94,11 @@ macro_rules! generate_attribute {
                 })
             }
         }
+        impl ::xso::IntoXmlText for $elem {
+            fn into_xml_text(self) -> Result<String, xso::error::Error> {
+                Ok(self.to_string())
+            }
+        }
         impl ::minidom::IntoAttributeValue for $elem {
             fn into_attribute_value(self) -> Option<String> {
                 Some(String::from(match self {
@@ -377,6 +387,16 @@ macro_rules! generate_id {
                 Ok($elem(String::from(s)))
             }
         }
+        impl ::xso::FromXmlText for $elem {
+            fn from_xml_text(s: String) -> Result<$elem, xso::error::Error> {
+                Ok(Self(s))
+            }
+        }
+        impl ::xso::IntoXmlText for $elem {
+            fn into_xml_text(self) ->Result<String, xso::error::Error> {
+                Ok(self.0)
+            }
+        }
         impl ::minidom::IntoAttributeValue for $elem {
             fn into_attribute_value(self) -> Option<String> {
                 Some(self.0)