1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use std::cell::RefCell;
use std::fmt;
use std::ops::Deref;
use tree::{Node, NodeRef, ElementData, Doctype, DocumentData};
impl NodeRef {
#[inline]
pub fn into_element_ref(self) -> Option<NodeDataRef<ElementData>> {
NodeDataRef::new_opt(self, Node::as_element)
}
#[inline]
pub fn into_text_ref(self) -> Option<NodeDataRef<RefCell<String>>> {
NodeDataRef::new_opt(self, Node::as_text)
}
#[inline]
pub fn into_comment_ref(self) -> Option<NodeDataRef<RefCell<String>>> {
NodeDataRef::new_opt(self, Node::as_comment)
}
#[inline]
pub fn into_doctype_ref(self) -> Option<NodeDataRef<Doctype>> {
NodeDataRef::new_opt(self, Node::as_doctype)
}
#[inline]
pub fn into_document_ref(self) -> Option<NodeDataRef<DocumentData>> {
NodeDataRef::new_opt(self, Node::as_document)
}
}
pub struct NodeDataRef<T> {
_keep_alive: NodeRef,
_reference: *const T
}
impl<T> NodeDataRef<T> {
#[inline]
pub fn new<F>(rc: NodeRef, f: F) -> NodeDataRef<T> where F: FnOnce(&Node) -> &T {
NodeDataRef {
_reference: f(&*rc),
_keep_alive: rc,
}
}
#[inline]
pub fn new_opt<F>(rc: NodeRef, f: F) -> Option<NodeDataRef<T>>
where F: FnOnce(&Node) -> Option<&T> {
f(&*rc).map(|r| r as *const T).map(move |r| NodeDataRef {
_reference: r,
_keep_alive: rc,
})
}
#[inline]
pub fn as_node(&self) -> &NodeRef {
&self._keep_alive
}
}
impl<T> Deref for NodeDataRef<T> {
type Target = T;
#[inline] fn deref(&self) -> &T { unsafe { &*self._reference } }
}
impl<T> Clone for NodeDataRef<T> {
#[inline]
fn clone(&self) -> Self {
NodeDataRef {
_keep_alive: self._keep_alive.clone(),
_reference: self._reference,
}
}
}
impl<T: fmt::Debug> fmt::Debug for NodeDataRef<T> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
fmt::Debug::fmt(&**self, f)
}
}
impl NodeDataRef<ElementData> {
pub fn text_contents(&self) -> String {
self.as_node().text_contents()
}
}