From 4e9c4883a3cd8bac64a285ef7f6867a28aa87997 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Wed, 26 Jun 2024 13:12:33 +0200 Subject: [PATCH] parsers: add xso text trait implementations to types This allows them to be used as attribute in xso-proc derived structs. --- parsers/src/date.rs | 17 ++++++++++++++++- parsers/src/util/macros.rs | 20 ++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/parsers/src/date.rs b/parsers/src/date.rs index 672ee2df0c05f1f627ad46131644202bc7c074f1..277fc0d940ea2fe2f8de7e369be21c0226c068ae 100644 --- a/parsers/src/date.rs +++ b/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 { + s.parse().map_err(Error::text_parse_error) + } +} + +impl IntoXmlText for DateTime { + fn into_xml_text(self) -> Result { + Ok(self.0.to_rfc3339()) + } +} + impl IntoAttributeValue for DateTime { fn into_attribute_value(self) -> Option { Some(self.0.to_rfc3339()) diff --git a/parsers/src/util/macros.rs b/parsers/src/util/macros.rs index 0bc4f73975beb3d26791c24ded290d8b731aff1d..6103e4b4efa3a349c47456eb8142d2589b9160ee 100644 --- a/parsers/src/util/macros.rs +++ b/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 { + Ok(self.to_string()) + } + } impl ::minidom::IntoAttributeValue for $elem { fn into_attribute_value(self) -> Option { 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 { + Ok(self.0) + } + } impl ::minidom::IntoAttributeValue for $elem { fn into_attribute_value(self) -> Option { Some(self.0)