on 55618b1 help sign in
dodrio/src/node.rs
87 lines 2.2 kB history raw
1use bumpalo::{Bump, BumpAllocSafe};
3/// A node is either a text node or an element.
4#[derive(Debug, Clone)]
5pub enum Node<'a> {
6 /// A text node.
7 Text(TextNode<'a>),
9 /// An element potentially with attributes and children.
10 Element(ElementNode<'a>),
13/// Text nodes are just a string of text. They cannot have attributes or
14/// children.
15#[derive(Debug, Clone)]
16pub struct TextNode<'a> {
17 pub(crate) text: &'a str,
20/// Elements have a tag name, zero or more attributes, and zero or more
21/// children.
22#[derive(Debug, Clone)]
23pub struct ElementNode<'a> {
24 pub(crate) tag_name: &'a str,
25 pub(crate) attributes: &'a [Attribute<'a>],
26 pub(crate) children: &'a [Node<'a>],
29#[derive(Clone, Debug)]
30pub struct Attribute<'a> {
31 pub name: &'a str,
32 pub value: &'a str,
35impl<'a> Node<'a> {
36 /// Is this node a text node?
37 pub fn is_text(&self) -> bool {
38 match self {
39 Node::Text(_) => true,
40 _ => false,
41 }
42 }
44 /// Is this node an element?
45 pub fn is_element(&self) -> bool {
46 match self {
47 Node::Element { .. } => true,
48 _ => false,
49 }
50 }
53impl<'a> BumpAllocSafe for Node<'a> {}
54impl<'a> BumpAllocSafe for Attribute<'a> {}
56impl<'a> Node<'a> {
57 /// Construct a new text node with the given text.
58 #[inline]
59 pub fn text(text: &'a str) -> Node<'a> {
60 Node::Text(TextNode { text })
61 }
63 /// Construct a new element node with the given tag name and children.
64 #[inline]
65 pub fn element<Attributes, Children>(
66 bump: &'a Bump,
67 tag_name: &'a str,
68 attributes: Attributes,
69 children: Children,
70 ) -> Node<'a>
71 where
72 Attributes: 'a + BumpAllocSafe + AsRef<[Attribute<'a>]>,
73 Children: 'a + BumpAllocSafe + AsRef<[Node<'a>]>,
74 {
75 let children: &'a Children = bump.alloc(children);
76 let children: &'a [Node<'a>] = children.as_ref();
78 let attributes: &'a Attributes = bump.alloc(attributes);
79 let attributes: &'a [Attribute<'a>] = attributes.as_ref();
81 Node::Element(ElementNode {
82 tag_name,
83 attributes,
84 children,
85 })
86 }