aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
authorLibravatar cel 🌸 <cel@bunny.garden>2025-05-30 13:29:02 +0100
committerLibravatar cel 🌸 <cel@bunny.garden>2025-05-30 13:29:02 +0100
commit6d1f28eb79c6c70b058fcbae5047dbd744764149 (patch)
tree0dd308a59df464d7c4156a459b56c205c9deb81f /src
parent826a17e34c167b53bd63544c5825b689a3a8fca7 (diff)
downloadpeanuts-6d1f28eb79c6c70b058fcbae5047dbd744764149.tar.gz
peanuts-6d1f28eb79c6c70b058fcbae5047dbd744764149.tar.bz2
peanuts-6d1f28eb79c6c70b058fcbae5047dbd744764149.zip
doc: everything
Diffstat (limited to 'src')
-rw-r--r--src/declaration.rs3
-rw-r--r--src/element.rs66
-rw-r--r--src/error.rs26
-rw-r--r--src/lib.rs31
-rw-r--r--src/reader.rs7
-rw-r--r--src/writer.rs53
-rw-r--r--src/writer/endable.rs (renamed from src/endable.rs)0
-rw-r--r--src/writer/loggable.rs (renamed from src/loggable.rs)0
8 files changed, 156 insertions, 30 deletions
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<String>,
pub sd_decl: Option<bool>,
}
+/// 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<T> = std::result::Result<T, DeserializeError>;
+/// Trait for conversion from an `Element` into another type, for deserialisation from a `Reader`.
pub trait FromElement: Sized {
fn from_element(element: Element) -> DeserializeResult<Self>;
}
+/// 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<NamespaceDeclaration>,
+ pub(crate) namespace_declaration_overrides: HashSet<NamespaceDeclaration>,
// 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<Name, String>,
+ pub(crate) attributes: HashMap<Name, String>,
// TODO: make a hashmap maybe? to be able to address parts of the content individually
- pub content: VecDeque<Content>,
+ pub(crate) content: VecDeque<Content>,
}
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<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<Option<V>> {
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<V: FromStr>(
&mut self,
att_name: &str,
@@ -144,6 +158,7 @@ impl Element {
}
}
+ /// Extract an attribute from the element.
pub fn attribute<V: FromStr>(&mut self, att_name: &str) -> DeserializeResult<V> {
let name = Name {
namespace: None,
@@ -158,6 +173,7 @@ impl Element {
}
}
+ /// Extract a namespaced attribute from the element.
pub fn attribute_namespaced<V: FromStr>(
&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<Self> {
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<T: FromElement>(&mut self) -> DeserializeResult<T> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(element) => <T as FromElement>::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<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
if let Some(position) = self.content.iter().position(|content| match content {
Content::Element(element) => <T as FromElement>::from_element(element.clone()).is_ok(),
@@ -222,6 +243,7 @@ impl Element {
}
}
+ /// Extract several children of type `T` from the element.
pub fn children<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
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<V: FromStr>(&mut self) -> DeserializeResult<V> {
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<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
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<T: FromElement>(&mut self) -> DeserializeResult<T> {
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<T: FromElement>(&mut self) -> DeserializeResult<Option<T>> {
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<T: FromElement>(&mut self) -> DeserializeResult<Vec<T>> {
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<V: FromStr>(&mut self) -> DeserializeResult<V> {
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<V: FromStr>(&mut self) -> DeserializeResult<Option<V>> {
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<Self> {
if self
.content
@@ -423,11 +458,13 @@ impl Element {
}
}
+ /// Create a new `ElementBuilder`.
pub fn builder(name: impl ToString, namespace: Option<impl ToString>) -> ElementBuilder {
ElementBuilder::new(name, namespace)
}
}
+/// Builder for the `Element` type.
pub struct ElementBuilder {
name: Name,
namespace_declaration_overrides: Vec<NamespaceDeclaration>,
@@ -436,6 +473,7 @@ pub struct ElementBuilder {
}
impl ElementBuilder {
+ /// Create a new `ElementBuilder`.
pub fn new(name: impl ToString, namespace: Option<impl ToString>) -> 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<impl ToString>,
@@ -461,6 +500,7 @@ impl ElementBuilder {
self
}
+ /// Push an attribute onto the element builder.
pub fn push_attribute<N: ToString, V: ToString>(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<impl ToString>) -> 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<impl IntoElement>) -> 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<impl ToString>) -> 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<impl IntoContent>) -> 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<Element> {
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<Self>;
}
+/// 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<Content> {
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/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<Name, String>),
+ /// Unexpected element content.
#[error("unexpected element content: {0:?}")]
UnexpectedContent(VecDeque<Content>),
+ /// 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<JsValue> for Error {
- fn from(e: JsValue) -> Self {
+ fn from(_e: JsValue) -> Self {
Self::Websocket(WebsocketError::Write)
}
}
@@ -108,12 +126,16 @@ impl From<std::io::Error> 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<T> = std::result::Result<T, error::Error>;
+/// 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/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<R> {
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<usize> {
- 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<W, C = Composer> {
+mod endable;
+mod loggable;
+
+/// Writer that tracks depth and corresponding declared/available namespaces.
#[derive(Debug)]
pub struct Writer<W> {
inner: Endable<W>,
@@ -26,6 +29,7 @@ pub struct Writer<W> {
}
impl<W> Writer<Loggable<W>> {
+ /// 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<W> Writer<Loggable<W>> {
}
}
+ /// 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<W> Writer<Loggable<W>> {
}
}
+ /// Extract the inner type from the `Writer`.
pub fn into_inner(self) -> W {
self.inner.into_inner().into_inner()
}
@@ -69,6 +75,7 @@ impl<W> Writer<Loggable<W>> {
#[cfg(target_arch = "wasm32")]
impl Writer<WebSocket> {
+ /// 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<WebSocket> {
}
}
+ /// 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<WebSocket> {
}
}
+ /// 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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
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<WebSocket> {
}
}
-#[cfg(not(target_arch = "wasm32"))]
impl<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
+ /// 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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
}
#[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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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<W: AsyncWrite + Unpin + Send> Writer<Loggable<W>> {
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/endable.rs b/src/writer/endable.rs
index 6d842f3..6d842f3 100644
--- a/src/endable.rs
+++ b/src/writer/endable.rs
diff --git a/src/loggable.rs b/src/writer/loggable.rs
index dd69668..dd69668 100644
--- a/src/loggable.rs
+++ b/src/writer/loggable.rs