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
use std::path::PathBuf;
use std::fs::File;
use std::io::{self, BufRead};

pub fn head(n: usize, path: PathBuf) -> Vec<String>{
    let file = File::open(path).expect("Failed open");
    let line_count = io::BufReader::new(&file).lines().count();
    if line_count < n {
        panic!("Number of lines in the file is less than {}", n);
    }
    io::BufReader::new(file)
        .lines()
        .take(n)
        .map(|line| line.expect("Failed to read a line"))
        .collect()
}

pub fn tail(n: usize, path: PathBuf) -> Vec<String>{
    let file = File::open(path).expect("Failed open");
    let line_count = io::BufReader::new(&file).lines().count();
    if line_count < n {
        panic!("Number of lines in the file is less than {}", n);
    }
    io::BufReader::new(file)
        .lines()
        .skip(line_count-n)
        .map(|line| line.expect("Failed to read a line"))
        .collect()
}