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
#![crate_name = "linecount"]
#![deny(missing_docs,
missing_debug_implementations, missing_copy_implementations,
trivial_casts, trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces, unused_qualifications)]
use std::io;
use std::io::{BufRead, BufReader};
const LF: u8 = '\n' as u8;
pub fn count_lines<R: io::Read>(handle: R) -> Result<usize, io::Error> {
let mut reader = BufReader::new(handle);
let mut count = 0;
let mut line: Vec<u8> = Vec::new();
while match reader.read_until(LF, &mut line) {
Ok(n) if n > 0 => true,
Err(e) => return Err(e),
_ => false,
} {
if *line.last().unwrap() == LF {
count += 1;
};
}
Ok(count)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_count_lines() {
let f: &[u8] = b"some text\nwith\nfour\nlines\n";
assert_eq!(count_lines(f).unwrap(), 4);
}
}