1// Copyright (c) 2024 Jonas Schäfer <jonas@zombofant.net>
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7//! Module containing implementations for conversions to/from XML text.
8
9use crate::{error::Error, FromXmlText, IntoXmlText};
10
11#[cfg(feature = "jid")]
12use jid;
13#[cfg(feature = "uuid")]
14use uuid;
15
16macro_rules! convert_via_fromstr_and_display {
17 ($($(#[cfg(feature = $feature:literal)])?$t:ty,)+) => {
18 $(
19 $(
20 #[cfg(feature = $feature)]
21 #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
22 )?
23 impl FromXmlText for $t {
24 fn from_xml_text(s: String) -> Result<Self, Error> {
25 s.parse().map_err(Error::text_parse_error)
26 }
27 }
28
29 $(
30 #[cfg(feature = $feature)]
31 #[cfg_attr(docsrs, doc(cfg(feature = $feature)))]
32 )?
33 impl IntoXmlText for $t {
34 fn into_xml_text(self) -> Result<String, Error> {
35 Ok(self.to_string())
36 }
37 }
38 )+
39 }
40}
41
42/// This provides an implementation compliant with xsd::bool.
43impl FromXmlText for bool {
44 fn from_xml_text(s: String) -> Result<Self, Error> {
45 match s.as_str() {
46 "1" => "true",
47 "0" => "false",
48 other => other,
49 }
50 .parse()
51 .map_err(Error::text_parse_error)
52 }
53}
54
55/// This provides an implementation compliant with xsd::bool.
56impl IntoXmlText for bool {
57 fn into_xml_text(self) -> Result<String, Error> {
58 Ok(self.to_string())
59 }
60}
61
62convert_via_fromstr_and_display! {
63 u8,
64 u16,
65 u32,
66 u64,
67 u128,
68 usize,
69 i8,
70 i16,
71 i32,
72 i64,
73 i128,
74 isize,
75 f32,
76 f64,
77 std::net::IpAddr,
78 std::net::Ipv4Addr,
79 std::net::Ipv6Addr,
80 std::net::SocketAddr,
81 std::net::SocketAddrV4,
82 std::net::SocketAddrV6,
83 std::num::NonZeroU8,
84 std::num::NonZeroU16,
85 std::num::NonZeroU32,
86 std::num::NonZeroU64,
87 std::num::NonZeroU128,
88 std::num::NonZeroUsize,
89 std::num::NonZeroI8,
90 std::num::NonZeroI16,
91 std::num::NonZeroI32,
92 std::num::NonZeroI64,
93 std::num::NonZeroI128,
94 std::num::NonZeroIsize,
95
96 #[cfg(feature = "uuid")]
97 uuid::Uuid,
98
99 #[cfg(feature = "jid")]
100 jid::Jid,
101 #[cfg(feature = "jid")]
102 jid::FullJid,
103 #[cfg(feature = "jid")]
104 jid::BareJid,
105}