| 1 | use std::collections::hash_map::DefaultHasher; |
| 2 | use std::fmt; |
| 3 | use std::hash::Hash; |
| 4 | |
| 5 | use crate::node::Node; |
| 6 | |
| 7 | /// A text node. |
| 8 | #[derive(Clone, Debug)] |
| 9 | pub struct Text { |
| 10 | content: String, |
| 11 | } |
| 12 | |
| 13 | impl Text { |
| 14 | /// Create a node. |
| 15 | #[inline] |
| 16 | pub fn new<T>(content: T) -> Self |
| 17 | where |
| 18 | T: Into<String>, |
| 19 | { |
| 20 | Text { |
| 21 | content: content.into(), |
| 22 | } |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | impl fmt::Display for Text { |
| 27 | #[inline] |
| 28 | fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { |
| 29 | escape(&self.content).fmt(formatter) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl Node for Text { |
| 34 | #[inline] |
| 35 | fn get_name(&self) -> &str { |
| 36 | "text" |
| 37 | } |
| 38 | |
| 39 | #[inline] |
| 40 | fn is_bare(&self) -> bool { |
| 41 | true |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | impl super::NodeDefaultHash for Text { |
| 46 | #[inline] |
| 47 | fn default_hash(&self, state: &mut DefaultHasher) { |
| 48 | self.content.hash(state); |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | pub(crate) fn escape(value: &str) -> String { |
| 53 | value |
| 54 | .replace('&', "&") |
| 55 | .replace('<', "<") |
| 56 | .replace('>', ">") |
| 57 | } |