xso: introduce AsXml trait

This will soon replace the IntoXml trait. The idea here is that we
don't generally need to take ownership of values which are going to
be transformed into XML: most of the time, the XML text is created
by building a string from some more specific type, such as an
integer or an enum. Requiring to clone an entire structure for this
purpose is wasteful.

In other cases, we actually could reference data right from the structs
we are converting to XML. In those cases, assuming that an iterator
always generates owned data would be incorrect, too.

Hence, we introduce a new `Item` type which closely mirrors the
`rxml::Item` type, but where the constituents are `Cow`. In the upcoming
changes, we are going to work toward replacing all uses of `IntoXml`
with `AsXml`, as well as modifying the macros accordingly.
This commit is contained in:
Jonas Schäfer 2024-07-09 16:40:40 +02:00
commit d29b89d307
2 changed files with 119 additions and 0 deletions

View file

@ -24,6 +24,7 @@ pub mod error;
#[cfg(feature = "minidom")]
#[cfg_attr(docsrs, doc(cfg(feature = "minidom")))]
pub mod minidom_compat;
mod rxml_util;
pub mod text;
#[doc(hidden)]
@ -38,6 +39,9 @@ use std::borrow::Cow;
#[doc(inline)]
pub use text::TextCodec;
#[doc(inline)]
pub use rxml_util::Item;
#[doc = include_str!("from_xml_doc.md")]
#[doc(inline)]
#[cfg(feature = "macros")]
@ -75,6 +79,29 @@ pub trait IntoXml {
fn into_event_iter(self) -> Result<Self::EventIter, self::error::Error>;
}
/// Trait allowing to iterate a struct's contents as serialisable
/// [`Item`]s.
///
/// **Important:** Changing the [`ItemIter`][`Self::ItemIter`] associated
/// type is considered a non-breaking change for any given implementation of
/// this trait. Always refer to a type's iterator type using fully-qualified
/// notation, for example: `<T as xso::AsXml>::ItemIter`.
pub trait AsXml {
/// The iterator type.
///
/// **Important:** Changing this type is considered a non-breaking change
/// for any given implementation of this trait. Always refer to a type's
/// iterator type using fully-qualified notation, for example:
/// `<T as xso::AsXml>::ItemIter`.
type ItemIter<'x>: Iterator<Item = Result<Item<'x>, self::error::Error>>
where
Self: 'x;
/// Return an iterator which emits the contents of the struct or enum as
/// serialisable [`Item`] items.
fn as_xml_iter(&self) -> Result<Self::ItemIter<'_>, self::error::Error>;
}
/// Trait for a temporary object allowing to construct a struct from
/// [`rxml::Event`] items.
///