usdpl-rs/usdpl-back/src/api_common/files.rs

23 lines
819 B
Rust
Raw Normal View History

2022-06-21 01:03:18 +01:00
//! Common low-level file operations
use std::fmt::Display;
use std::path::Path;
use std::fs::File;
use std::io::{Read, Write, self};
use std::str::FromStr;
/// Write something to a file.
/// Useful for kernel configuration files.
pub fn write_single<P: AsRef<Path>, D: Display>(path: P, display: D) -> Result<(), io::Error> {
let mut file = File::create(path)?;
2022-07-09 17:26:40 +01:00
write!(file, "{}", display)
2022-06-21 01:03:18 +01:00
}
/// Read something from a file.
/// Useful for kernel configuration files.
pub fn read_single<P: AsRef<Path>, D: FromStr<Err=E>, E>(path: P) -> Result<D, (Option<io::Error>, Option<E>)> {
let mut file = File::open(path).map_err(|e| (Some(e), None))?;
2022-06-21 01:03:18 +01:00
let mut string = String::new();
file.read_to_string(&mut string).map_err(|e| (Some(e), None))?;
string.trim().parse().map_err(|e| (None, Some(e)))
2022-06-21 01:03:18 +01:00
}