message_format/ast/
simple_format.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7use std::fmt;
8
9use super::Format;
10use Args;
11
12/// A simple message consisting of a value to be formatted.
13pub struct SimpleFormat {
14    /// The name of the variable whose value should be formatted.
15    variable_name: String,
16}
17
18impl SimpleFormat {
19    /// Construct a `SimpleFormat`.
20    pub fn new(variable_name: &str) -> Self {
21        SimpleFormat { variable_name: variable_name.to_string() }
22    }
23}
24
25impl Format for SimpleFormat {
26    fn format_message_part(&self, stream: &mut fmt::Write, args: &Args) -> fmt::Result {
27        if let Some(value) = args.get(self.variable_name.as_str()) {
28            try!(write!(stream, "{}", value));
29            Ok(())
30        } else {
31            // XXX: Should we return an error in this case?
32            Ok(())
33        }
34    }
35}
36
37#[cfg(test)]
38mod tests {
39    use super::*;
40    use ast::Format;
41    use Args;
42
43    #[test]
44    fn it_works() {
45        let fmt = SimpleFormat::new("name");
46        let mut output = String::new();
47        fmt.format_message_part(&mut output, &Args::new()).unwrap();
48        assert_eq!("", output);
49    }
50}