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
#![deprecated(since="0.2.0", note="please use `map(str::trim)` instead")]
pub use std::str::Lines;

///A wrapper around Lines which trims the whitespace from each line.
pub struct TrimLines<'a> {
    l: Lines<'a>,
}

impl<'a> Iterator for TrimLines<'a> {
    type Item = &'a str;
    #[inline]
    fn next(&mut self) -> Option<&'a str> {
        let n = self.l.next();
        match n {
            Some(s) => Some(s.trim()),
            None => None,
        }
    }
}

impl<'a> DoubleEndedIterator for TrimLines<'a> {
    #[inline]
    fn next_back(&mut self) -> Option<&'a str> {
        let n = self.l.next_back();
        return match n {
            Some(s) => Some(s.trim()),
            None => None,
        };
    }
}

impl<'a> TrimLines<'a> {
    ///Create a TrimLines from a Lines.
    #[inline]
    pub fn new(lines: Lines) -> TrimLines {
        return TrimLines { l: lines };
    }

    ///Create a TrimLines directly from a string slice.
    #[inline]
    pub fn from_str(st: &str) -> TrimLines {
        return TrimLines { l: st.lines() };
    }
}

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

    #[test]
    fn forward_iter() {
        let text = "    foo    \r\n    bar    \n   \n    baz    \n";
        let mut lines = TrimLines::new(text.lines());

        assert_eq!(Some("foo"), lines.next());
        assert_eq!(Some("bar"), lines.next());
        assert_eq!(Some(""), lines.next());
        assert_eq!(Some("baz"), lines.next());
        assert_eq!(None, lines.next());
    }

    #[test]
    fn backward_iter() {
        let text = "    foo    \r\n    bar    \n   \n    baz    \n";
        let mut lines = TrimLines::new(text.lines());

        assert_eq!(Some("baz"), lines.next_back());
        assert_eq!(Some(""), lines.next_back());
        assert_eq!(Some("bar"), lines.next_back());
        assert_eq!(Some("foo"), lines.next_back());
        assert_eq!(None, lines.next_back());
    }
}