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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
/// A `DocumentTemplate` mimics a [mustache](https://mustache.github.io/)
/// template. A template consists of a list of `Partial`s.
#[derive(Debug, PartialEq)]
pub struct DocumentTemplate {
    pub partials: Vec<Partial>,
}

impl DocumentTemplate {
    pub fn new() -> Self {
        Self {
            partials: Vec::new(),
        }
    }

    pub fn with_partials(partials: &[Partial]) -> Self {
        Self {
            partials: partials.to_vec(),
        }
    }

    pub fn add_partial(&mut self, partial: &Partial) {
        self.partials.push(partial.clone());
    }
}

pub type Identifier = String;

/// Each `Partial` is either a UTF-8 `StringLiteral`, or a `Tag`.
#[derive(Debug, PartialEq, Clone)]
pub enum Partial {
    StringLiteral(String),
    Tag(Identifier),
}

/// A `FilledDocument` is generated from a `DocumentTemplate` with the required
/// `Tag`s filled in.
#[derive(Debug, PartialEq)]
pub struct FilledDocument(String);

impl FilledDocument {
    pub fn document<'a>(&'a self) -> &'a str {
        &self.0
    }
}

/// A `TagPair` is an association between the tag name `key` and the `value`
/// that should be used to fill its place.
#[derive(Debug, PartialEq)]
pub struct TagPair {
    pub key: String,
    pub value: String,
}

/// Cause of error when trying to fill a `DocumentTemplate`.
#[derive(Debug, PartialEq)]
pub enum TemplateError {
    MissingRequiredTagValue(Identifier),
    NonExhaustiveTags(Vec<Identifier>),
}

impl DocumentTemplate {
    pub fn saturate(
        &self,
        tag_pairs: &[TagPair],
    ) -> Result<FilledDocument, TemplateError> {
        let mut content = String::new();

        // TODO: replace this `O(n^2)` loop with a `O(1)` `HashMap`. Currently
        // this requires iterating over `self.partials` in the outer loop and
        // iterating over `tag_pairs` in the inner loop in the worst case
        // scenario.
        for partial in &self.partials[..] {
            match partial {
                Partial::StringLiteral(s) => content.push_str(s),
                Partial::Tag(id) => {
                    let tag_value = saturate_or_error(tag_pairs, id)?;
                    content.push_str(tag_value);
                }
            }
        }

        Ok(FilledDocument(content))
    }
}

fn saturate_or_error<'a>(
    tag_pairs: &'a [TagPair],
    tag_key: &'a str,
) -> Result<&'a str, TemplateError> {
    match tag_pairs.iter().find(|&t| &t.key == tag_key) {
        Some(TagPair { value, .. }) => Ok(value),
        None => {
            Err(TemplateError::MissingRequiredTagValue(tag_key.to_string()))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_no_tags() -> Result<(), String> {
        let template = DocumentTemplate::new();
        let saturated = template.saturate(&[]);
        assert!(saturated.is_ok());
        Ok(())
    }

    #[test]
    fn test_one_tag() -> Result<(), String> {
        let template = DocumentTemplate::with_partials(&vec![
            Partial::StringLiteral("Hello ".to_string()),
            Partial::Tag("name".to_string()),
            Partial::StringLiteral(", welcome!".to_string()),
        ]);

        let filled_document = template
            .saturate(&vec![TagPair {
                key: "name".to_string(),
                value: "Joe".to_string(),
            }])
            .unwrap();

        let expected_string = "Hello Joe, welcome!".to_string();

        assert_eq!(expected_string, filled_document.document());

        Ok(())
    }

    #[test]
    #[should_panic]
    fn test_non_existent_tag() {
        let template = DocumentTemplate::with_partials(&vec![Partial::Tag(
            "name".to_string(),
        )]);

        template
            .saturate(&vec![TagPair {
                key: "Hello".to_string(),
                value: "___".to_string(),
            }])
            .unwrap();
    }

    #[test]
    fn test_multiple_tags() -> Result<(), String> {
        let template = DocumentTemplate::with_partials(&vec![
            Partial::StringLiteral("<S1>".to_string()),
            Partial::Tag("T1".to_string()),
            Partial::StringLiteral("<S2>".to_string()),
            Partial::Tag("T2".to_string()),
            Partial::Tag("T1".to_string()),
            Partial::Tag("T3".to_string()),
        ]);

        let filled_document = template
            .saturate(&vec![
                TagPair {
                    key: "T1".to_string(),
                    value: "T1V".to_string(),
                },
                TagPair {
                    key: "T2".to_string(),
                    value: "T2V".to_string(),
                },
                TagPair {
                    key: "T3".to_string(),
                    value: "T3V".to_string(),
                },
            ])
            .unwrap();

        let expected_string = "<S1>T1V<S2>T2VT1VT3V".to_string();

        assert_eq!(expected_string, filled_document.document());

        Ok(())
    }
}