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
|
|
|
}
|
|
|
|
|
2022-11-28 03:11:41 +00:00
|
|
|
/// read_single error
|
2023-01-10 01:24:23 +00:00
|
|
|
#[derive(Debug)]
|
2022-11-28 03:11:41 +00:00
|
|
|
pub enum ReadError<E> {
|
|
|
|
/// IO Error
|
|
|
|
Io(io::Error),
|
|
|
|
/// String parsing error
|
|
|
|
Parse(E),
|
|
|
|
}
|
|
|
|
|
2023-01-10 01:24:23 +00:00
|
|
|
impl<E: std::error::Error> std::fmt::Display for ReadError<E> {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
|
|
|
match self {
|
|
|
|
Self::Io(io) => write!(f, "io: {}", io),
|
|
|
|
Self::Parse(e) => write!(f, "parse: {}", e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<E: std::error::Error> std::error::Error for ReadError<E> {
|
|
|
|
|
|
|
|
}
|
|
|
|
|
2022-06-21 01:03:18 +01:00
|
|
|
/// Read something from a file.
|
|
|
|
/// Useful for kernel configuration files.
|
2022-11-28 03:11:41 +00:00
|
|
|
pub fn read_single<P: AsRef<Path>, D: FromStr<Err=E>, E>(path: P) -> Result<D, ReadError<E>> {
|
|
|
|
let mut file = File::open(path).map_err(ReadError::Io)?;
|
2022-06-21 01:03:18 +01:00
|
|
|
let mut string = String::new();
|
2022-11-28 03:11:41 +00:00
|
|
|
file.read_to_string(&mut string).map_err(ReadError::Io)?;
|
|
|
|
string.trim().parse().map_err(ReadError::Parse)
|
2022-06-21 01:03:18 +01:00
|
|
|
}
|