uj_tcs_rust_23_18/
lib.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
use std::path::PathBuf;

/// provided 'path' to the file prints Min('n', file_line_count) first lines of the file.
pub fn head(path: &PathBuf, n: u32) -> std::io::Result<()> {
    let mut line_count: u32 = 0;
    for _ in read_lines(path)? {
        line_count += 1;
    }

    let first_not_to_print: u32 = std::cmp::min(n, line_count);

    let mut at_line: u32 = 0;
    for line in read_lines(path)? {
        if at_line >= first_not_to_print {
            break;
        }
        println!("{}", line.expect("failed to read line"));
        at_line += 1;
    }
    Ok(())
}

/// provided 'path' to the file prints Min('n', file_line_count) last lines of the file.
pub fn tail(path: &PathBuf, n: u32) -> std::io::Result<()> {
    let mut line_count: u32 = 0;
    for _ in read_lines(path)? {
        line_count += 1;
    }

    let first_to_print: u32 = line_count.saturating_sub(n);

    let mut at_line: u32 = 0;
    for line in read_lines(path)? {
        if at_line >= first_to_print {
            println!("{}", line.expect("failed to read line"));
        }
        at_line += 1;
    }
    Ok(())
}

use std::io::BufRead;

fn read_lines(
    filename: &PathBuf,
) -> std::io::Result<std::io::Lines<std::io::BufReader<std::fs::File>>> {
    let file = std::fs::File::open(filename)?;
    Ok(std::io::BufReader::new(file).lines())
}

#[cfg(test)]
mod tests {
    #[test]
    fn test_math() {}
}