ju_tcs_rust_23_2/
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
use std::fs;
use std::path::Path;

pub fn head(path: &Path, n: usize) -> Vec<String> {
    read_file_lines(path).into_iter().take(n).collect()
}

pub fn tail(path: &Path, n: usize) -> Vec<String> {
    let lines = read_file_lines(path);
    if lines.len() <= n {
        lines
    } else {
        let to_skip = lines.len() - n;
        lines.into_iter().skip(to_skip).collect()
    }
}

fn read_file_lines(path: &Path) -> Vec<String> {
    fs::read_to_string(path)
        .unwrap()
        .lines()
        .map(String::from)
        .collect()
}

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

    #[test]
    fn head_works_with_small_n() {
        let lines = head(&Path::new("test_files/lines.txt"), 2);
        assert_eq!(lines, vec!["a", "b"]);
    }

    #[test]
    fn head_works_with_big_n() {
        let lines = head(&Path::new("test_files/lines.txt"), 10);
        assert_eq!(lines, vec!["a", "b", "", "c", "d", "e"]);
    }

    #[test]
    fn tail_works_with_small_n() {
        let lines = tail(&Path::new("test_files/lines.txt"), 2);
        assert_eq!(lines, vec!["d", "e"]);
    }

    #[test]
    fn tail_works_with_big_n() {
        let lines = tail(&Path::new("test_files/lines.txt"), 10);
        assert_eq!(lines, vec!["a", "b", "", "c", "d", "e"]);
    }
}