bookdata/util/
accum.rs

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
/// Activatable data acumulator.
pub struct StringAccumulator {
    acc: String,
    active: bool,
}

impl StringAccumulator {
    /// Create a new data accumulator.
    pub fn new() -> StringAccumulator {
        StringAccumulator {
            acc: String::with_capacity(1024),
            active: false,
        }
    }

    /// Start accumulating data
    pub fn activate(&mut self) {
        self.active = true;
        self.acc.clear();
    }

    /// Add a slice of data to the accumulator.
    pub fn add_slice<S: AsRef<str>>(&mut self, other: S) {
        if self.active {
            self.acc.push_str(other.as_ref());
        }
    }

    pub fn finish(&mut self) -> &str {
        if self.active {
            self.active = false;
            &self.acc
        } else {
            ""
        }
    }
}

#[test]
fn test_empty() {
    let mut acc = StringAccumulator::new();
    let res = acc.finish();
    assert!(res.is_empty());
}

#[test]
fn test_add_inactive() {
    let mut acc = StringAccumulator::new();
    acc.add_slice("foo");
    let res = acc.finish();
    assert!(res.is_empty());
}

#[test]
fn test_accum() {
    let mut acc = StringAccumulator::new();
    acc.activate();
    acc.add_slice("lorem");
    acc.add_slice(" ipsum");
    let res = acc.finish();
    assert_eq!(res, "lorem ipsum".to_owned());
}

#[test]
fn test_accum_finish() {
    let mut acc = StringAccumulator::new();
    acc.activate();
    acc.add_slice("lorem");
    acc.add_slice(" ipsum");
    let res = acc.finish();
    assert_eq!(res, "lorem ipsum".to_owned());

    acc.add_slice("bob");
    let res = acc.finish();
    assert!(res.is_empty())
}

#[test]
fn test_accum_twice() {
    let mut acc = StringAccumulator::new();
    acc.activate();
    acc.add_slice("lorem");
    acc.add_slice(" ipsum");
    let res = acc.finish();
    assert_eq!(res, "lorem ipsum".to_owned());

    acc.add_slice("bob");

    acc.activate();
    acc.add_slice("fishbone");
    let res = acc.finish();
    assert_eq!(res, "fishbone".to_owned());
}