oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! The error type: the operating system's own error code.

use core::fmt;

use crate::sys;

/// The result of an operating system call.
pub type Result<T> = core::result::Result<T, Error>;

/// An error reported by the operating system.
///
/// It holds the system's own code, unchanged: an `errno` value on Linux, macOS
/// and WASI, a `GetLastError` or `WSAGetLastError` code on Windows.
/// [`kind`](Error::kind) classifies it portably.
///
/// The few errors oscall detects itself (a path with an interior NUL, an
/// operation the platform does not have) are reported with the code the
/// system uses for that condition.
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct Error(i32);

impl Error {
    /// Wraps a raw operating system error code.
    #[inline]
    pub const fn from_raw_os_error(code: i32) -> Self {
        Self(code)
    }

    /// The raw operating system error code.
    #[inline]
    pub const fn raw_os_error(self) -> i32 {
        self.0
    }

    /// The portable classification of this error.
    pub fn kind(self) -> ErrorKind {
        sys::ERRORS
            .iter()
            .find(|(code, _)| *code == self.0)
            .map_or(ErrorKind::Other, |(_, kind)| *kind)
    }
}

/// The error the current platform uses for `kind`.
///
/// [`ErrorKind::Other`], and a kind the platform has no code for, become its
/// generic I/O error.
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)
    }
}

/// A portable classification of [`Error`]s.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ErrorKind {
    /// The file, directory or other entity does not exist.
    NotFound,
    /// The caller lacks the permission for the operation.
    PermissionDenied,
    /// The entity already exists.
    AlreadyExists,
    /// The operation would block and the handle is non-blocking.
    WouldBlock,
    /// A non-blocking operation was started and has not completed yet.
    InProgress,
    /// The call was interrupted before it did anything; it can be retried.
    Interrupted,
    /// An argument is not valid for the operation.
    InvalidInput,
    /// The operation's deadline passed.
    TimedOut,
    /// The platform or the object does not support the operation.
    Unsupported,
    /// The system is out of memory or address space.
    OutOfMemory,
    /// The handle is closed or of the wrong type.
    BadHandle,
    /// The other end of the pipe or socket is closed.
    BrokenPipe,
    /// A directory was required and something else was found.
    NotADirectory,
    /// The operation does not apply to a directory.
    IsADirectory,
    /// The directory is not empty.
    DirectoryNotEmpty,
    /// A path or one of its components is too long, or not a valid name.
    InvalidFilename,
    /// The buffer given for the result is too small to hold it.
    BufferTooSmall,
    /// Too many symbolic links were followed.
    FilesystemLoop,
    /// The storage is full.
    StorageFull,
    /// A storage quota is exhausted.
    QuotaExceeded,
    /// The file would become larger than allowed.
    FileTooLarge,
    /// The filesystem is read-only.
    ReadOnlyFilesystem,
    /// The operation cannot cross filesystems.
    CrossesDevices,
    /// The file has too many hard links.
    TooManyLinks,
    /// The process or the system has too many open handles.
    TooManyOpenFiles,
    /// The resource is in use.
    ResourceBusy,
    /// The operation would deadlock.
    Deadlock,
    /// The handle cannot seek.
    NotSeekable,
    /// The executable file is in use.
    ExecutableFileBusy,
    /// The remote host refused the connection.
    ConnectionRefused,
    /// The remote host reset the connection.
    ConnectionReset,
    /// The connection was aborted.
    ConnectionAborted,
    /// The socket is not connected.
    NotConnected,
    /// The socket is already connected.
    AlreadyConnected,
    /// The address is already in use.
    AddrInUse,
    /// The address is not available on this host.
    AddrNotAvailable,
    /// The network is down.
    NetworkDown,
    /// The network cannot be reached.
    NetworkUnreachable,
    /// The host cannot be reached.
    HostUnreachable,
    /// The message does not fit in the buffer or in a datagram.
    MessageTooLong,
    /// The process does not exist.
    NoSuchProcess,
    /// An error with no portable classification.
    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);
    }
}