use core::fmt;
use crate::sys;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Error(i32);
impl Error {
#[inline]
pub const fn from_raw_os_error(code: i32) -> Self {
Self(code)
}
#[inline]
pub const fn raw_os_error(self) -> i32 {
self.0
}
pub fn kind(self) -> ErrorKind {
sys::ERRORS
.iter()
.find(|(code, _)| *code == self.0)
.map_or(ErrorKind::Other, |(_, kind)| *kind)
}
}
impl From<ErrorKind> for Error {
fn from(kind: ErrorKind) -> Self {
let code = sys::ERRORS
.iter()
.find(|(_, k)| *k == kind)
.map_or(sys::OTHER_ERROR, |(code, _)| *code);
Self(code)
}
}
impl PartialEq<ErrorKind> for Error {
fn eq(&self, kind: &ErrorKind) -> bool {
self.kind() == *kind
}
}
impl fmt::Debug for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Error")
.field("code", &self.0)
.field("kind", &self.kind())
.finish()
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} (os error {})", self.kind().description(), self.0)
}
}
impl core::error::Error for Error {}
#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
fn from(error: Error) -> Self {
Self::from_raw_os_error(error.0)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
NotFound,
PermissionDenied,
AlreadyExists,
WouldBlock,
InProgress,
Interrupted,
InvalidInput,
TimedOut,
Unsupported,
OutOfMemory,
BadHandle,
BrokenPipe,
NotADirectory,
IsADirectory,
DirectoryNotEmpty,
InvalidFilename,
BufferTooSmall,
FilesystemLoop,
StorageFull,
QuotaExceeded,
FileTooLarge,
ReadOnlyFilesystem,
CrossesDevices,
TooManyLinks,
TooManyOpenFiles,
ResourceBusy,
Deadlock,
NotSeekable,
ExecutableFileBusy,
ConnectionRefused,
ConnectionReset,
ConnectionAborted,
NotConnected,
AlreadyConnected,
AddrInUse,
AddrNotAvailable,
NetworkDown,
NetworkUnreachable,
HostUnreachable,
MessageTooLong,
NoSuchProcess,
Other,
}
impl ErrorKind {
fn description(self) -> &'static str {
match self {
Self::NotFound => "entity not found",
Self::PermissionDenied => "permission denied",
Self::AlreadyExists => "entity already exists",
Self::WouldBlock => "operation would block",
Self::InProgress => "operation in progress",
Self::Interrupted => "operation interrupted",
Self::InvalidInput => "invalid input",
Self::TimedOut => "timed out",
Self::Unsupported => "unsupported operation",
Self::OutOfMemory => "out of memory",
Self::BadHandle => "bad handle",
Self::BrokenPipe => "broken pipe",
Self::NotADirectory => "not a directory",
Self::IsADirectory => "is a directory",
Self::DirectoryNotEmpty => "directory not empty",
Self::InvalidFilename => "invalid filename",
Self::BufferTooSmall => "buffer too small",
Self::FilesystemLoop => "filesystem loop",
Self::StorageFull => "no storage space",
Self::QuotaExceeded => "quota exceeded",
Self::FileTooLarge => "file too large",
Self::ReadOnlyFilesystem => "read-only filesystem",
Self::CrossesDevices => "cross-device operation",
Self::TooManyLinks => "too many links",
Self::TooManyOpenFiles => "too many open files",
Self::ResourceBusy => "resource busy",
Self::Deadlock => "deadlock",
Self::NotSeekable => "not seekable",
Self::ExecutableFileBusy => "executable file busy",
Self::ConnectionRefused => "connection refused",
Self::ConnectionReset => "connection reset",
Self::ConnectionAborted => "connection aborted",
Self::NotConnected => "not connected",
Self::AlreadyConnected => "already connected",
Self::AddrInUse => "address in use",
Self::AddrNotAvailable => "address not available",
Self::NetworkDown => "network down",
Self::NetworkUnreachable => "network unreachable",
Self::HostUnreachable => "host unreachable",
Self::MessageTooLong => "message too long",
Self::NoSuchProcess => "no such process",
Self::Other => "other error",
}
}
}
impl fmt::Display for ErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.description())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kinds_round_trip() {
for &(code, kind) in sys::ERRORS {
assert_eq!(Error::from_raw_os_error(code).kind(), kind);
assert_eq!(Error::from(kind).kind(), kind);
}
assert_eq!(Error::from(ErrorKind::Other).kind(), ErrorKind::Other);
}
}