phoenix_lang/io/
mod.rs

1use crate::{error, info};
2use std::fs;
3use std::fs::File;
4use std::io::{Read, Write};
5use std::path::Path;
6use std::process::exit;
7
8pub fn read_file(file_name: String) -> Result<String, String> {
9    let path = Path::new(&file_name);
10    let path_display = path.display();
11
12    let mut file = match File::open(path) {
13        Ok(file) => file,
14        Err(why) => {
15            return Err(format!("Failed to open {}: {}", path_display, why));
16        }
17    };
18    let mut s = String::new();
19    match file.read_to_string(&mut s) {
20        Ok(_) => Ok(s.to_string()),
21        Err(why) => Err(format!("Failed to read {}: {}", path_display, why)),
22    }
23}
24
25pub fn get_file_as_byte_vec(filename: String) -> Result<Vec<u8>, String> {
26    let mut f = match File::open(&filename) {
27        Ok(file) => file,
28        Err(why) => {
29            return Err(format!("Failed to open {}: {}", filename, why));
30        }
31    };
32    let metadata = match fs::metadata(&filename) {
33        Ok(metadata) => metadata,
34        Err(why) => {
35            return Err(format!("Failed to get metadata for {}: {}", filename, why));
36        }
37    };
38    let mut buffer = vec![0; metadata.len() as usize];
39    match f.read_exact(&mut buffer) {
40        Ok(_) => {}
41        Err(why) => {
42            return Err(format!("Failed to read {}: {}", filename, why));
43        }
44    }
45
46    Ok(buffer)
47}
48
49pub fn write_to_file(filename: &String, content: Vec<u8>) {
50    let path = Path::new(&filename);
51    let path_display = path.display();
52
53    let mut file = match File::create(path) {
54        Ok(file) => file,
55        Err(why) => {
56            eprintln!("Failed to create {}: {}", path_display, why);
57            exit(1);
58        }
59    };
60
61    match file.write_all(&content) {
62        Ok(_) => {
63            info!("Successfully wrote to {}", path_display);
64        }
65        Err(why) => {
66            error!("Failed to write to {}: {}", path_display, why);
67            exit(1);
68        }
69    };
70}