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
use derive_more::Into;
/// The HTML text node. This is used inside tags eg <p>Text</p>
#[derive(Into, Clone, PartialEq, Eq, Debug)]
pub struct Text(String);

impl Text {
    /// Creates a text node. Note: will escape html markup eg <,>,&
    pub fn create<S>(text: S) -> Text
    where
        S: Into<String>,
    {
        // I suspect there might be a more complete ruleset here
        let text = text.into();
        let gt = ">";
        let lt = "<";
        let amp = "&";
        let gt_escaped = "&gt;";
        let lt_escaped = "&lt;";
        let amp_escaped = "&amp;";
        let text = text
            .replace(amp, amp_escaped)
            .replace(gt, gt_escaped)
            .replace(lt, lt_escaped);
        Text(text)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn unescaped() {
        let input = Text::create("Hello");
        let expected = Text("Hello".to_string());
        assert_eq!(input, expected);
    }

    #[test]
    fn escaped_greater_than() {
        let input = Text::create(">attempt");
        let expected = Text("&gt;attempt".to_string());
        assert_eq!(input, expected);
    }

    #[test]
    fn escaped_less_than() {
        let input = Text::create("<attempt");
        let expected = Text("&lt;attempt".to_string());
        assert_eq!(input, expected);
    }

    #[test]
    fn escaped_ampersand() {
        let input = Text::create("&attempt");
        let expected = Text("&amp;attempt".to_string());
        assert_eq!(input, expected);
    }
}