Add conversion traits to Builder #12

Merged
cadey merged 3 commits from :to-string into main 2020-12-06 01:13:25 +00:00
1 changed files with 15 additions and 1 deletions
Showing only changes of commit 2f3dd72d90 - Show all commits

View File

@ -61,7 +61,7 @@ impl ToString for Builder {
fn to_string(&self) -> String { fn to_string(&self) -> String {
let len: usize = self.nodes.iter().map(Node::estimate_len).sum(); // sum up node lengths let len: usize = self.nodes.iter().map(Node::estimate_len).sum(); // sum up node lengths
let mut bytes = Vec::with_capacity(len + self.nodes.len()); // add in inter-node newlines let mut bytes = Vec::with_capacity(len + self.nodes.len()); // add in inter-node newlines
render(&self.nodes, &mut bytes).unwrap(); // Writing to a string shouldn't produce errors render(self, &mut bytes).unwrap(); // Writing to a string shouldn't produce errors
unsafe { unsafe {
// This is safe because bytes is composed of Strings. We could have this as // This is safe because bytes is composed of Strings. We could have this as
@ -73,6 +73,20 @@ impl ToString for Builder {
} }
} }
impl AsRef<[Node]> for Builder {
/// Get a reference to the internal node list of this builder
fn as_ref(&self) -> &[Node] {
self.nodes.as_ref()
}
}
impl AsMut<[Node]> for Builder {
/// Get a mutable reference to the internal node list of this builder
fn as_mut(&mut self) -> &mut [Node] {
self.nodes.as_mut()
}
}
/// Render a set of nodes as a document to a writer. /// Render a set of nodes as a document to a writer.
pub fn render(nodes: impl AsRef<[Node]>, out: &mut impl Write) -> io::Result<()> { pub fn render(nodes: impl AsRef<[Node]>, out: &mut impl Write) -> io::Result<()> {
use Node::*; use Node::*;