failed_result/
lib.rs

1#![doc = include_str!("../README.md")]
2
3use std::io::{Error as IoError, Result as IoResult};
4
5#[cfg(any(target_os = "linux", target_os = "android"))]
6pub mod linux;
7#[cfg(any(target_os = "macos"))]
8pub mod macos;
9#[cfg(windows)]
10pub mod windows;
11
12#[cfg(any(target_os = "linux", target_os = "android"))]
13pub use self::linux::*;
14#[cfg(any(target_os = "macos"))]
15pub use self::macos::*;
16#[cfg(windows)]
17pub use self::windows::*;
18
19/// Trait to convert a failed value to Result with last os error
20pub trait LastError {
21    type Output;
22
23    fn last_error(self) -> IoResult<Self::Output>;
24}
25
26/// implements [`LastError`] for Option
27impl<T> LastError for Option<T> {
28    type Output = T;
29
30    fn last_error(self) -> IoResult<Self::Output> {
31        self.ok_or_else(IoError::last_os_error)
32    }
33}
34
35/// implements [`LastError`] for bool
36impl LastError for bool {
37    type Output = bool;
38
39    fn last_error(self) -> IoResult<Self::Output> {
40        if self {
41            Ok(self)
42        } else {
43            Err(IoError::last_os_error())
44        }
45    }
46}
47
48/// implements [`LastError`] for null-pointer
49impl<T> LastError for *mut T {
50    type Output = *mut T;
51
52    fn last_error(self) -> IoResult<Self::Output> {
53        if self.is_null() {
54            Err(IoError::last_os_error())
55        } else {
56            Ok(self)
57        }
58    }
59}
60
61/// implements [`LastError`] for null-pointer
62impl<T> LastError for *const T {
63    type Output = *const T;
64
65    fn last_error(self) -> IoResult<Self::Output> {
66        if self.is_null() {
67            Err(IoError::last_os_error())
68        } else {
69            Ok(self)
70        }
71    }
72}