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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
use std::cell::RefCell;
use std::string::ToString;
use std::collections::HashMap;
use rustc_serialize::Encodable;

use encoder;
use encoder::Error;
use super::{Data, StrVal, Bool, VecVal, Map, Fun};

/// `MapBuilder` is a helper type that construct `Data` types.
pub struct MapBuilder {
    data: HashMap<String, Data>,
}

impl MapBuilder {
    /// Create a `MapBuilder`
    #[inline]
    pub fn new() -> MapBuilder {
        MapBuilder {
            data: HashMap::new(),
        }
    }

    /// Add an `Encodable` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let data = MapBuilder::new()
    ///     .insert("name", &("Jane Austen")).ok().unwrap()
    ///     .insert("age", &41usize).ok().unwrap()
    ///     .build();
    /// ```
    #[inline]
    pub fn insert<
        K: ToString, T: Encodable
    >(self, key: K, value: &T) -> Result<MapBuilder, Error> {
        let MapBuilder { mut data } = self;
        let value = try!(encoder::encode(value));
        data.insert(key.to_string(), value);
        Ok(MapBuilder { data: data })
    }

    /// Add a `String` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let data = MapBuilder::new()
    ///     .insert_str("name", "Jane Austen")
    ///     .build();
    /// ```
    #[inline]
    pub fn insert_str<
        K: ToString, V: ToString
    >(self, key: K, value: V) -> MapBuilder {
        let MapBuilder { mut data } = self;
        data.insert(key.to_string(), StrVal(value.to_string()));
        MapBuilder { data: data }
    }

    /// Add a `bool` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let data = MapBuilder::new()
    ///     .insert_bool("show", true)
    ///     .build();
    /// ```
    #[inline]
    pub fn insert_bool<K: ToString>(self, key: K, value: bool) -> MapBuilder {
        let MapBuilder { mut data } = self;
        data.insert(key.to_string(), Bool(value));
        MapBuilder { data: data }
    }

    /// Add a `Vec` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let data = MapBuilder::new()
    ///     .insert_vec("authors", |builder| {
    ///         builder
    ///             .push_str("Jane Austen")
    ///             .push_str("Lewis Carroll")
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn insert_vec<K: ToString, F>(self, key: K, mut f: F) -> MapBuilder
        where F: FnMut(VecBuilder) -> VecBuilder {
        let MapBuilder { mut data } = self;
        let builder = f(VecBuilder::new());
        data.insert(key.to_string(), builder.build());
        MapBuilder { data: data }
    }

    /// Add a `Map` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let data = MapBuilder::new()
    ///     .insert_map("person1", |builder| {
    ///         builder
    ///             .insert_str("first_name", "Jane")
    ///             .insert_str("last_name", "Austen")
    ///     })
    ///     .insert_map("person2", |builder| {
    ///         builder
    ///             .insert_str("first_name", "Lewis")
    ///             .insert_str("last_name", "Carroll")
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn insert_map<K: ToString, F>(self, key: K, mut f: F) -> MapBuilder
        where F: FnMut(MapBuilder) -> MapBuilder {
        let MapBuilder { mut data } = self;
        let builder = f(MapBuilder::new());
        data.insert(key.to_string(), builder.build());
        MapBuilder { data: data }
    }

    /// Add a function to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::MapBuilder;
    /// let mut count = 0;
    /// let data = MapBuilder::new()
    ///     .insert_fn("increment", move |_| {
    ///         count += 1usize;
    ///         count.to_string()
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn insert_fn<K: ToString, F>(self, key: K, f: F) -> MapBuilder
                                where F: FnMut(String) -> String + Send + 'static {
        let MapBuilder { mut data } = self;
        data.insert(key.to_string(), Fun(RefCell::new(Box::new(f))));
        MapBuilder { data: data }
    }

    /// Return the built `Data`.
    #[inline]
    pub fn build(self) -> Data {
        Map(self.data)
    }
}

pub struct VecBuilder {
    data: Vec<Data>,
}

impl<'a> VecBuilder {
    /// Create a `VecBuilder`
    #[inline]
    pub fn new() -> VecBuilder {
        VecBuilder {
            data: Vec::new(),
        }
    }

    /// Add an `Encodable` to the `VecBuilder`.
    ///
    /// ```rust
    /// use mustache::{VecBuilder, Data};
    /// let data: Data = VecBuilder::new()
    ///     .push(& &"Jane Austen").ok().unwrap()
    ///     .push(&41usize).ok().unwrap()
    ///     .build();
    /// ```
    #[inline]
    pub fn push<T: Encodable>(self, value: &T) -> Result<VecBuilder, Error> {
        let VecBuilder { mut data } = self;
        let value = try!(encoder::encode(value));
        data.push(value);
        Ok(VecBuilder { data: data })
    }

    /// Add a `String` to the `VecBuilder`.
    ///
    /// ```rust
    /// use mustache::VecBuilder;
    /// let data = VecBuilder::new()
    ///     .push_str("Jane Austen")
    ///     .push_str("Lewis Carroll")
    ///     .build();
    /// ```
    #[inline]
    pub fn push_str<T: ToString>(self, value: T) -> VecBuilder {
        let VecBuilder { mut data } = self;
        data.push(StrVal(value.to_string()));
        VecBuilder { data: data }
    }

    /// Add a `bool` to the `VecBuilder`.
    ///
    /// ```rust
    /// use mustache::VecBuilder;
    /// let data = VecBuilder::new()
    ///     .push_bool(false)
    ///     .push_bool(true)
    ///     .build();
    /// ```
    #[inline]
    pub fn push_bool(self, value: bool) -> VecBuilder {
        let VecBuilder { mut data } = self;
        data.push(Bool(value));
        VecBuilder { data: data }
    }

    /// Add a `Vec` to the `MapBuilder`.
    ///
    /// ```rust
    /// use mustache::VecBuilder;
    /// let data = VecBuilder::new()
    ///     .push_vec(|builder| {
    ///         builder
    ///             .push_str("Jane Austen".to_string())
    ///             .push_str("Lewis Carroll".to_string())
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn push_vec<F>(self, mut f: F) -> VecBuilder
        where F: FnMut(VecBuilder) -> VecBuilder {
        let VecBuilder { mut data } = self;
        let builder = f(VecBuilder::new());
        data.push(builder.build());
        VecBuilder { data: data }
    }

    /// Add a `Map` to the `VecBuilder`.
    ///
    /// ```rust
    /// use mustache::VecBuilder;
    /// let data = VecBuilder::new()
    ///     .push_map(|builder| {
    ///         builder
    ///             .insert_str("first_name".to_string(), "Jane".to_string())
    ///             .insert_str("last_name".to_string(), "Austen".to_string())
    ///     })
    ///     .push_map(|builder| {
    ///         builder
    ///             .insert_str("first_name".to_string(), "Lewis".to_string())
    ///             .insert_str("last_name".to_string(), "Carroll".to_string())
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn push_map<F>(self, mut f: F) -> VecBuilder
        where F: FnMut(MapBuilder) -> MapBuilder {
        let VecBuilder { mut data } = self;
        let builder = f(MapBuilder::new());
        data.push(builder.build());
        VecBuilder { data: data }
    }

    /// Add a function to the `VecBuilder`.
    ///
    /// ```rust
    /// use mustache::VecBuilder;
    /// let mut count = 0;
    /// let data = VecBuilder::new()
    ///     .push_fn(move |s| {
    ///         count += 1usize;
    ///         s + &count.to_string()
    ///     })
    ///     .build();
    /// ```
    #[inline]
    pub fn push_fn<F>(self, f: F) -> VecBuilder
                   where F: FnMut(String) -> String + Send + 'static {
        let VecBuilder { mut data } = self;
        data.push(Fun(RefCell::new(Box::new(f))));
        VecBuilder { data: data }
    }

    #[inline]
    pub fn build(self) -> Data {
        VecVal(self.data)
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::super::{StrVal, Bool, VecVal, Map, Fun};
    use super::{MapBuilder, VecBuilder};

    #[test]
    fn test_empty_builders() {
        assert_eq!(
            MapBuilder::new().build(),
            Map(HashMap::new()));

        assert_eq!(
            VecBuilder::new().build(),
            VecVal(Vec::new()));
    }

    #[test]
    fn test_builders() {
        let mut pride_and_prejudice = HashMap::new();
        pride_and_prejudice.insert("title".to_string(), StrVal("Pride and Prejudice".to_string()));
        pride_and_prejudice.insert("publish_date".to_string(), StrVal("1813".to_string()));

        let mut m = HashMap::new();
        m.insert("first_name".to_string(), StrVal("Jane".to_string()));
        m.insert("last_name".to_string(), StrVal("Austen".to_string()));
        m.insert("age".to_string(), StrVal("41".to_string()));
        m.insert("died".to_string(), Bool(true));
        m.insert("works".to_string(), VecVal(vec!(
            StrVal("Sense and Sensibility".to_string()),
            Map(pride_and_prejudice))));

        assert_eq!(
            MapBuilder::new()
                .insert_str("first_name", "Jane")
                .insert_str("last_name", "Austen")
                .insert("age", &41usize).ok().unwrap()
                .insert_bool("died", true)
                .insert_vec("works", |builder| {
                    builder
                        .push_str("Sense and Sensibility")
                        .push_map(|builder| {
                            builder
                                .insert_str("title", "Pride and Prejudice")
                                .insert("publish_date", &1813usize).ok().unwrap()
                        })
                })
                .build(),
            Map(m));
    }

    #[test]
    fn test_map_fn_builder() {
        // We can't directly compare closures, so just make sure we thread
        // through the builder.

        let mut count = 0usize;
        let data = MapBuilder::new()
            .insert_fn("count".to_string(), move |s| {
                count += 1usize;
                s.clone() + &count.to_string()
            })
            .build();

        match data {
            Map(m) => {
                match *m.get(&"count".to_string()).unwrap() {
                    Fun(ref f) => {
                        let f = &mut *f.borrow_mut();
                        assert_eq!((*f)("count: ".to_string()), "count: 1".to_string());
                        assert_eq!((*f)("count: ".to_string()), "count: 2".to_string());
                        assert_eq!((*f)("count: ".to_string()), "count: 3".to_string());
                    }
                    _ => panic!(),
                }
            }
            _ => panic!(),
        }
    }

    #[test]
    fn test_vec_fn_builder() {
        // We can't directly compare closures, so just make sure we thread
        // through the builder.

        let mut count = 0usize;
        let data = VecBuilder::new()
            .push_fn(move |s| {
                count += 1usize;
                s + &count.to_string()
            })
            .build();

        match data {
            VecVal(vs) => {
                let mut iter = vs.iter();

                if let Some(&Fun(ref f)) = iter.next() {
                    let f = &mut *f.borrow_mut();
                    assert_eq!((*f)("count: ".to_string()), "count: 1".to_string());
                    assert_eq!((*f)("count: ".to_string()), "count: 2".to_string());
                    assert_eq!((*f)("count: ".to_string()), "count: 3".to_string());
                } else {
                    panic!()
                }

                if let Some(..) = iter.next() {
                    panic!()
                }
            }
            _ => panic!(),
        }
    }
}