Skip to main content

wacore_binary/
builder.rs

1use std::borrow::Cow;
2
3use crate::node::{Attrs, Node, NodeContent, NodeValue};
4
5#[derive(Debug, Default)]
6pub struct NodeBuilder {
7    tag: Cow<'static, str>,
8    attrs: Attrs,
9    content: Option<NodeContent>,
10}
11
12impl NodeBuilder {
13    pub fn new(tag: &'static str) -> Self {
14        Self {
15            tag: Cow::Borrowed(tag),
16            ..Default::default()
17        }
18    }
19
20    /// For dynamic tags (rare).
21    pub fn new_dynamic(tag: String) -> Self {
22        Self {
23            tag: Cow::Owned(tag),
24            ..Default::default()
25        }
26    }
27
28    pub fn attr(mut self, key: &'static str, value: impl Into<NodeValue>) -> Self {
29        self.attrs.insert(Cow::Borrowed(key), value.into());
30        self
31    }
32
33    pub fn attrs<I, V>(mut self, attrs: I) -> Self
34    where
35        I: IntoIterator<Item = (&'static str, V)>,
36        V: Into<NodeValue>,
37    {
38        for (key, value) in attrs.into_iter() {
39            self.attrs.insert(Cow::Borrowed(key), value.into());
40        }
41        self
42    }
43
44    pub fn children(mut self, children: impl IntoIterator<Item = Node>) -> Self {
45        self.content = Some(NodeContent::Nodes(children.into_iter().collect()));
46        self
47    }
48
49    pub fn bytes(mut self, bytes: impl Into<Vec<u8>>) -> Self {
50        self.content = Some(NodeContent::Bytes(bytes.into()));
51        self
52    }
53
54    pub fn string_content(mut self, s: impl Into<String>) -> Self {
55        self.content = Some(NodeContent::String(s.into()));
56        self
57    }
58
59    pub fn build(self) -> Node {
60        Node {
61            tag: self.tag,
62            attrs: self.attrs,
63            content: self.content,
64        }
65    }
66
67    pub fn apply_content(mut self, content: Option<NodeContent>) -> Self {
68        self.content = content;
69        self
70    }
71}