jabba_lib/jfs.rs
1//! file system
2
3use std::fs::{self, File};
4use std::io::{self, BufRead, BufReader};
5
6/// Reads all the lines of a file and returns them in a vector.
7///
8/// It is similar to Python's `f.readlines()`, where `f` is a file handler.
9///
10/// # Examples
11///
12/// ```
13/// let lines: Vec<String> = jabba_lib::jfs::readlines("Cargo.toml").unwrap();
14/// ```
15pub fn readlines(fname: &str) -> io::Result<Vec<String>> {
16 let file = File::open(fname)?;
17 let reader = BufReader::new(file);
18 let mut lines = Vec::new();
19
20 for line in reader.lines() {
21 let line = line?;
22 lines.push(line);
23 }
24
25 Ok(lines)
26}
27
28/// Reads the content of a file and returns it in a single string.
29///
30/// It is similar to Python's `f.read()`, where `f` is a file handler.
31///
32/// # Examples
33///
34/// ```
35/// let content: String = jabba_lib::jfs::read("Cargo.toml").unwrap();
36/// ```
37pub fn read(fname: &str) -> io::Result<String> {
38 fs::read_to_string(fname)
39}
40
41/// Opens a file for reading.
42///
43/// With this, you can read a file line by line.
44///
45/// It is similar to Python's `f = open("text.txt")`.
46///
47/// # Examples
48///
49/// ```
50/// use std::io::BufRead;
51///
52/// let f = jabba_lib::jfs::open("Cargo.toml").unwrap();
53/// for line in f.lines() {
54/// let line = line.unwrap();
55/// println!("{}", line);
56/// }
57/// ```
58///
59/// In Python, it would look like this:
60///
61/// ```python
62/// f = open("Cargo.toml")
63/// for line in f:
64/// line = line.rstrip("\n")
65/// print(line)
66/// ```
67pub fn open(fname: &str) -> io::Result<BufReader<File>> {
68 let file = File::open(fname)?;
69 let reader = BufReader::new(file);
70
71 Ok(reader)
72}
73
74// ==========================================================================
75
76#[cfg(test)]
77mod tests {
78 use super::*;
79
80 #[test]
81 fn readlines_test1() {
82 let fname = "Cargo.toml";
83 let lines = readlines(fname).unwrap();
84 assert_eq!(lines.is_empty(), false);
85 }
86
87 #[test]
88 fn read_test1() {
89 let fname = "Cargo.toml";
90 let content = read(fname).unwrap();
91 assert_eq!(content.is_empty(), false);
92 }
93
94 #[test]
95 fn open_test1() {
96 let fname = "Cargo.toml";
97 let f = open(fname).unwrap();
98 for line in f.lines() {
99 let line = line.unwrap();
100 println!("{}", line);
101 }
102 }
103}