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
use std::collections::HashMap;

use serde_json;

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

    #[test]
    fn it_builds_a_mon_command() {
        let command = MonCommand::new().with_prefix("osd set").with("key", "osdout");

        let actual: HashMap<String, String> = serde_json::from_str(&command.as_json()).unwrap();
        let expected: HashMap<String, String> =
            serde_json::from_str(r#"{"prefix":"osd set","format":"json","key":"osdout"}"#).unwrap();

        assert_eq!(expected, actual);
    }
}

pub struct MonCommand<'a> {
    map: HashMap<&'a str, &'a str>,
}

impl<'a> MonCommand<'a> {
    pub fn new() -> MonCommand<'a> {
        MonCommand {
            map: {
                let mut map = HashMap::new();
                map.insert("format", "json");
                map
            },
        }
    }

    pub fn with_format(self, format: &'a str) -> MonCommand<'a> {
        self.with("format", format)
    }

    pub fn with_name(self, name: &'a str) -> MonCommand<'a> {
        self.with("name", name)
    }

    pub fn with_prefix(self, prefix: &'a str) -> MonCommand<'a> {
        self.with("prefix", prefix)
    }

    pub fn with(mut self, name: &'a str, value: &'a str) -> MonCommand<'a> {
        self.map.insert(name, value);
        self
    }

    pub fn as_json(&self) -> String {
        serde_json::to_string(&self.map).unwrap()
    }
}