xso: add type-erased and dyn-compatible variant of AsXml

That way, we don't need to know the specific type of iterator or even
iteree anymore. This can turn out useful when working with `Box<dyn _>`,
that is, in contexts where we don't know the (possible or actual) types
at compile time.
This commit is contained in:
Jonas Schäfer 2025-05-01 10:30:46 +02:00 committed by Link Mauve
commit d7b62488dc
3 changed files with 40 additions and 1 deletions

View file

@ -127,6 +127,28 @@ impl<T: AsXml> fmt::Display for PrintRawXml<'_, T> {
}
}
/// Dyn-compatible version of [`AsXml`].
///
/// This trait is automatically implemented for all types which implement
/// `AsXml`.
pub trait AsXmlDyn {
/// Return an iterator which emits the contents of the struct or enum as
/// serialisable [`Item`] items.
fn as_xml_dyn_iter<'x>(
&'x self,
) -> Result<Box<dyn Iterator<Item = Result<Item<'x>, Error>> + 'x>, Error>;
}
impl<T: AsXml> AsXmlDyn for T {
/// Return an iterator which emits the contents of the struct or enum as
/// serialisable [`Item`] items by calling [`AsXml::as_xml_dyn_iter`].
fn as_xml_dyn_iter<'x>(
&'x self,
) -> Result<Box<dyn Iterator<Item = Result<Item<'x>, Error>> + 'x>, Error> {
<T as AsXml>::as_xml_dyn_iter(self)
}
}
#[cfg(test)]
mod tests {
use super::*;