uj_tcs_rust_23_18/
lib.rs

1use std::path::PathBuf;
2
3/// provided 'path' to the file prints Min('n', file_line_count) first lines of the file.
4pub fn head(path: &PathBuf, n: u32) -> std::io::Result<()> {
5    let mut line_count: u32 = 0;
6    for _ in read_lines(path)? {
7        line_count += 1;
8    }
9
10    let first_not_to_print: u32 = std::cmp::min(n, line_count);
11
12    let mut at_line: u32 = 0;
13    for line in read_lines(path)? {
14        if at_line >= first_not_to_print {
15            break;
16        }
17        println!("{}", line.expect("failed to read line"));
18        at_line += 1;
19    }
20    Ok(())
21}
22
23/// provided 'path' to the file prints Min('n', file_line_count) last lines of the file.
24pub fn tail(path: &PathBuf, n: u32) -> std::io::Result<()> {
25    let mut line_count: u32 = 0;
26    for _ in read_lines(path)? {
27        line_count += 1;
28    }
29
30    let first_to_print: u32 = line_count.saturating_sub(n);
31
32    let mut at_line: u32 = 0;
33    for line in read_lines(path)? {
34        if at_line >= first_to_print {
35            println!("{}", line.expect("failed to read line"));
36        }
37        at_line += 1;
38    }
39    Ok(())
40}
41
42use std::io::BufRead;
43
44fn read_lines(
45    filename: &PathBuf,
46) -> std::io::Result<std::io::Lines<std::io::BufReader<std::fs::File>>> {
47    let file = std::fs::File::open(filename)?;
48    Ok(std::io::BufReader::new(file).lines())
49}
50
51#[cfg(test)]
52mod tests {
53    #[test]
54    fn test_math() {}
55}