rustviz_lib/svg_frontend/
utils.rs

1use std::io::{self, prelude::*};
2use std::fs::File;
3use std::path::Path;
4
5/* File handling helper functions. */
6
7// Returns: a result object that we can match to OK(), and then use .lines() on.
8pub fn read_file<P>(file_path: P) -> io::Result<io::BufReader<File>>
9where
10    P: AsRef<Path>,
11{
12    let file = File::open(file_path)?;
13    Ok(io::BufReader::new(file))
14}
15
16pub fn read_file_to_string<P>(file_path: P) -> io::Result<String>
17where
18    P: AsRef<Path>,
19{
20    let mut string = String::new();
21    if let Ok(mut buf) = read_file(file_path) {
22        buf.read_to_string(&mut string)?;
23    }
24    Ok(string.to_owned())
25}
26
27// Returns: a result object that we can match to OK(), and then use .lines() on.
28pub fn read_lines<P>(file_path: P) -> io::Result<io::Lines<io::BufReader<File>>>
29where
30    P: AsRef<Path>,
31{
32    let file = File::open(file_path)?;
33    Ok(io::BufReader::new(file).lines())
34}
35
36// First Create the file, then write content into it.
37// Arguments:
38//      file_path:  any object that can be converted to a path
39//              Notable examples including String, str, Path, PathBuf, OsString.
40//      content:    a String that needs to be written.
41pub fn create_and_write_to_file<P>(content: &String, file_path: P)
42where
43    P: AsRef<Path>,
44{
45    let display = file_path.as_ref().display();
46
47    // Open a file in write-only mode, returns `io::Result<File>`
48    let mut file = match File::create(file_path.as_ref()) {
49        Err(why) => panic!("couldn't create {}: {}", display, why),
50        Ok(file) => file,
51    };
52
53    // Write the content string to `file`, returns `io::Result<()>`
54    match file.write_all(content.as_bytes()) {
55        Err(why) => panic!("couldn't write to {}: {}", display, why),
56        Ok(_) => println!("successfully wrote to {}", display),
57    }
58}