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 children_vec(mut self, children: Vec<Node>) -> Self {
50        self.content = Some(NodeContent::Nodes(children));
51        self
52    }
53
54    pub fn bytes(mut self, bytes: impl Into<Vec<u8>>) -> Self {
55        self.content = Some(NodeContent::Bytes(bytes.into()));
56        self
57    }
58
59    pub fn string_content(mut self, s: impl Into<crate::CompactString>) -> Self {
60        self.content = Some(NodeContent::String(s.into()));
61        self
62    }
63
64    pub fn build(self) -> Node {
65        Node {
66            tag: self.tag,
67            attrs: self.attrs,
68            content: self.content,
69        }
70    }
71
72    pub fn apply_content(mut self, content: Option<NodeContent>) -> Self {
73        self.content = content;
74        self
75    }
76}