1pub struct StringAccumulator {
3 acc: String,
4 active: bool,
5}
6
7impl StringAccumulator {
8 pub fn new() -> StringAccumulator {
10 StringAccumulator {
11 acc: String::with_capacity(1024),
12 active: false,
13 }
14 }
15
16 pub fn activate(&mut self) {
18 self.active = true;
19 self.acc.clear();
20 }
21
22 pub fn add_slice<S: AsRef<str>>(&mut self, other: S) {
24 if self.active {
25 self.acc.push_str(other.as_ref());
26 }
27 }
28
29 pub fn finish(&mut self) -> &str {
30 if self.active {
31 self.active = false;
32 &self.acc
33 } else {
34 ""
35 }
36 }
37}
38
39#[test]
40fn test_empty() {
41 let mut acc = StringAccumulator::new();
42 let res = acc.finish();
43 assert!(res.is_empty());
44}
45
46#[test]
47fn test_add_inactive() {
48 let mut acc = StringAccumulator::new();
49 acc.add_slice("foo");
50 let res = acc.finish();
51 assert!(res.is_empty());
52}
53
54#[test]
55fn test_accum() {
56 let mut acc = StringAccumulator::new();
57 acc.activate();
58 acc.add_slice("lorem");
59 acc.add_slice(" ipsum");
60 let res = acc.finish();
61 assert_eq!(res, "lorem ipsum".to_owned());
62}
63
64#[test]
65fn test_accum_finish() {
66 let mut acc = StringAccumulator::new();
67 acc.activate();
68 acc.add_slice("lorem");
69 acc.add_slice(" ipsum");
70 let res = acc.finish();
71 assert_eq!(res, "lorem ipsum".to_owned());
72
73 acc.add_slice("bob");
74 let res = acc.finish();
75 assert!(res.is_empty())
76}
77
78#[test]
79fn test_accum_twice() {
80 let mut acc = StringAccumulator::new();
81 acc.activate();
82 acc.add_slice("lorem");
83 acc.add_slice(" ipsum");
84 let res = acc.finish();
85 assert_eq!(res, "lorem ipsum".to_owned());
86
87 acc.add_slice("bob");
88
89 acc.activate();
90 acc.add_slice("fishbone");
91 let res = acc.finish();
92 assert_eq!(res, "fishbone".to_owned());
93}