xmpp: document xml parsing types

This commit is contained in:
Nikita Vilunov 2024-04-28 17:29:31 +02:00
parent c69513f38b
commit c1dc2df150
1 changed files with 41 additions and 0 deletions

View File

@ -10,9 +10,38 @@ use anyhow::Result;
mod ignore; mod ignore;
pub use ignore::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<Output = Result<Self>>;
///
/// fn parse() -> Self::P {
/// |(mut namespace, mut event): (ResolveResult<'static>, &'static Event<'static>)| -> Result<Self> {
/// (namespace, event) = yield;
/// Ok(MyStruct)
/// }
/// }
/// }
/// ```
pub trait FromXml: Sized { 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<Output = Result<Self>>; type P: Parser<Output = Result<Self>>;
/// Creates a new instance of a parser with an initial state.
fn parse() -> Self::P; fn parse() -> Self::P;
} }
@ -25,9 +54,18 @@ pub trait FromXmlTag: FromXml {
const NS: &'static str; 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 { pub trait Parser: Sized {
type Output; 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<Self, Self::Output>; fn consume<'a>(self: Self, namespace: ResolveResult, event: &Event<'a>) -> Continuation<Self, Self::Output>;
} }
@ -50,8 +88,11 @@ where
} }
} }
/// The result of a single parser iteration.
pub enum Continuation<Parser, Res> { pub enum Continuation<Parser, Res> {
/// The parsing is complete and the final result is available.
Final(Res), Final(Res),
/// The parsing is not complete and more XML events are required.
Continue(Parser), Continue(Parser),
} }