Skip to main content

ju_tcs_rust_23_04/
lib.rs

1pub mod backend {
2    use std::fs::read_to_string;
3    use std::path::PathBuf;
4
5    pub fn head(path: PathBuf, n: usize) -> Result<Vec<String>, String> {
6        Ok(
7        read_to_string(path)
8            .or(Err("Could not open file.".to_owned()))?
9            .lines()
10            .take(n)
11            .map(|l| l.to_owned())
12            .collect()
13        )
14    }
15
16    pub fn tail(path: PathBuf, n: usize) -> Result<Vec<String>, String> {
17        let lines = read_to_string(path)
18            .or(Err("Could not open file.".to_owned()))?
19            .lines()
20            .map(|l| l.to_owned())
21            .collect::<Vec<_>>();
22        let len = lines.len();
23        Ok(lines[len - n..].iter().map(|l| l.to_owned()).collect())
24    }
25}
26
27#[cfg(test)]
28mod tests {
29    use crate::backend::*;
30    #[test]
31    fn test_head() {
32        let lines = head("files/test.txt".into(), 3);
33        assert_eq!(lines, Ok(vec!["1".to_owned(), "2".to_owned(), "3".to_owned()]));
34    }
35
36    #[test]
37    fn test_tail() {
38        let lines = tail("files/test.txt".into(), 3);
39        assert_eq!(lines, Ok(vec!["8".to_owned(), "9".to_owned(), "10".to_owned()]));
40    }
41}