about summary refs log tree commit diff
path: root/src/messages.rs
blob: aa0366e786ca89b63df1beb434aa4e47ab0b47bd (plain) (blame)
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
use crate::util::template::Template;
use crate::util::template::TemplateParams;
use rand::seq::SliceRandom;
use rand::Rng;
use std::collections::HashMap;

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum Message<'a> {
    #[serde(borrow)]
    Single(Template<'a>),
    Choice(Vec<Template<'a>>),
}

impl<'a> Message<'a> {
    fn resolve<R: Rng + ?Sized>(&self, rng: &mut R) -> Option<&Template<'a>> {
        use Message::*;
        match self {
            Single(msg) => Some(msg),
            Choice(msgs) => msgs.choose(rng),
        }
    }
}

#[derive(Deserialize, Debug, PartialEq, Eq)]
#[serde(untagged)]
enum NestedMap<'a> {
    #[serde(borrow)]
    Direct(Message<'a>),
    #[serde(borrow)]
    Nested(HashMap<&'a str, NestedMap<'a>>),
}

impl<'a> NestedMap<'a> {
    fn lookup(&'a self, path: &str) -> Option<&'a Message<'a>> {
        use NestedMap::*;
        let leaf =
            path.split(".")
                .fold(Some(self), |current, key| match current {
                    Some(Nested(m)) => m.get(key),
                    _ => None,
                });
        match leaf {
            Some(Direct(msg)) => Some(msg),
            _ => None,
        }
    }
}

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

    #[test]
    fn test_deserialize_nested_map() {
        let src = r#"
[global]
hello = "Hello World!"

[foo.bar]
single = "Single"
choice = ["Say this", "Or this"]
"#;
        let result = toml::from_str(src);
        assert_eq!(
            result,
            Ok(NestedMap::Nested(hashmap! {
                "global" => NestedMap::Nested(hashmap!{
                    "hello" => NestedMap::Direct(Message::Single(Template::parse("Hello World!").unwrap())),
                }),
                "foo" => NestedMap::Nested(hashmap!{
                    "bar" => NestedMap::Nested(hashmap!{
                        "single" => NestedMap::Direct(Message::Single(
                            Template::parse("Single").unwrap()
                        )),
                        "choice" => NestedMap::Direct(Message::Choice(
                            vec![
                                Template::parse("Say this").unwrap(),
                                Template::parse("Or this").unwrap()
                            ]
                        ))
                    })
                })
            }))
        )
    }

    #[test]
    fn test_lookup() {
        let map: NestedMap<'static> = toml::from_str(
            r#"
[global]
hello = "Hello World!"

[foo.bar]
single = "Single"
choice = ["Say this", "Or this"]
"#,
        )
        .unwrap();

        assert_eq!(
            map.lookup("global.hello"),
            Some(&Message::Single(Template::parse("Hello World!").unwrap()))
        );
        assert_eq!(
            map.lookup("foo.bar.single"),
            Some(&Message::Single(Template::parse("Single").unwrap()))
        );
        assert_eq!(
            map.lookup("foo.bar.choice"),
            Some(&Message::Choice(vec![
                Template::parse("Say this").unwrap(),
                Template::parse("Or this").unwrap()
            ]))
        );
    }
}

// static MESSAGES_RAW: &'static str = include_str!("messages.toml");

static_cfg! {
    static ref MESSAGES: NestedMap<'static> = toml_file("messages.toml");
}

/// Look up and format a game message based on the given (dot-separated) name,
/// with the given random generator used to select from choice-based messages
pub fn message<'a, R: Rng + ?Sized>(
    name: &'static str,
    rng: &mut R,
    params: &TemplateParams<'a>,
) -> String {
    match MESSAGES.lookup(name).and_then(|msg| msg.resolve(rng)) {
        Some(msg) => msg.format(params).unwrap_or_else(|e| {
            error!("Error formatting template: {}", e);
            "Template Error".to_string()
        }),
        None => {
            error!("Message not found: {}", name);
            "Template Not Found".to_string()
        }
    }
}