use alloc::{
format,
string::ToString,
sync::Arc,
};
use core::panic::Location;
use std::{
io,
path::{
Path,
PathBuf,
},
};
use crate::errors::{
BunsenError,
BunsenErrorKind,
LookupError,
LookupProblem,
};
pub fn io_error_kind(error: &io::Error) -> BunsenErrorKind {
match error.kind() {
io::ErrorKind::NotFound | io::ErrorKind::PermissionDenied => BunsenErrorKind::Lookup,
io::ErrorKind::TimedOut
| io::ErrorKind::ConnectionReset
| io::ErrorKind::ConnectionAborted
| io::ErrorKind::ConnectionRefused
| io::ErrorKind::Interrupted
| io::ErrorKind::WouldBlock => BunsenErrorKind::Unavailable,
io::ErrorKind::InvalidData | io::ErrorKind::UnexpectedEof => {
BunsenErrorKind::InvalidResource
}
_ => BunsenErrorKind::Sys,
}
}
fn sort_io_error(
op: &str,
path: Option<&Path>,
error: io::Error,
location: &'static Location<'static>,
) -> BunsenError {
let problem = match error.kind() {
io::ErrorKind::NotFound => Some(LookupProblem::Missing),
io::ErrorKind::PermissionDenied => Some(LookupProblem::Denied),
_ => None,
};
match (problem, path) {
(Some(problem), Some(path)) => {
let lookup = LookupError::path(path, problem).with_source(error);
let message = lookup.to_string();
BunsenError::build(
BunsenErrorKind::Lookup,
message.into(),
Some(Arc::new(lookup)),
true,
location,
)
}
_ => {
let kind = io_error_kind(&error);
let message = match path {
Some(path) => format!("{op} {}: {error}", path.display()),
None => format!("{op}: {error}"),
};
BunsenError::build(kind, message.into(), Some(Arc::new(error)), true, location)
}
}
}
#[track_caller]
pub fn sys_at(
op: &'static str,
path: impl AsRef<Path>,
) -> impl FnOnce(io::Error) -> BunsenError {
let location = Location::caller();
let path: PathBuf = path.as_ref().to_path_buf();
move |error| sort_io_error(op, Some(&path), error, location)
}
#[track_caller]
pub fn sys_op(op: &'static str) -> impl FnOnce(io::Error) -> BunsenError {
let location = Location::caller();
move |error| sort_io_error(op, None, error, location)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sorting() {
let missing = io::Error::new(io::ErrorKind::NotFound, "gone");
let e = sys_at("open", "/a/b")(missing);
assert_eq!(e.kind(), BunsenErrorKind::Lookup);
assert_eq!(e.to_string(), "/a/b: not found");
assert_eq!(
e.find::<LookupError>().unwrap().problem,
LookupProblem::Missing
);
assert!(e.find::<io::Error>().is_some());
let full = io::Error::new(io::ErrorKind::StorageFull, "disk full");
let e = sys_at("write", "/a/b")(full);
assert_eq!(e.kind(), BunsenErrorKind::Sys);
assert_eq!(e.to_string(), "write /a/b: disk full");
let timeout = io::Error::new(io::ErrorKind::TimedOut, "slow");
let e = sys_op("connect")(timeout);
assert_eq!(e.kind(), BunsenErrorKind::Unavailable);
assert_eq!(e.to_string(), "connect: slow");
}
}