1use std::fs;
2use std::path::Path;
3
4pub fn head(path: &Path, n: usize) -> Vec<String> {
5 read_file_lines(path).into_iter().take(n).collect()
6}
7
8pub fn tail(path: &Path, n: usize) -> Vec<String> {
9 let lines = read_file_lines(path);
10 if lines.len() <= n {
11 lines
12 } else {
13 let to_skip = lines.len() - n;
14 lines.into_iter().skip(to_skip).collect()
15 }
16}
17
18fn read_file_lines(path: &Path) -> Vec<String> {
19 fs::read_to_string(path)
20 .unwrap()
21 .lines()
22 .map(String::from)
23 .collect()
24}
25
26#[cfg(test)]
27mod tests {
28 use super::*;
29
30 #[test]
31 fn head_works_with_small_n() {
32 let lines = head(&Path::new("test_files/lines.txt"), 2);
33 assert_eq!(lines, vec!["a", "b"]);
34 }
35
36 #[test]
37 fn head_works_with_big_n() {
38 let lines = head(&Path::new("test_files/lines.txt"), 10);
39 assert_eq!(lines, vec!["a", "b", "", "c", "d", "e"]);
40 }
41
42 #[test]
43 fn tail_works_with_small_n() {
44 let lines = tail(&Path::new("test_files/lines.txt"), 2);
45 assert_eq!(lines, vec!["d", "e"]);
46 }
47
48 #[test]
49 fn tail_works_with_big_n() {
50 let lines = tail(&Path::new("test_files/lines.txt"), 10);
51 assert_eq!(lines, vec!["a", "b", "", "c", "d", "e"]);
52 }
53}