xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
// Copyright (c) 2024 Jonas Schäfer <jonas@zombofant.net>
|
|
|
|
|
//
|
|
|
|
|
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
|
|
|
// 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/.
|
|
|
|
|
|
|
|
|
|
//! Module containing implementations for conversions to/from XML text.
|
|
|
|
|
|
2024-06-26 18:36:48 +02:00
|
|
|
use core::marker::PhantomData;
|
|
|
|
|
|
2024-07-09 16:57:45 +02:00
|
|
|
use std::borrow::Cow;
|
|
|
|
|
|
2024-07-09 17:03:46 +02:00
|
|
|
use crate::{error::Error, AsXmlText, FromXmlText};
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
|
2024-06-26 18:36:48 +02:00
|
|
|
#[cfg(feature = "base64")]
|
|
|
|
|
use base64::engine::{general_purpose::STANDARD as StandardBase64Engine, Engine as _};
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
|
|
|
|
|
macro_rules! convert_via_fromstr_and_display {
|
2024-07-24 16:07:59 +02:00
|
|
|
($($(#[cfg $cfg:tt])?$t:ty,)+) => {
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
$(
|
|
|
|
|
$(
|
2024-07-24 16:07:59 +02:00
|
|
|
#[cfg $cfg]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg $cfg))]
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
)?
|
|
|
|
|
impl FromXmlText for $t {
|
2024-07-24 16:07:29 +02:00
|
|
|
#[doc = concat!("Parse [`", stringify!($t), "`] from XML text via [`FromStr`][`core::str::FromStr`].")]
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
fn from_xml_text(s: String) -> Result<Self, Error> {
|
|
|
|
|
s.parse().map_err(Error::text_parse_error)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-07-09 16:57:45 +02:00
|
|
|
$(
|
2024-07-24 16:07:59 +02:00
|
|
|
#[cfg $cfg]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg $cfg))]
|
2024-07-09 16:57:45 +02:00
|
|
|
)?
|
|
|
|
|
impl AsXmlText for $t {
|
2024-07-24 16:07:29 +02:00
|
|
|
#[doc = concat!("Convert [`", stringify!($t), "`] to XML text via [`Display`][`core::fmt::Display`].\n\nThis implementation never fails.")]
|
2024-07-09 16:57:45 +02:00
|
|
|
fn as_xml_text(&self) -> Result<Cow<'_, str>, Error> {
|
|
|
|
|
Ok(Cow::Owned(self.to_string()))
|
|
|
|
|
}
|
|
|
|
|
}
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
)+
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This provides an implementation compliant with xsd::bool.
|
|
|
|
|
impl FromXmlText for bool {
|
2024-07-24 16:07:29 +02:00
|
|
|
/// Parse a boolean from XML text.
|
|
|
|
|
///
|
|
|
|
|
/// The values `"1"` and `"true"` are considered true. The values `"0"`
|
|
|
|
|
/// and `"false"` are considered `false`. Any other value is invalid and
|
|
|
|
|
/// will return an error.
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
fn from_xml_text(s: String) -> Result<Self, Error> {
|
|
|
|
|
match s.as_str() {
|
|
|
|
|
"1" => "true",
|
|
|
|
|
"0" => "false",
|
|
|
|
|
other => other,
|
|
|
|
|
}
|
|
|
|
|
.parse()
|
|
|
|
|
.map_err(Error::text_parse_error)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// This provides an implementation compliant with xsd::bool.
|
2024-07-09 16:57:45 +02:00
|
|
|
impl AsXmlText for bool {
|
2024-07-24 16:07:29 +02:00
|
|
|
/// Convert a boolean to XML text.
|
|
|
|
|
///
|
|
|
|
|
/// `true` is converted to `"true"` and `false` is converted to `"false"`.
|
|
|
|
|
/// This implementation never fails.
|
2024-07-09 16:57:45 +02:00
|
|
|
fn as_xml_text(&self) -> Result<Cow<'_, str>, Error> {
|
|
|
|
|
match self {
|
|
|
|
|
true => Ok(Cow::Borrowed("true")),
|
|
|
|
|
false => Ok(Cow::Borrowed("false")),
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
convert_via_fromstr_and_display! {
|
|
|
|
|
u8,
|
|
|
|
|
u16,
|
|
|
|
|
u32,
|
|
|
|
|
u64,
|
|
|
|
|
u128,
|
|
|
|
|
usize,
|
|
|
|
|
i8,
|
|
|
|
|
i16,
|
|
|
|
|
i32,
|
|
|
|
|
i64,
|
|
|
|
|
i128,
|
|
|
|
|
isize,
|
|
|
|
|
f32,
|
|
|
|
|
f64,
|
2024-07-24 16:08:48 +02:00
|
|
|
char,
|
2024-08-03 17:26:35 +02:00
|
|
|
core::net::IpAddr,
|
|
|
|
|
core::net::Ipv4Addr,
|
|
|
|
|
core::net::Ipv6Addr,
|
|
|
|
|
core::net::SocketAddr,
|
|
|
|
|
core::net::SocketAddrV4,
|
|
|
|
|
core::net::SocketAddrV6,
|
|
|
|
|
core::num::NonZeroU8,
|
|
|
|
|
core::num::NonZeroU16,
|
|
|
|
|
core::num::NonZeroU32,
|
|
|
|
|
core::num::NonZeroU64,
|
|
|
|
|
core::num::NonZeroU128,
|
|
|
|
|
core::num::NonZeroUsize,
|
|
|
|
|
core::num::NonZeroI8,
|
|
|
|
|
core::num::NonZeroI16,
|
|
|
|
|
core::num::NonZeroI32,
|
|
|
|
|
core::num::NonZeroI64,
|
|
|
|
|
core::num::NonZeroI128,
|
|
|
|
|
core::num::NonZeroIsize,
|
xso: add traits for XML text <-> value conversion
The traits have undergone a couple iterations and this is what we end up
with. The core issue which makes this entire thing ugly is the
Orphan Rule, preventing some trait implementations relating to types
which haven't been defined in this crate.
In an ideal world, we would implement FromXmlText and IntoXmlText for
all types implementing FromStr and/or fmt::Display.
This comes with two severe issues:
1. Downstream crates cannot chose to have different
parsing/serialisation behaviour for "normal" text vs. xml.
2. We ourselves cannot define a behaviour for `Option<T>`. `Option<T>`
does not implement `FromStr` (nor `Display`), but the standard
library *could* do that at some point, and thus Rust doesn't let us
implement e.g. `FromXmlText for Option<T> where T: FromXmlText`,
if we also implement it on `T: FromStr`.
The second one hurts particularly once we get to optional attributes:
For these, we need to "detect" that the type is in fact `Option<T>`,
because we then need to invoke `FromXmlText` on `T` instead of
`Option<T>`. Unfortunately, we cannot do that: macros operate on token
streams and we have no type information available.
We can of course match on the name `Option`, but that breaks down when
users re-import `Option` under a different name. Even just enumerating
all the possible correct ways of using `Option` from the standard
library (there are more than three) would be a nuisance at best.
Hence, we need *another* trait or at least a specialized implementation
of `FromXmlText for Option<T>`, and we cannot do that if we blanket-impl
`FromXmlText` on `T: FromStr`.
That makes the traits what they are, and introduces the requirement that
we know about any upstream crate which anyone might want to parse from
or to XML. This sucks a lot, but that's the state of the world. We are
late to the party, and we cannot expect everyone to do the same they
have done for `serde` (many crates have a `feature = "serde"` which then
provides Serialize/Deserialize trait impls for their types).
2024-06-25 17:36:36 +02:00
|
|
|
|
|
|
|
|
#[cfg(feature = "uuid")]
|
|
|
|
|
uuid::Uuid,
|
|
|
|
|
|
|
|
|
|
#[cfg(feature = "jid")]
|
|
|
|
|
jid::Jid,
|
|
|
|
|
#[cfg(feature = "jid")]
|
|
|
|
|
jid::FullJid,
|
|
|
|
|
#[cfg(feature = "jid")]
|
|
|
|
|
jid::BareJid,
|
|
|
|
|
}
|
2024-06-26 18:26:13 +02:00
|
|
|
|
|
|
|
|
/// Represent a way to encode/decode text data into a Rust type.
|
|
|
|
|
///
|
2024-08-03 13:35:41 +02:00
|
|
|
/// This trait can be used in scenarios where implementing [`FromXmlText`]
|
2024-07-09 17:01:42 +02:00
|
|
|
/// and/or [`AsXmlText`] on a type is not feasible or sensible, such as the
|
2024-06-26 18:26:13 +02:00
|
|
|
/// following:
|
|
|
|
|
///
|
|
|
|
|
/// 1. The type originates in a foreign crate, preventing the implementation
|
|
|
|
|
/// of foreign traits.
|
|
|
|
|
///
|
|
|
|
|
/// 2. There is more than one way to convert a value to/from XML.
|
|
|
|
|
///
|
|
|
|
|
/// The codec to use for a text can be specified in the attributes understood
|
2024-07-09 17:01:42 +02:00
|
|
|
/// by `FromXml` and `AsXml` derive macros. See the documentation of the
|
2024-06-26 18:26:13 +02:00
|
|
|
/// [`FromXml`][`macro@crate::FromXml`] derive macro for details.
|
|
|
|
|
pub trait TextCodec<T> {
|
|
|
|
|
/// Decode a string value into the type.
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<T, Error>;
|
2024-06-26 18:26:13 +02:00
|
|
|
|
|
|
|
|
/// Encode the type as string value.
|
|
|
|
|
///
|
|
|
|
|
/// If this returns `None`, the string value is not emitted at all.
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, value: &'x T) -> Result<Option<Cow<'x, str>>, Error>;
|
|
|
|
|
|
|
|
|
|
/// Apply a filter to this codec.
|
|
|
|
|
///
|
|
|
|
|
/// Filters preprocess strings before they are handed to the codec for
|
|
|
|
|
/// parsing, allowing to, for example, make the codec ignore irrelevant
|
|
|
|
|
/// content by stripping it.
|
|
|
|
|
// NOTE: The bound on T is needed because any given type A may implement
|
|
|
|
|
// TextCodec for any number of types. If we pass T down to the `Filtered`
|
|
|
|
|
// struct, rustc can do type inferrence on which `TextCodec`
|
|
|
|
|
// implementation the `filtered` method is supposed to have been called
|
|
|
|
|
// on.
|
|
|
|
|
fn filtered<F: TextFilter>(self, filter: F) -> Filtered<F, Self, T>
|
|
|
|
|
where
|
|
|
|
|
// placing the bound here (instead of on the `TextCodec<T>` trait
|
|
|
|
|
// itself) preserves object-safety of TextCodec<T>.
|
|
|
|
|
Self: Sized,
|
|
|
|
|
{
|
|
|
|
|
Filtered {
|
|
|
|
|
filter,
|
|
|
|
|
codec: self,
|
|
|
|
|
bound: PhantomData,
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Wrapper struct to apply a filter to a codec.
|
|
|
|
|
///
|
|
|
|
|
/// You can construct a value of this type via [`TextCodec::filtered`].
|
|
|
|
|
// NOTE: see the note on TextCodec::filtered for why we bind `T` here, too.
|
|
|
|
|
pub struct Filtered<F, C, T> {
|
|
|
|
|
filter: F,
|
|
|
|
|
codec: C,
|
|
|
|
|
bound: PhantomData<T>,
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T, F: TextFilter, C: TextCodec<T>> TextCodec<T> for Filtered<F, C, T> {
|
|
|
|
|
fn decode(&self, s: String) -> Result<T, Error> {
|
|
|
|
|
let s = self.filter.preprocess(s);
|
|
|
|
|
self.codec.decode(s)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
fn encode<'x>(&self, value: &'x T) -> Result<Option<Cow<'x, str>>, Error> {
|
|
|
|
|
self.codec.encode(value)
|
|
|
|
|
}
|
2024-06-26 18:26:13 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Text codec which does no transform.
|
|
|
|
|
pub struct Plain;
|
|
|
|
|
|
|
|
|
|
impl TextCodec<String> for Plain {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<String, Error> {
|
2024-06-26 18:26:13 +02:00
|
|
|
Ok(s)
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, value: &'x String) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-09 17:01:42 +02:00
|
|
|
Ok(Some(Cow::Borrowed(value.as_str())))
|
2024-06-26 18:26:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 13:35:41 +02:00
|
|
|
/// Text codec which returns `None` if the input to decode is the empty string, instead of
|
|
|
|
|
/// attempting to decode it.
|
|
|
|
|
///
|
|
|
|
|
/// Particularly useful when parsing `Option<T>` on `#[xml(text)]`, which does not support
|
|
|
|
|
/// `Option<_>` otherwise.
|
2024-06-26 18:26:13 +02:00
|
|
|
pub struct EmptyAsNone;
|
|
|
|
|
|
2024-08-03 13:35:41 +02:00
|
|
|
impl<T> TextCodec<Option<T>> for EmptyAsNone
|
|
|
|
|
where
|
|
|
|
|
T: FromXmlText + AsXmlText,
|
|
|
|
|
{
|
|
|
|
|
fn decode(&self, s: String) -> Result<Option<T>, Error> {
|
2024-07-03 11:12:20 +02:00
|
|
|
if s.is_empty() {
|
2024-06-26 18:26:13 +02:00
|
|
|
Ok(None)
|
|
|
|
|
} else {
|
2024-08-03 13:35:41 +02:00
|
|
|
Some(T::from_xml_text(s)).transpose()
|
2024-06-26 18:26:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 13:35:41 +02:00
|
|
|
fn encode<'x>(&self, value: &'x Option<T>) -> Result<Option<Cow<'x, str>>, Error> {
|
|
|
|
|
Ok(value
|
|
|
|
|
.as_ref()
|
|
|
|
|
.map(AsXmlText::as_xml_text)
|
|
|
|
|
.transpose()?
|
|
|
|
|
.map(|v| (!v.is_empty()).then_some(v))
|
|
|
|
|
.flatten())
|
2024-06-26 18:26:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
2024-06-26 18:36:48 +02:00
|
|
|
|
2024-07-24 17:47:35 +02:00
|
|
|
/// Text codec which returns None instead of the empty string.
|
|
|
|
|
pub struct EmptyAsError;
|
|
|
|
|
|
|
|
|
|
impl TextCodec<String> for EmptyAsError {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<String, Error> {
|
2024-07-24 17:47:35 +02:00
|
|
|
if s.is_empty() {
|
|
|
|
|
Err(Error::Other("Empty text node."))
|
|
|
|
|
} else {
|
|
|
|
|
Ok(s)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, value: &'x String) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-24 17:47:35 +02:00
|
|
|
if value.is_empty() {
|
|
|
|
|
Err(Error::Other("Empty text node."))
|
|
|
|
|
} else {
|
|
|
|
|
Ok(Some(Cow::Borrowed(value.as_str())))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-06-26 18:36:48 +02:00
|
|
|
/// Trait for preprocessing text data from XML.
|
|
|
|
|
///
|
|
|
|
|
/// This may be used by codecs to allow to customize some of their behaviour.
|
|
|
|
|
pub trait TextFilter {
|
|
|
|
|
/// Process the incoming string and return the result of the processing.
|
2024-08-03 10:51:23 +02:00
|
|
|
fn preprocess(&self, s: String) -> String;
|
2024-06-26 18:36:48 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Text preprocessor which returns the input unchanged.
|
|
|
|
|
pub struct NoFilter;
|
|
|
|
|
|
|
|
|
|
impl TextFilter for NoFilter {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn preprocess(&self, s: String) -> String {
|
2024-06-26 18:36:48 +02:00
|
|
|
s
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Text preprocessor to remove all whitespace.
|
|
|
|
|
pub struct StripWhitespace;
|
|
|
|
|
|
|
|
|
|
impl TextFilter for StripWhitespace {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn preprocess(&self, s: String) -> String {
|
2024-06-26 18:36:48 +02:00
|
|
|
let s: String = s
|
|
|
|
|
.chars()
|
|
|
|
|
.filter(|ch| *ch != ' ' && *ch != '\n' && *ch != '\t')
|
|
|
|
|
.collect();
|
|
|
|
|
s
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// Text codec transforming text to binary using standard base64.
|
|
|
|
|
///
|
|
|
|
|
/// The `Filter` type argument can be used to employ additional preprocessing
|
|
|
|
|
/// of incoming text data. Most interestingly, passing [`StripWhitespace`]
|
|
|
|
|
/// will make the implementation ignore any whitespace within the text.
|
|
|
|
|
#[cfg(feature = "base64")]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
|
2024-08-03 10:51:23 +02:00
|
|
|
pub struct Base64;
|
2024-06-26 18:36:48 +02:00
|
|
|
|
|
|
|
|
#[cfg(feature = "base64")]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
|
2024-08-03 10:51:23 +02:00
|
|
|
impl TextCodec<Vec<u8>> for Base64 {
|
|
|
|
|
fn decode(&self, s: String) -> Result<Vec<u8>, Error> {
|
2024-07-03 11:12:20 +02:00
|
|
|
StandardBase64Engine
|
2024-08-03 10:51:23 +02:00
|
|
|
.decode(s.as_bytes())
|
2024-07-03 11:12:20 +02:00
|
|
|
.map_err(Error::text_parse_error)
|
2024-06-26 18:36:48 +02:00
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, value: &'x Vec<u8>) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-09 17:01:42 +02:00
|
|
|
Ok(Some(Cow::Owned(StandardBase64Engine.encode(&value))))
|
2024-06-26 18:36:48 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(feature = "base64")]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
|
2024-08-03 10:51:23 +02:00
|
|
|
impl<'x> TextCodec<Cow<'x, [u8]>> for Base64 {
|
|
|
|
|
fn decode(&self, s: String) -> Result<Cow<'x, [u8]>, Error> {
|
2024-07-24 16:09:02 +02:00
|
|
|
StandardBase64Engine
|
2024-08-03 10:51:23 +02:00
|
|
|
.decode(s.as_bytes())
|
2024-07-24 16:09:02 +02:00
|
|
|
.map_err(Error::text_parse_error)
|
|
|
|
|
.map(Cow::Owned)
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'a>(&self, value: &'a Cow<'x, [u8]>) -> Result<Option<Cow<'a, str>>, Error> {
|
2024-07-24 16:09:02 +02:00
|
|
|
Ok(Some(Cow::Owned(StandardBase64Engine.encode(&value))))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
#[cfg(feature = "base64")]
|
|
|
|
|
#[cfg_attr(docsrs, doc(cfg(feature = "base64")))]
|
2024-08-03 10:51:23 +02:00
|
|
|
impl<T> TextCodec<Option<T>> for Base64
|
2024-07-24 16:09:02 +02:00
|
|
|
where
|
2024-08-03 10:51:23 +02:00
|
|
|
Base64: TextCodec<T>,
|
2024-07-24 16:09:02 +02:00
|
|
|
{
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<Option<T>, Error> {
|
2024-07-03 11:12:20 +02:00
|
|
|
if s.is_empty() {
|
2024-06-26 18:36:48 +02:00
|
|
|
return Ok(None);
|
|
|
|
|
}
|
2024-08-03 10:51:23 +02:00
|
|
|
Ok(Some(self.decode(s)?))
|
2024-06-26 18:36:48 +02:00
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, decoded: &'x Option<T>) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-09 17:01:42 +02:00
|
|
|
decoded
|
|
|
|
|
.as_ref()
|
2024-08-03 10:51:23 +02:00
|
|
|
.map(|x| self.encode(x))
|
2024-07-09 17:01:42 +02:00
|
|
|
.transpose()
|
|
|
|
|
.map(Option::flatten)
|
2024-06-26 18:36:48 +02:00
|
|
|
}
|
|
|
|
|
}
|
2024-07-24 16:27:50 +02:00
|
|
|
|
|
|
|
|
/// Text codec transforming text to binary using hexadecimal nibbles.
|
|
|
|
|
///
|
|
|
|
|
/// The length must be known at compile-time.
|
|
|
|
|
pub struct FixedHex<const N: usize>;
|
|
|
|
|
|
|
|
|
|
impl<const N: usize> TextCodec<[u8; N]> for FixedHex<N> {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<[u8; N], Error> {
|
2024-07-24 16:27:50 +02:00
|
|
|
if s.len() != 2 * N {
|
|
|
|
|
return Err(Error::Other("Invalid length"));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
let mut bytes = [0u8; N];
|
|
|
|
|
for i in 0..N {
|
|
|
|
|
bytes[i] =
|
|
|
|
|
u8::from_str_radix(&s[2 * i..2 * i + 2], 16).map_err(Error::text_parse_error)?;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
Ok(bytes)
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, value: &'x [u8; N]) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-24 16:27:50 +02:00
|
|
|
let mut bytes = String::with_capacity(N * 2);
|
|
|
|
|
for byte in value {
|
|
|
|
|
bytes.extend(format!("{:02x}", byte).chars());
|
|
|
|
|
}
|
|
|
|
|
Ok(Some(Cow::Owned(bytes)))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T, const N: usize> TextCodec<Option<T>> for FixedHex<N>
|
|
|
|
|
where
|
|
|
|
|
FixedHex<N>: TextCodec<T>,
|
|
|
|
|
{
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<Option<T>, Error> {
|
2024-07-24 16:27:50 +02:00
|
|
|
if s.is_empty() {
|
|
|
|
|
return Ok(None);
|
|
|
|
|
}
|
2024-08-03 10:51:23 +02:00
|
|
|
Ok(Some(self.decode(s)?))
|
2024-07-24 16:27:50 +02:00
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, decoded: &'x Option<T>) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-24 16:27:50 +02:00
|
|
|
decoded
|
|
|
|
|
.as_ref()
|
2024-08-03 10:51:23 +02:00
|
|
|
.map(|x| self.encode(x))
|
2024-07-24 16:27:50 +02:00
|
|
|
.transpose()
|
|
|
|
|
.map(Option::flatten)
|
|
|
|
|
}
|
|
|
|
|
}
|
2024-07-24 16:30:36 +02:00
|
|
|
|
|
|
|
|
/// Text codec for colon-separated bytes of uppercase hexadecimal.
|
|
|
|
|
pub struct ColonSeparatedHex;
|
|
|
|
|
|
|
|
|
|
impl TextCodec<Vec<u8>> for ColonSeparatedHex {
|
2024-08-03 10:51:23 +02:00
|
|
|
fn decode(&self, s: String) -> Result<Vec<u8>, Error> {
|
2024-07-24 16:30:36 +02:00
|
|
|
assert_eq!((s.len() + 1) % 3, 0);
|
|
|
|
|
let mut bytes = Vec::with_capacity((s.len() + 1) / 3);
|
|
|
|
|
for i in 0..(1 + s.len()) / 3 {
|
|
|
|
|
let byte =
|
|
|
|
|
u8::from_str_radix(&s[3 * i..3 * i + 2], 16).map_err(Error::text_parse_error)?;
|
|
|
|
|
if 3 * i + 2 < s.len() {
|
|
|
|
|
assert_eq!(&s[3 * i + 2..3 * i + 3], ":");
|
|
|
|
|
}
|
|
|
|
|
bytes.push(byte);
|
|
|
|
|
}
|
|
|
|
|
Ok(bytes)
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-03 10:51:23 +02:00
|
|
|
fn encode<'x>(&self, decoded: &'x Vec<u8>) -> Result<Option<Cow<'x, str>>, Error> {
|
2024-07-24 16:30:36 +02:00
|
|
|
// TODO: Super inefficient!
|
|
|
|
|
let mut bytes = Vec::with_capacity(decoded.len());
|
|
|
|
|
for byte in decoded {
|
|
|
|
|
bytes.push(format!("{:02X}", byte));
|
|
|
|
|
}
|
|
|
|
|
Ok(Some(Cow::Owned(bytes.join(":"))))
|
|
|
|
|
}
|
|
|
|
|
}
|