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
use crate::{
    toolkit::{context::Context, deserializer::Deserializer},
    toolkit::{matcher::Matcher, node::Node},
};

/// Representation of an Italic text
#[derive(Debug, PartialEq)]
pub struct Italic {
    text: String,
}

impl Italic {
    pub fn new<S: Into<String>>(text: S) -> Self {
        Italic { text: text.into() }
    }
}

impl Node for Italic {
    fn serialize(&self) -> String {
        format!("_{}_", self.text)
    }
    fn len(&self) -> usize {
        self.text.len() + 2
    }
}

impl Deserializer for Italic {
    fn deserialize_with_context(input: &str, _: Option<Context>) -> Option<Self> {
        let mut matcher = Matcher::new(input);
        if let Some(italic) = matcher.get_match("_", "_", false) {
            return Some(Italic::new(italic.body));
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::Italic;
    use crate::toolkit::{deserializer::Deserializer, node::Node};
    use pretty_assertions::assert_eq;

    #[test]
    fn happy_path() {
        let i = Italic::new("italic");
        assert_eq!(i.text, "italic".to_string());
    }

    #[test]
    fn to_string() {
        let i = Italic::new("italic").serialize();
        assert_eq!(i, "_italic_".to_string());
    }

    #[test]
    fn from_string() {
        assert_eq!(Italic::deserialize("_italic_"), Some(Italic::new("italic")));
        assert_eq!(
            Italic::deserialize("_italic_not"),
            Some(Italic::new("italic"))
        );
        assert_eq!(
            Italic::deserialize("_it alic_not"),
            Some(Italic::new("it alic"))
        );
        assert_eq!(Italic::deserialize("not italic_not"), None);
        assert_eq!(Italic::deserialize("*italic not"), None);
        assert_eq!(
            Italic::deserialize("_ita\nlic_"),
            Some(Italic::new("ita\nlic"))
        );
    }

    #[test]
    fn len() {
        assert_eq!(Italic::new("i").len(), 3);
    }
}