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
use std::collections::HashMap;
#[derive(Default)]
pub struct Config {
value: HashMap<String, String>,
}
impl Config {
pub fn new() -> Config {
Config::default()
}
pub fn insert(mut self, key: impl Into<String>, value: impl Into<String>) -> Config {
let key = key.into();
let value = value.into();
self.value.insert(key, value);
self
}
pub fn apply(&self, content: impl Into<String>) -> String {
let content = content.into();
self.value
.iter()
.fold(content, |content, (key, value)| content.replace(key, value))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn replace_once() {
let content = r#"Replace <foo> once"#;
let config = Config::new().insert("<foo>", "me");
assert_eq!(config.apply(content), "Replace me once");
}
#[test]
fn replace_multiple() {
let content = r#"
Line 1: <foo>
Line 2: <bar>
Line 3: <foobar>
"#;
let config = Config::new()
.insert("<foo>", "一")
.insert("<bar>", "二")
.insert("<foobar>", "三");
let result = config.apply(content);
let expect = r#"
Line 1: 一
Line 2: 二
Line 3: 三
"#;
assert_eq!(result, expect);
}
#[test]
fn replace_many_time() {
let content = r#"
A: <explosion>
B: <explosion>
C: <explosion>
D: <explosion>
"#;
let config = Config::new().insert("<explosion>", "エクプロシオン");
let result = config.apply(content);
let expect = r#"
A: エクプロシオン
B: エクプロシオン
C: エクプロシオン
D: エクプロシオン
"#;
assert_eq!(result, expect);
}
}