From 6d1f28eb79c6c70b058fcbae5047dbd744764149 Mon Sep 17 00:00:00 2001 From: cel 🌸 Date: Fri, 30 May 2025 13:29:02 +0100 Subject: doc: everything --- src/declaration.rs | 3 +++ src/element.rs | 66 ++++++++++++++++++++++++++++++++++++++++++++++--- src/endable.rs | 37 ---------------------------- src/error.rs | 26 ++++++++++++++++++-- src/lib.rs | 31 +++++++++++++++++++---- src/loggable.rs | 67 -------------------------------------------------- src/reader.rs | 7 +++--- src/writer.rs | 53 ++++++++++++++++++++++++++++----------- src/writer/endable.rs | 37 ++++++++++++++++++++++++++++ src/writer/loggable.rs | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++ 10 files changed, 260 insertions(+), 134 deletions(-) delete mode 100644 src/endable.rs delete mode 100644 src/loggable.rs create mode 100644 src/writer/endable.rs create mode 100644 src/writer/loggable.rs (limited to 'src') diff --git a/src/declaration.rs b/src/declaration.rs index 2c0855f..ecd877a 100644 --- a/src/declaration.rs +++ b/src/declaration.rs @@ -1,9 +1,11 @@ +/// An XML declaration. pub struct Declaration { pub version_info: VersionInfo, pub encoding_decl: Option, pub sd_decl: Option, } +/// An XML version. #[derive(Clone, Copy)] pub enum VersionInfo { One, @@ -11,6 +13,7 @@ pub enum VersionInfo { } impl Declaration { + /// Create an XML declaration from a version. pub fn version(version: VersionInfo) -> Self { Self { version_info: version, diff --git a/src/element.rs b/src/element.rs index 1c1366a..b6b3c15 100644 --- a/src/element.rs +++ b/src/element.rs @@ -11,12 +11,15 @@ use crate::{ Result, }; +/// Result type for the `FromElement` trait. pub type DeserializeResult = std::result::Result; +/// Trait for conversion from an `Element` into another type, for deserialisation from a `Reader`. pub trait FromElement: Sized { fn from_element(element: Element) -> DeserializeResult; } +/// Trait for conversion from a type into an `Element`, for serialisation into a `Writer`. pub trait IntoElement { fn builder(&self) -> ElementBuilder; @@ -45,18 +48,24 @@ pub struct Name { pub local_name: String, } +/// `Content` represents anything that can be the content of an XML element. #[derive(Debug, Clone)] pub enum Content { + /// A child element. Element(Element), + /// A text value. Text(String), + /// A processing instruction. PI, + /// A comment. Comment(String), } // should this be a trait? +/// `Element` represents an XML element that can be written to a `Writer` or read from a `Reader`. #[derive(Debug, Clone)] pub struct Element { - pub name: Name, + pub(crate) name: Name, // namespace: Name, // each element once created contains the qualified namespace information for that element // the name contains the qualified namespace so this is unnecessary @@ -64,15 +73,15 @@ pub struct Element { // hashmap of explicit namespace declarations on the element itself only // possibly not needed as can be calculated at write time depending on context and qualified namespace, and for reading, element validity and namespaces are kept track of by the reader. // change this to custom namespace declarations only, so you can override the definition of namespaces if you wish - pub namespace_declaration_overrides: HashSet, + pub(crate) namespace_declaration_overrides: HashSet, // attributes can be in a different namespace than the element. how to make sure they are valid? // maybe include the namespace instead of or with the prefix // you can calculate the prefix from the namespaced name and the current writer context // you can validate the prefix and calculate the namespace from the current reader context // this results in readers and writers being able to return qualification errors as they aren't able to create elements until every part is qualified. - pub attributes: HashMap, + pub(crate) attributes: HashMap, // TODO: make a hashmap maybe? to be able to address parts of the content individually - pub content: VecDeque, + pub(crate) content: VecDeque, } impl FromElement for Element { @@ -82,10 +91,12 @@ impl FromElement for Element { } impl Element { + /// Return the namespace the xml element is qualified by, and the localname, for matching on the element when you don't know which kind of element to expect. pub fn identify(&self) -> (Option<&str>, &str) { (self.name.namespace.as_deref(), &self.name.local_name) } + /// Check the localname of the element. pub fn check_name(&self, name: &str) -> DeserializeResult<()> { if self.name.local_name == name { Ok(()) @@ -97,6 +108,7 @@ impl Element { } } + /// Check the element is qualified by a namespace. pub fn check_namespace(&self, namespace: &str) -> DeserializeResult<()> { if self.name.namespace.as_deref() == Some(namespace) { return Ok(()); @@ -114,6 +126,7 @@ impl Element { } } + /// Optionally extract an attribute from the element. pub fn attribute_opt(&mut self, att_name: &str) -> DeserializeResult> { if let Some(att_value) = self.attributes.remove(&Name { namespace: None, @@ -127,6 +140,7 @@ impl Element { } } + /// Optionally extract a namespaced attribute from the elmeent. pub fn attribute_opt_namespaced( &mut self, att_name: &str, @@ -144,6 +158,7 @@ impl Element { } } + /// Extract an attribute from the element. pub fn attribute(&mut self, att_name: &str) -> DeserializeResult { let name = Name { namespace: None, @@ -158,6 +173,7 @@ impl Element { } } + /// Extract a namespaced attribute from the element. pub fn attribute_namespaced( &mut self, att_name: &str, @@ -176,6 +192,7 @@ impl Element { } } + /// Ensure there are no more attributes on the element. pub fn no_more_attributes(self) -> DeserializeResult { if self.attributes.is_empty() { Ok(self) @@ -186,6 +203,8 @@ impl Element { // for xs:any + /// Extract a child of type `T` from the element. + /// E.g. when there is an xs:any. pub fn child_one(&mut self) -> DeserializeResult { if let Some(position) = self.content.iter().position(|content| match content { Content::Element(element) => ::from_element(element.clone()).is_ok(), @@ -204,6 +223,8 @@ impl Element { } } + /// Optionally extract a child of type `T` from the element. + /// E.g. when there is an xs:any. pub fn child_opt(&mut self) -> DeserializeResult> { if let Some(position) = self.content.iter().position(|content| match content { Content::Element(element) => ::from_element(element.clone()).is_ok(), @@ -222,6 +243,7 @@ impl Element { } } + /// Extract several children of type `T` from the element. pub fn children(&mut self) -> DeserializeResult> { let (children, rest): (VecDeque<_>, VecDeque<_>) = self .content @@ -252,6 +274,7 @@ impl Element { Ok(children) } + /// Extract a text value from the element. pub fn value(&mut self) -> DeserializeResult { if let Some(position) = self.content.iter().position(|content| match content { Content::Element(_) => false, @@ -270,6 +293,7 @@ impl Element { } } + /// Optionally extract a text value from the element. pub fn value_opt(&mut self) -> DeserializeResult> { if let Some(position) = self.content.iter().position(|content| match content { Content::Element(_) => false, @@ -290,6 +314,8 @@ impl Element { // for xs:sequence + /// Pop a child element of type `T` from the element. + /// E.g. when there is an xs:sequence. pub fn pop_child_one(&mut self) -> DeserializeResult { loop { let child = self @@ -307,6 +333,8 @@ impl Element { } } + /// Optionally pop a child element of type `T` from the element. + /// E.g. when there is an xs:sequence. pub fn pop_child_opt(&mut self) -> DeserializeResult> { loop { let child = self.content.pop_front(); @@ -327,6 +355,8 @@ impl Element { } } + /// Pop several children of type `T` from the element. + /// E.g. when there is an xs:sequence. pub fn pop_children(&mut self) -> DeserializeResult> { let mut children = Vec::new(); loop { @@ -360,6 +390,8 @@ impl Element { } } + /// Pop a text value from the element. + /// E.g. when there is an xs:sequence. pub fn pop_value(&mut self) -> DeserializeResult { loop { let child = self @@ -381,6 +413,8 @@ impl Element { } } + /// Optionally pop a text value from the element. + /// E.g. when there is an xs:sequence. pub fn pop_value_opt(&mut self) -> DeserializeResult> { loop { let child = self.content.pop_front(); @@ -404,6 +438,7 @@ impl Element { } } + /// Ensure there is no more element content left. pub fn no_more_content(self) -> DeserializeResult { if self .content @@ -423,11 +458,13 @@ impl Element { } } + /// Create a new `ElementBuilder`. pub fn builder(name: impl ToString, namespace: Option) -> ElementBuilder { ElementBuilder::new(name, namespace) } } +/// Builder for the `Element` type. pub struct ElementBuilder { name: Name, namespace_declaration_overrides: Vec, @@ -436,6 +473,7 @@ pub struct ElementBuilder { } impl ElementBuilder { + /// Create a new `ElementBuilder`. pub fn new(name: impl ToString, namespace: Option) -> Self { Self { name: Name { @@ -448,6 +486,7 @@ impl ElementBuilder { } } + /// Push a namespace declaration override onto the element builder. pub fn push_namespace_declaration_override( mut self, prefix: Option, @@ -461,6 +500,7 @@ impl ElementBuilder { self } + /// Push an attribute onto the element builder. pub fn push_attribute(mut self, name: N, value: V) -> Self { self.attributes.push(( // TODO: make sure name is a valid name, same for prefixes @@ -473,6 +513,7 @@ impl ElementBuilder { self } + /// Push a namespaced attribute onto the element builder. pub fn push_attribute_namespaced( mut self, namespace: impl ToString, @@ -490,17 +531,20 @@ impl ElementBuilder { } // TODO: use references for everything to avoid cloning + /// Push a child element onto the element builder. pub fn push_child(mut self, child: impl IntoElement) -> Self { self.content.push(ContentBuilder::Element(child.builder())); self } // TODO: better way for push_text to work, empty string should be empty element no matter what + /// Push a text value onto the element builder. pub fn push_text(mut self, text: impl ToString) -> Self { self.content.push(ContentBuilder::Text(text.to_string())); self } + /// Optionally push an attribute onto the element builder. pub fn push_attribute_opt(self, name: impl ToString, value: Option) -> Self { if let Some(value) = value { self.push_attribute(name, value) @@ -509,6 +553,7 @@ impl ElementBuilder { } } + /// Optionally push a namespaced attribute onto the element builder. pub fn push_attribute_opt_namespaced( self, namespace: impl ToString, @@ -522,6 +567,7 @@ impl ElementBuilder { } } + /// Optionally push a child onto the element builder. pub fn push_child_opt(self, child: Option) -> Self { if let Some(child) = child { self.push_child(child) @@ -530,6 +576,7 @@ impl ElementBuilder { } } + /// Optionally push a text value onto the element builder. pub fn push_text_opt(self, text: Option) -> Self { if let Some(text) = text { self.push_text(text) @@ -538,11 +585,13 @@ impl ElementBuilder { } } + /// Optionally push a content item onto the element builder. pub fn push_content(mut self, content: ContentBuilder) -> Self { self.content.push(content); self } + /// Optionally push content items onto the element builder. pub fn push_children(self, children: Vec) -> Self { let mut element_builder = self; for child in children { @@ -551,6 +600,7 @@ impl ElementBuilder { element_builder } + /// Build an `Element` from the `ElementBuilder`. pub fn build(&self) -> Result { let mut namespace_declaration_overrides = HashSet::new(); for namespace_declaration in &self.namespace_declaration_overrides { @@ -588,6 +638,7 @@ impl ElementBuilder { } } +/// Trait for conversion from a type into an (`Element`) `Content` item. pub trait IntoContent { fn into_content(&self) -> Content { self.builder().build().unwrap() @@ -605,17 +656,23 @@ where } } +/// Trait for conversion from some `Element` `Content` into another type. pub trait FromContent: Sized { fn from_content(content: Content) -> DeserializeResult; } +/// Builder for `Content`. pub enum ContentBuilder { + /// A child element. Element(ElementBuilder), + /// A text value. Text(String), + /// A comment. Comment(String), } impl ContentBuilder { + /// Build a `Content` item from the builder. pub fn build(&self) -> Result { match self { ContentBuilder::Element(element_builder) => { @@ -627,6 +684,7 @@ impl ContentBuilder { } } +/// Escape a str into an XML escaped string. pub fn escape_str(s: &str) -> String { let mut string = String::new(); for str in s.split_inclusive(|c| c == '<' || c == '&' || c == '>') { diff --git a/src/endable.rs b/src/endable.rs deleted file mode 100644 index 6d842f3..0000000 --- a/src/endable.rs +++ /dev/null @@ -1,37 +0,0 @@ -use crate::Error; - -#[derive(Debug)] -pub struct Endable { - inner: T, - ended: bool, -} - -impl Endable { - pub fn new(inner: T) -> Self { - Self { - inner, - ended: false, - } - } - - pub fn end(&mut self) { - self.ended = true; - } - - pub fn into_inner(self) -> T { - self.inner - } - - #[inline(always)] - pub fn try_as_mut(&mut self) -> Result<&mut T, Error> { - if self.ended { - Err(Error::RootElementEnded) - } else { - Ok(&mut self.inner) - } - } - - pub fn ignore_end(&mut self) -> &mut T { - &mut self.inner - } -} diff --git a/src/error.rs b/src/error.rs index 41c3bfe..26b7766 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,6 +1,5 @@ use std::{ collections::{HashMap, VecDeque}, - fmt, num::ParseIntError, str::Utf8Error, sync::Arc, @@ -15,35 +14,49 @@ use crate::{ Element, }; +/// Error type for the `FromElement` trait. Used when deserialising from an `Element`. #[derive(Error, Debug, Clone)] pub enum DeserializeError { + /// Could not parse string. #[error("could not parse string {0:?} to requested value")] FromStr(String), + /// Unexpected attributes. #[error("unexpected attributes {0:?}")] UnexpectedAttributes(HashMap), + /// Unexpected element content. #[error("unexpected element content: {0:?}")] UnexpectedContent(VecDeque), + /// Missing attribute. #[error("attribute `{0:?}` missing")] MissingAttribute(Name), + /// Incorrect localname encountered. #[error("incorrect localname: expected `{expected:?}`, found `{found:?}`")] IncorrectName { expected: String, found: String }, + /// Incorrect namespace encountered. #[error("incorrect namespace: expected `{expected:?}`, found `{found:?}`")] IncorrectNamespace { expected: String, found: String }, + /// Unqualified namespace when expecting qualified namespace. #[error("unqualified namespace: expected `{expected:?}`")] Unqualified { expected: String }, + /// Element missing expected child. #[error("element missing expected child")] MissingChild, + /// Element missing expected text value. #[error("element missing expected text value")] MissingValue, // not used by crate (yet), but may be used by consumers implementing FromElement + /// Unexpected element. #[error("unexpected element: {0:?}")] UnexpectedElement(Element), + /// Attribute is an empty string. #[error("attribute `{0}` is an empty string")] AttributeEmptyString(String), + /// Empty string. #[error("empty string")] EmptyString, } +/// General error type for functions in the crate. // TODO: add error context (usually the stanza) #[derive(Error, Debug, Clone)] pub enum Error { @@ -82,22 +95,27 @@ pub enum Error { Websocket(#[from] WebsocketError), } +/// Websocket-related errors. #[cfg(target_arch = "wasm32")] #[derive(Error, Debug, Clone)] pub enum WebsocketError { + /// Websocket write error. #[error("write")] Write, + /// Invalid encoding. #[error("invalid encoding")] InvalidEncoding, + /// Can't decode blob. #[error("can't decode blob")] CantDecodeBlob, + /// Unknown data type. #[error("unknown data type")] UnknownDataType, } #[cfg(target_arch = "wasm32")] impl From for Error { - fn from(e: JsValue) -> Self { + fn from(_e: JsValue) -> Self { Self::Websocket(WebsocketError::Write) } } @@ -108,12 +126,16 @@ impl From for Error { } } +/// Character reference decode error. #[derive(Error, Debug, Clone)] pub enum CharRefError { + /// Int parsing. #[error("int parsing: {0}")] ParseInt(#[from] ParseIntError), + /// Integer is not a valid char. #[error("u32 `{0}` does not represent a valid char")] IntegerNotAChar(u32), + /// Character is an invalid XML char. #[error("`{0}` is not a valid xml char")] InvalidXMLChar(char), } diff --git a/src/lib.rs b/src/lib.rs index 8d95d0b..b534d08 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,18 +1,39 @@ +//! # peanuts: An ergonomic (async) xml reader/writer library. +//! +//! Features: +//! +//! - Serialisation +//! - Deserialisation +//! - DOM navigation +//! - Namespacing +//! - Websocket framing + +/// XML prolog declaration types. pub mod declaration; -pub mod element; -mod endable; +mod element; mod error; -pub mod loggable; -pub mod reader; +mod reader; mod writer; -pub mod xml; +// TODO: alternative raw xml API +mod xml; +/// Result type for the crate. pub type Result = std::result::Result; +/// XML namespace URI for the `xml:` namespace prefix. pub const XML_NS: &str = "http://www.w3.org/XML/1998/namespace"; +/// XML namespace URI for the `xmlns:` namespace prefix. pub const XMLNS_NS: &str = "http://www.w3.org/2000/xmlns/"; +pub use element::Content; +pub use element::ContentBuilder; +pub use element::DeserializeResult; pub use element::Element; +pub use element::ElementBuilder; +pub use element::FromContent; +pub use element::FromElement; +pub use element::IntoContent; +pub use element::IntoElement; pub use error::DeserializeError; pub use error::Error; pub use reader::Reader; diff --git a/src/loggable.rs b/src/loggable.rs deleted file mode 100644 index dd69668..0000000 --- a/src/loggable.rs +++ /dev/null @@ -1,67 +0,0 @@ -use std::{fmt::Display, mem, pin::pin, task::Poll}; - -use futures::ready; -use pin_project::pin_project; -pub use tokio::io::AsyncWrite; - -#[pin_project] -#[derive(Debug)] -pub struct Loggable { - log_buffer: Vec, - #[pin] - writer: W, -} - -impl Loggable { - pub fn new(writer: W) -> Self { - Self { - log_buffer: Vec::new(), - writer, - } - } - - pub fn into_inner(self) -> W { - self.writer - } - - pub fn take_log(&mut self) -> Vec { - let log: Vec = mem::replace(&mut self.log_buffer, Vec::new()); - log - } -} - -impl Display for Loggable { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let str = str::from_utf8(&self.log_buffer).unwrap_or("buffer to string conversion failed"); - f.write_str(str) - } -} - -impl AsyncWrite for Loggable { - fn poll_write( - mut self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - buf: &[u8], - ) -> std::task::Poll> { - let this = self.as_mut().project(); - let ready = ready!(this.writer.poll_write(cx, buf)); - self.log_buffer.extend_from_slice(buf); - Poll::Ready(ready) - } - - fn poll_flush( - self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { - let this = self.project(); - Poll::Ready(ready!(this.writer.poll_flush(cx))) - } - - fn poll_shutdown( - self: std::pin::Pin<&mut Self>, - cx: &mut std::task::Context<'_>, - ) -> std::task::Poll> { - let this = self.project(); - Poll::Ready(ready!(this.writer.poll_shutdown(cx))) - } -} diff --git a/src/reader.rs b/src/reader.rs index ea6c804..a403171 100644 --- a/src/reader.rs +++ b/src/reader.rs @@ -8,10 +8,10 @@ use std::{ collections::{HashMap, HashSet, VecDeque}, str, }; -use tokio::io::{AsyncRead, AsyncReadExt}; +use tokio::io::AsyncRead; #[cfg(target_arch = "wasm32")] use tokio::sync::mpsc; -use tracing::{debug, info, trace}; +use tracing::{info, trace}; #[cfg(target_arch = "wasm32")] use wasm_bindgen::{closure::Closure, JsCast}; #[cfg(target_arch = "wasm32")] @@ -29,7 +29,7 @@ use crate::{ static MAX_STANZA_SIZE: usize = 65536; -/// Streaming reader that tracks depth and corresponding available namespaces. +/// Reader that tracks depth and corresponding declared/available namespaces. #[derive(Debug)] pub struct Reader { inner: R, @@ -134,7 +134,6 @@ impl WebSocketOnMessageRead { #[cfg(target_arch = "wasm32")] impl Readable for WebSocketOnMessageRead { async fn read_buf(&mut self, buffer: &mut Buffer) -> Result { - debug!("reading buf"); let msg = self.queue.recv().await; let msg = match msg { Some(msg) => msg, diff --git a/src/writer.rs b/src/writer.rs index 40a935b..c30f03e 100644 --- a/src/writer.rs +++ b/src/writer.rs @@ -9,14 +9,17 @@ use web_sys::WebSocket; use crate::{ declaration::{Declaration, VersionInfo}, element::{escape_str, Content, Element, IntoContent, IntoElement, Name, NamespaceDeclaration}, - endable::Endable, error::Error, - loggable::Loggable, xml::{self, composers::Composer, parsers_complete::Parser}, Result, XMLNS_NS, XML_NS, }; +use endable::Endable; +use loggable::Loggable; -// pub struct Writer { +mod endable; +mod loggable; + +/// Writer that tracks depth and corresponding declared/available namespaces. #[derive(Debug)] pub struct Writer { inner: Endable, @@ -26,6 +29,7 @@ pub struct Writer { } impl Writer> { + /// Create a new `Writer` which is constrained to a single root element. pub fn new(writer: W) -> Self { let mut default_declarations = HashSet::new(); default_declarations.insert(NamespaceDeclaration { @@ -44,6 +48,7 @@ impl Writer> { } } + /// Create a new `Writer` which is not constrained to a single root element. pub fn new_unendable(writer: W) -> Self { let mut default_declarations = HashSet::new(); default_declarations.insert(NamespaceDeclaration { @@ -62,6 +67,7 @@ impl Writer> { } } + /// Extract the inner type from the `Writer`. pub fn into_inner(self) -> W { self.inner.into_inner().into_inner() } @@ -69,6 +75,7 @@ impl Writer> { #[cfg(target_arch = "wasm32")] impl Writer { + /// Create a new `Writer` which is constrained to a single root element. pub fn new(websocket: WebSocket) -> Self { let mut default_declarations = HashSet::new(); default_declarations.insert(NamespaceDeclaration { @@ -87,10 +94,12 @@ impl Writer { } } + /// Extract the inner `WebSocket` from the `Writer`. pub fn into_inner(self) -> WebSocket { self.inner.into_inner() } + /// Create a new `Writer` which is not constrained to a single root element. pub fn new_unendable(websocket: WebSocket) -> Self { let mut default_declarations = HashSet::new(); default_declarations.insert(NamespaceDeclaration { @@ -109,6 +118,7 @@ impl Writer { } } + /// Write an XML declaration with the provided `VersionInfo`. pub async fn write_declaration(&mut self, version: VersionInfo) -> Result<()> { let declaration = Declaration::version(version); let version_info; @@ -132,6 +142,7 @@ impl Writer { Ok(()) } + /// Write a full element corresponding with the item implementing `IntoElement` (start tag + content + end tag). pub async fn write_full(&mut self, into_element: &impl IntoElement) -> Result<()> { let element = into_element.into_element(); let mut frame = String::new(); @@ -141,6 +152,7 @@ impl Writer { Ok(()) } + /// Write the start tag of an item that implements `IntoElement`. Navigates up the document. pub async fn write_start(&mut self, into_element: &impl IntoElement) -> Result<()> { let element = into_element.into_element(); let mut frame = String::new(); @@ -150,6 +162,7 @@ impl Writer { Ok(()) } + /// Write all the inner content (everything within the start and end tag of an xml element) of an item that implements `IntoElement`. In the case of an empty element, write nothing. pub async fn write_all_content(&mut self, into_element: &impl IntoElement) -> Result<()> { let mut frame = String::new(); for content in &into_element.get_content() { @@ -160,6 +173,7 @@ impl Writer { Ok(()) } + /// Write an item that implements `IntoContent`. Could be an element, some text, a comment, etc. Anything that could be included in an element body. pub async fn write(&mut self, into_content: &impl IntoContent) -> Result<()> { let content = into_content.into_content(); let mut frame = String::new(); @@ -169,7 +183,7 @@ impl Writer { Ok(()) } - // pub async fn write_end(&mut self) + /// Navigate down the document structure and write the end tag for the current element opened in the document context. pub async fn write_end(&mut self) -> Result<()> { let mut frame = String::new(); self.write_end_tag_to_frame(&mut frame)?; @@ -178,7 +192,7 @@ impl Writer { Ok(()) } - pub fn write_element_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> { + fn write_element_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> { if element.content.is_empty() { self.write_empty_to_frame(element, frame)?; } else { @@ -191,8 +205,8 @@ impl Writer { Ok(()) } - pub fn write_empty_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> { - let writer = if self.unendable { + fn write_empty_to_frame(&mut self, element: &Element, frame: &mut String) -> Result<()> { + let _writer = if self.unendable { self.inner.ignore_end() } else { self.inner.try_as_mut()? @@ -306,12 +320,12 @@ impl Writer { Ok(()) } - pub fn write_element_start_to_frame( + fn write_element_start_to_frame( &mut self, element: &Element, frame: &mut String, ) -> Result<()> { - let writer = if self.unendable { + let _writer = if self.unendable { self.inner.ignore_end() } else { self.inner.try_as_mut()? @@ -424,11 +438,11 @@ impl Writer { Ok(()) } - pub fn write_content_to_frame(&mut self, content: &Content, frame: &mut String) -> Result<()> { + fn write_content_to_frame(&mut self, content: &Content, frame: &mut String) -> Result<()> { match content { Content::Element(element) => self.write_element_to_frame(element, frame)?, Content::Text(text) => { - let writer = if self.unendable { + let _writer = if self.unendable { self.inner.ignore_end() } else { self.inner.try_as_mut()? @@ -442,8 +456,8 @@ impl Writer { Ok(()) } - pub fn write_end_tag_to_frame(&mut self, frame: &mut String) -> Result<()> { - let writer = if self.unendable { + fn write_end_tag_to_frame(&mut self, frame: &mut String) -> Result<()> { + let _writer = if self.unendable { self.inner.ignore_end() } else { self.inner.try_as_mut()? @@ -491,8 +505,8 @@ impl Writer { } } -#[cfg(not(target_arch = "wasm32"))] impl Writer> { + /// Write an XML declaration with the provided `VersionInfo`. pub async fn write_declaration(&mut self, version: VersionInfo) -> Result<()> { let writer = if self.unendable { self.inner.ignore_end() @@ -516,6 +530,7 @@ impl Writer> { Ok(()) } + /// Write a full element corresponding with the item implementing `IntoElement` (start tag + content + end tag). pub async fn write_full(&mut self, into_element: &impl IntoElement) -> Result<()> { let element = into_element.into_element(); self.write_element(&element).await?; @@ -525,6 +540,7 @@ impl Writer> { Ok(()) } + /// Write the start tag of an item that implements `IntoElement`. Navigates up the document. pub async fn write_start(&mut self, into_element: &impl IntoElement) -> Result<()> { let element = into_element.into_element(); self.write_element_start(&element).await?; @@ -534,6 +550,7 @@ impl Writer> { Ok(()) } + /// Write all the inner content (everything within the start and end tag of an xml element) of an item that implements `IntoElement`. In the case of an empty element, write nothing. pub async fn write_all_content(&mut self, into_element: &impl IntoElement) -> Result<()> { for content in &into_element.get_content() { self.write_content(content).await?; @@ -544,6 +561,7 @@ impl Writer> { Ok(()) } + /// Write an item that implements `IntoContent`. Could be an element, some text, a comment, etc. Anything that could be included in an element body. pub async fn write(&mut self, into_content: &impl IntoContent) -> Result<()> { let content = into_content.into_content(); self.write_content(&content).await?; @@ -553,7 +571,7 @@ impl Writer> { Ok(()) } - // pub async fn write_end(&mut self) + /// Navigate down the document structure and write the end tag for the current element opened in the document context. pub async fn write_end(&mut self) -> Result<()> { self.write_end_tag().await?; let bytes = &self.inner.ignore_end().take_log(); @@ -563,6 +581,7 @@ impl Writer> { } #[async_recursion] + /// Write an `Element`. pub async fn write_element(&mut self, element: &Element) -> Result<()> { if element.content.is_empty() { self.write_empty(element).await?; @@ -576,6 +595,7 @@ impl Writer> { Ok(()) } + /// Write an empty element tag from an `Element` (ignoring any content). pub async fn write_empty(&mut self, element: &Element) -> Result<()> { let writer = if self.unendable { self.inner.ignore_end() @@ -690,6 +710,7 @@ impl Writer> { Ok(()) } + /// Write an element start tag from an `Element`, navigating up in document depth. pub async fn write_element_start(&mut self, element: &Element) -> Result<()> { let writer = if self.unendable { self.inner.ignore_end() @@ -803,6 +824,7 @@ impl Writer> { Ok(()) } + /// Write some `Content`. pub async fn write_content(&mut self, content: &Content) -> Result<()> { match content { Content::Element(element) => self.write_element(element).await?, @@ -821,6 +843,7 @@ impl Writer> { Ok(()) } + /// Write an end tag (depending on the current document context), moving back down in the document. pub async fn write_end_tag(&mut self) -> Result<()> { let writer = if self.unendable { self.inner.ignore_end() diff --git a/src/writer/endable.rs b/src/writer/endable.rs new file mode 100644 index 0000000..6d842f3 --- /dev/null +++ b/src/writer/endable.rs @@ -0,0 +1,37 @@ +use crate::Error; + +#[derive(Debug)] +pub struct Endable { + inner: T, + ended: bool, +} + +impl Endable { + pub fn new(inner: T) -> Self { + Self { + inner, + ended: false, + } + } + + pub fn end(&mut self) { + self.ended = true; + } + + pub fn into_inner(self) -> T { + self.inner + } + + #[inline(always)] + pub fn try_as_mut(&mut self) -> Result<&mut T, Error> { + if self.ended { + Err(Error::RootElementEnded) + } else { + Ok(&mut self.inner) + } + } + + pub fn ignore_end(&mut self) -> &mut T { + &mut self.inner + } +} diff --git a/src/writer/loggable.rs b/src/writer/loggable.rs new file mode 100644 index 0000000..dd69668 --- /dev/null +++ b/src/writer/loggable.rs @@ -0,0 +1,67 @@ +use std::{fmt::Display, mem, pin::pin, task::Poll}; + +use futures::ready; +use pin_project::pin_project; +pub use tokio::io::AsyncWrite; + +#[pin_project] +#[derive(Debug)] +pub struct Loggable { + log_buffer: Vec, + #[pin] + writer: W, +} + +impl Loggable { + pub fn new(writer: W) -> Self { + Self { + log_buffer: Vec::new(), + writer, + } + } + + pub fn into_inner(self) -> W { + self.writer + } + + pub fn take_log(&mut self) -> Vec { + let log: Vec = mem::replace(&mut self.log_buffer, Vec::new()); + log + } +} + +impl Display for Loggable { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let str = str::from_utf8(&self.log_buffer).unwrap_or("buffer to string conversion failed"); + f.write_str(str) + } +} + +impl AsyncWrite for Loggable { + fn poll_write( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &[u8], + ) -> std::task::Poll> { + let this = self.as_mut().project(); + let ready = ready!(this.writer.poll_write(cx, buf)); + self.log_buffer.extend_from_slice(buf); + Poll::Ready(ready) + } + + fn poll_flush( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + let this = self.project(); + Poll::Ready(ready!(this.writer.poll_flush(cx))) + } + + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + let this = self.project(); + Poll::Ready(ready!(this.writer.poll_shutdown(cx))) + } +} -- cgit