ys1r/
io.rs

1use std::error::Error;
2use std::fs::{self, File};
3use std::io::{BufRead, BufReader, Write};
4
5/// Reads the content of a file into a String.
6///
7/// # Arguments
8///
9/// * `file_name` - The path to the file to read.
10///
11/// # Returns
12///
13/// A `Result` containing the content of the file as a `String`, or an error if the file could not be read.
14pub fn file_read(file_name: &str) -> Result<String, Box<dyn Error>> {
15    let content = fs::read_to_string(file_name)?;
16    Ok(content)
17}
18
19/// Writes a string to a file.
20///
21/// # Arguments
22///
23/// * `file_name` - The path to the file to write to.
24/// * `content` - The content to write to the file.
25///
26/// # Returns
27///
28/// A `Result` indicating success or an error if the file could not be written.
29pub fn file_write(file_name: &str, content: &str) -> Result<(), Box<dyn Error>> {
30    let mut file = File::create(file_name)?;
31    file.write_all(content.as_bytes())?;
32    Ok(())
33}
34
35/// Processes each line of a file with a given function.
36///
37/// # Arguments
38///
39/// * `file_name` - The path to the file to process.
40/// * `f` - A function to apply to each line of the file.
41///
42/// # Returns
43///
44/// A `Result` indicating success or an error if the file could not be read.
45pub fn process_file_lines<F>(file_name: &str, mut f: F) -> Result<(), Box<dyn Error>>
46where
47    F: FnMut(&str),
48{
49    let file = File::open(file_name)?;
50    let reader = BufReader::new(file);
51
52    for line_result in reader.lines() {
53        let line = line_result?;
54        f(&line);
55    }
56
57    Ok(())
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63    use std::fs;
64    use std::io::Write;
65
66    #[test]
67    fn test_file_read_write() -> Result<(), Box<dyn Error>> {
68        let file_name = "test_file.txt";
69        let content_a = "HELLO WORLD!";
70
71        file_write(file_name, content_a)?;
72
73        let content_b = file_read(file_name)?;
74
75        assert_eq!(content_b, content_a);
76        fs::remove_file(file_name)?;
77        Ok(())
78    }
79
80    #[test]
81    fn test_process_file_lines() -> Result<(), Box<dyn Error>> {
82        let mut path = std::env::temp_dir();
83        path.push("test_file_lines.txt");
84        let content = "rust\nruby\nr\n";
85        let mut file = File::create(&path)?;
86        file.write_all(content.as_bytes())?;
87
88        let mut collected = Vec::new();
89        process_file_lines(path.to_str().unwrap(), |line| {
90            let modified_line = line.replace("r", "R");
91            collected.push(modified_line);
92        })?;
93
94        assert_eq!(collected, vec!["Rust", "Ruby", "R"]);
95
96        fs::remove_file(path)?;
97        Ok(())
98    }
99}