use core::fmt;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug)]
pub enum Error {
UnmappedRegion,
InvalidParameter(&'static str),
ProcfsInput(alloc::string::String),
SystemCall(i32),
MachCall(i32),
}
impl fmt::Display for Error {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::UnmappedRegion => write!(f, "Queried memory is unmapped"),
Error::InvalidParameter(param) => write!(f, "Invalid parameter value: {param}"),
Error::ProcfsInput(input) => write!(f, "Invalid procfs input: {input}"),
#[cfg(feature = "std")]
Error::SystemCall(code) => {
let err = std::io::Error::from_raw_os_error(*code);
write!(f, "System call failed: {err}")
}
#[cfg(not(feature = "std"))]
Error::SystemCall(code) => write!(f, "System call failed: {code}"),
Error::MachCall(code) => write!(f, "macOS kernel call failed: {code}"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for Error {}
#[cfg(feature = "std")]
impl From<Error> for std::io::Error {
#[inline]
fn from(error: Error) -> Self {
match error {
Error::SystemCall(code) => Self::from_raw_os_error(code),
other => Self::other(other),
}
}
}
impl Error {
#[inline]
pub(crate) fn last_os_error() -> Self {
Self::SystemCall(last_os_error_code())
}
#[inline]
pub fn raw_os_error(&self) -> Option<i32> {
match *self {
Error::SystemCall(code) => Some(code),
_ => None,
}
}
#[cfg(feature = "std")]
#[inline]
pub fn as_io_error(&self) -> Option<std::io::Error> {
self.raw_os_error().map(std::io::Error::from_raw_os_error)
}
#[cfg(feature = "std")]
#[inline]
pub fn into_io_error(self) -> std::io::Error {
self.into()
}
}
#[inline]
fn last_os_error_code() -> i32 {
#[cfg(unix)]
{
#[cfg(any(target_os = "linux", target_os = "hurd", target_os = "fuchsia"))]
unsafe {
*libc::__errno_location()
}
#[cfg(any(target_os = "android", target_os = "netbsd", target_os = "openbsd"))]
unsafe {
*libc::__errno()
}
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "dragonfly"
))]
unsafe {
*libc::__error()
}
#[cfg(any(target_os = "illumos", target_os = "solaris"))]
unsafe {
*libc::___errno()
}
#[cfg(not(any(
target_os = "linux",
target_os = "android",
target_os = "hurd",
target_os = "fuchsia",
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly",
target_os = "illumos",
target_os = "solaris"
)))]
{
0
}
}
#[cfg(windows)]
{
unsafe { windows_sys::Win32::Foundation::GetLastError() as i32 }
}
#[cfg(not(any(unix, windows)))]
{
0
}
}