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
use std::{
cell::{Ref, RefCell},
rc::Rc,
};
use crate::{
save::write_escaped_char_data,
tree::{
Document, NodeType,
node::{Node, NodeCore, NodeSpec},
},
};
pub struct TextSpec {
data: String,
}
impl NodeSpec for TextSpec {
fn node_type(&self) -> NodeType {
NodeType::Text
}
fn first_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>> {
None
}
fn last_child(&self) -> Option<Rc<RefCell<NodeCore<dyn NodeSpec>>>> {
None
}
}
pub type Text = Node<TextSpec>;
impl Text {
pub(crate) fn new(data: String, owner_document: Document) -> Self {
Node::create_node(TextSpec { data }, owner_document)
}
/// Return the character data of this text node.
///
/// The returned data is literal data that does not contain escapes or references.
pub fn data(&self) -> Ref<'_, str> {
Ref::map(self.core.borrow(), |core| core.spec.data.as_str())
}
/// Add `ch` to the end of the character data.
pub fn push(&mut self, ch: char) {
self.core.borrow_mut().spec.data.push(ch);
}
/// Add `string` to the end of the character data.
///
/// `string` is treated as literal data. \
/// For example, `"<"` is treated as the literal character data `"<"`, not as `"<"`.
pub fn push_str(&mut self, string: &str) {
self.core.borrow_mut().spec.data.push_str(string);
}
/// Create new node and copy internal data to the new node.
///
/// While [`Clone::clone`] merely copies the pointer, this method copies the internal data
/// to new memory, creating a completely different node. Comparing the source node and
/// the new node using [`Node::is_same_node`] will always return `false`.
///
/// # Example
/// ```rust
/// use anyxml::tree::Document;
///
/// let document = Document::new();
/// let text1 = document.create_text("text node");
/// let text2 = text1.deep_copy();
/// assert!(text1.is_same_node(text1.clone()));
/// assert_eq!(*text1.data(), *text2.data());
/// assert!(!text1.is_same_node(text2));
/// ```
pub fn deep_copy(&self) -> Self {
Node::create_node(
TextSpec {
data: self.data().to_owned(),
},
self.owner_document(),
)
}
}
impl std::fmt::Display for Text {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write_escaped_char_data(f, &self.data())
}
}