1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#![doc = include_str!("../README.md")]

use std::io::{Error as IoError, Result as IoResult};

#[cfg(any(target_os = "linux", target_os = "android"))]
pub mod linux;
#[cfg(any(target_os = "macos"))]
pub mod macos;
#[cfg(windows)]
pub mod windows;

#[cfg(any(target_os = "linux", target_os = "android"))]
pub use self::linux::*;
#[cfg(any(target_os = "macos"))]
pub use self::macos::*;
#[cfg(windows)]
pub use self::windows::*;

/// Trait to convert a failed value to Result with last os error
pub trait LastError {
    type Output;

    fn last_error(self) -> IoResult<Self::Output>;
}

/// implements LastError for None
impl<T> LastError for Option<T> {
    type Output = T;

    fn last_error(self) -> IoResult<Self::Output> {
        self.ok_or_else(IoError::last_os_error)
    }
}

/// implements [`LastError`] for bool
impl LastError for bool {
    type Output = bool;

    fn last_error(self) -> IoResult<Self::Output> {
        if self {
            Ok(self)
        } else {
            Err(IoError::last_os_error())
        }
    }
}

/// implements [`LastError`] for null-pointer
impl<T> LastError for *mut T {
    type Output = *mut T;

    fn last_error(self) -> IoResult<Self::Output> {
        if self.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(self)
        }
    }
}

/// implements [`LastError`] for null-pointer
impl<T> LastError for *const T {
    type Output = *const T;

    fn last_error(self) -> IoResult<Self::Output> {
        if self.is_null() {
            Err(IoError::last_os_error())
        } else {
            Ok(self)
        }
    }
}