From c1dc2df150468e498df7e433c2d85db1111697da Mon Sep 17 00:00:00 2001 From: Nikita Vilunov Date: Sun, 28 Apr 2024 17:29:31 +0200 Subject: [PATCH] xmpp: document xml parsing types --- crates/proto-xmpp/src/xml/mod.rs | 41 ++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/crates/proto-xmpp/src/xml/mod.rs b/crates/proto-xmpp/src/xml/mod.rs index b928fa0..79c85ea 100644 --- a/crates/proto-xmpp/src/xml/mod.rs +++ b/crates/proto-xmpp/src/xml/mod.rs @@ -10,9 +10,38 @@ use anyhow::Result; mod ignore; pub use ignore::Ignore; +/// Types which can be parsed from an XML input stream. +/// +/// Example: +/// ``` +/// #![feature(type_alias_impl_trait)] +/// #![feature(impl_trait_in_assoc_type)] +/// #![feature(coroutines)] +/// # use proto_xmpp::xml::FromXml; +/// # use quick_xml::events::Event; +/// # use quick_xml::name::ResolveResult; +/// # use proto_xmpp::xml::Parser; +/// # use anyhow::Result; +/// +/// struct MyStruct; +/// impl FromXml for MyStruct { +/// type P = impl Parser>; +/// +/// fn parse() -> Self::P { +/// |(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result { +/// (namespace, event) = yield; +/// Ok(MyStruct) +/// } +/// } +/// } +/// ``` pub trait FromXml: Sized { + /// The type of parser instances. + /// + /// If the result type of the [parse] is anonymous, this type member can be defined by using `impl Trait`. type P: Parser>; + /// Creates a new instance of a parser with an initial state. fn parse() -> Self::P; } @@ -25,9 +54,18 @@ pub trait FromXmlTag: FromXml { const NS: &'static str; } +/// A stateful parser instance which consumes XML events until the parsing is complete. +/// +/// Usually implemented with the experimental coroutine syntax, which yields to consume the next XML event, +/// and returns the final result when the parsing is done. pub trait Parser: Sized { type Output; + /// Advance the parsing by one XML event. + /// + /// This method consumes `self`, but if the parsing is incomplete, + /// it will return the next state of the parser in the returned result. + /// Otherwise, it will return the final result of parsing. fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation; } @@ -50,8 +88,11 @@ where } } +/// The result of a single parser iteration. pub enum Continuation { + /// The parsing is complete and the final result is available. Final(Res), + /// The parsing is not complete and more XML events are required. Continue(Parser), }