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
use errors::*;
use dispenser::Dispenser;
use std::{collections, fmt};
struct Mixer {
pub dispensers: collections::HashMap<String, Box<Dispenser>>,
}
impl fmt::Debug for Mixer {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (name, dispenser) in self.dispensers.iter() {
writeln!(f,
"{} => \n\tmax_flow_rate: {} mL/s\n\tremaining: {} mL",
name,
dispenser.max_flow_rate(),
dispenser.remaining().unwrap());
}
Ok(())
}
}
impl Mixer {
fn new() -> Mixer {
let mut dispensers = collections::HashMap::new();
Mixer { dispensers: dispensers }
}
fn clear(&mut self) {
self.dispensers.clear();
}
fn get(&mut self, name: &str) -> Option<&Box<Dispenser>> {
self.dispensers.get(name)
}
fn remove(&mut self, name: &str) {
self.dispensers.remove(name);
}
fn add(&mut self, name: &str, dispenser: Box<Dispenser>) {
self.dispensers.insert(String::from(name), dispenser);
}
}
#[cfg(test)]
mod test {
use dispenser::TestDispenser;
use mixer::Mixer;
#[test]
fn test_create_a_mixer() {
let mut mixer = Mixer::new();
let mut dispenser1 = Box::new(TestDispenser::new(1.0, 3.0));
let mut dispenser2 = Box::new(TestDispenser::new(1.0, 3.0));
let mut dispenser3 = Box::new(TestDispenser::new(1.0, 3.0));
mixer.add("whiskey", dispenser1);
mixer.add("vodka", dispenser2);
mixer.add("gin", dispenser3);
mixer.get("whiskey").unwrap();
mixer.get("vodka").unwrap();
mixer.get("gin").unwrap();
mixer.remove("whiskey");
mixer.remove("vodka");
mixer.remove("gin");
assert!(mixer.get("whiskey").is_none());
assert!(mixer.get("vodka").is_none());
assert!(mixer.get("gin").is_none());
}
}