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
182
183
184
185
186
187
188
189
190
191
192
193
/*!
Runtime string template formatting.
*/

use std::fmt;

/**
A runtime field-value template.
*/
pub struct Template<'a> {
    parts: &'a [Part<'a>],
}

impl<'a> Template<'a> {
    /**
    Render the template using the given context.

    The context helps the template find replacement values and determines how to render them if they're missing.
    An empty context can be used to render out the template with just its holes.
    */
    pub fn render<'brw>(
        &'brw self,
        ctx: Context<
            impl (Fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>) + 'brw,
            impl (Fn(&mut fmt::Formatter, &str) -> fmt::Result) + 'brw,
        >,
    ) -> impl fmt::Display + 'brw {
        struct ImplDisplay<'tpl, 'brw, TFill, TMissing> {
            template: &'brw Template<'tpl>,
            ctx: Context<TFill, TMissing>,
        }

        impl<'tpl, 'brw, TFill, TMissing> fmt::Display for ImplDisplay<'tpl, 'brw, TFill, TMissing>
        where
            TFill: Fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
            TMissing: Fn(&mut fmt::Formatter, &str) -> fmt::Result,
        {
            fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
                for part in self.template.parts {
                    match part {
                        Part::Text(text) => f.write_str(text)?,
                        Part::Hole(label) => {
                            if let Some(r) = (self.ctx.fill)(f, label) {
                                r?;
                            } else {
                                (self.ctx.missing)(f, label)?;
                            }
                        }
                    }
                }

                Ok(())
            }
        }

        ImplDisplay {
            template: self,
            ctx,
        }
    }
}

/**
A context used to render a template.
*/
pub struct Context<TFill, TMissing> {
    fill: TFill,
    missing: TMissing,
}

impl
    Context<
        fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
        fn(&mut fmt::Formatter, &str) -> fmt::Result,
    >
{
    /**
    Create a new rendering context with default handling for holes.
    */
    pub fn new() -> Self {
        Context {
            fill: |_, _| None,
            missing: |f, label| f.write_fmt(format_args!("`{}`", label)),
        }
    }
}

impl<TFill, TMissing> Context<TFill, TMissing>
where
    TFill: Fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
    TMissing: Fn(&mut fmt::Formatter, &str) -> fmt::Result,
{
    /**
    Provide a function to fill the holes in the template with.
    */
    pub fn fill<T>(self, fill: T) -> Context<T, TMissing>
    where
        T: Fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
    {
        Context {
            fill,
            missing: self.missing,
        }
    }

    /**
    Provide a function to handle unfilled holes.
    */
    pub fn missing<T>(self, missing: T) -> Context<TFill, T>
    where
        T: Fn(&mut fmt::Formatter, &str) -> fmt::Result,
    {
        Context {
            fill: self.fill,
            missing,
        }
    }
}

impl Default
    for Context<
        fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
        fn(&mut fmt::Formatter, &str) -> fmt::Result,
    >
{
    fn default() -> Self {
        Self::new()
    }
}

/**
A fragment of a template.

A set of `Part`s can be concatenated to form a user-facing representation
of a template.
*/
pub enum Part<'a> {
    /**
    A plain text fragment.
    */
    Text(&'a str),
    /**
    A hole in the template with a corresponding label to fill.
    */
    Hole(&'a str),
}

/**
Construct a `Template` from a set of `Part`s.
*/
pub fn template<'a>(parts: &'a [Part<'a>]) -> Template<'a> {
    Template { parts }
}

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

    #[test]
    fn render() {
        let cases = vec![
            (
                &[Part::Text("Hello "), Part::Hole("world"), Part::Text("!")],
                Context::new().fill(
                    (|write, label| Some(write.write_str(label)))
                        as fn(&mut fmt::Formatter, &str) -> Option<fmt::Result>,
                ),
                "Hello world!",
            ),
            (
                &[Part::Text("Hello "), Part::Hole("world"), Part::Text("!")],
                Context::new(),
                "Hello `world`!",
            ),
            (
                &[Part::Text("Hello "), Part::Hole("world"), Part::Text("!")],
                Context::new().missing(
                    (|write, label| write.write_fmt(format_args!("{{{}}}", label)))
                        as fn(&mut fmt::Formatter, &str) -> fmt::Result,
                ),
                "Hello {world}!",
            ),
        ];

        for (parts, ctx, expected) in cases {
            let template = template(parts);

            let actual = template.render(ctx).to_string();

            assert_eq!(expected, actual);
        }
    }
}