message_format/ast/
select_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::collections::HashMap;
8use std::fmt;
9use std::hash::Hash;
10
11use ast::Format;
12use {Args, Message};
13
14/// Using a value, select the appropriate message and format it.
15pub struct SelectFormat<K> {
16    /// The name of the variable whose value should be formatted.
17    #[allow(dead_code)]
18    variable_name: String,
19    /// Given a value of a variable, this maps that to a message format.
20    #[allow(dead_code)]
21    mappings: HashMap<K, Message>,
22    /// The message format to use if no valid mapping is found for
23    /// the variable value.
24    default: Message,
25}
26
27impl<K> SelectFormat<K>
28    where K: Eq + Hash
29{
30    /// Construct a `SelectFormat`.
31    pub fn new(variable_name: &str, default: Message) -> Self {
32        SelectFormat {
33            variable_name: variable_name.to_string(),
34            mappings: HashMap::<K, Message>::new(),
35            default: default,
36        }
37    }
38
39    /// Map a value for a particular message.
40    pub fn map(mut self, value: K, message: Message) -> Self {
41        self.mappings.insert(value, message);
42        self
43    }
44}
45
46impl<K> Format for SelectFormat<K> {
47    fn format_message_part(&self, stream: &mut fmt::Write, args: &Args) -> fmt::Result {
48        try!(self.default.format_message(stream, args));
49        Ok(())
50    }
51}