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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
use alloc::format;
use alloc::string::*;
use core::{
fmt::{self, Debug, Display, Formatter},
num::TryFromIntError,
};
use crate::{bindings, util::cstring::from_cstring_raw};
pub enum Error {
System(i32),
Custom(String),
}
impl From<rcstring::Error> for Error {
fn from(err: rcstring::Error) -> Self {
Error::Custom(format!("{:?}", err))
}
}
impl From<TryFromIntError> for Error {
fn from(err: TryFromIntError) -> Self {
Error::Custom(format!("{:?}", err))
}
}
impl<T> From<Error> for Result<T, Error> {
#[inline]
fn from(err: Error) -> Self {
Err(err)
}
}
impl Debug for Error {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Error::System(n) => write!(f, "System({}) [{}]", n, unsafe {
from_cstring_raw(libc::strerror(*n))
}),
Error::Custom(s) => write!(f, "Custom({:?})", s),
}
}
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Error::System(n) => Display::fmt(unsafe { &from_cstring_raw(libc::strerror(*n)) }, f),
Error::Custom(s) => Display::fmt(s, f),
}
}
}
pub trait SentinelError: Sized {
fn check(self) -> Result<Self, Error>;
}
impl SentinelError for i32 {
fn check(self) -> Result<Self, Error> {
if self == bindings::PROS_ERR_ {
Err(from_errno())
} else {
Ok(self)
}
}
}
impl SentinelError for f64 {
fn check(self) -> Result<Self, Error> {
if self == bindings::PROS_ERR_F_ {
Err(from_errno())
} else {
Ok(self)
}
}
}
impl<T> SentinelError for *mut T {
fn check(self) -> Result<Self, Error> {
if self.is_null() {
Err(from_errno())
} else {
Ok(self)
}
}
}
extern "C" {
fn __errno() -> *mut i32;
}
#[inline]
pub fn get_errno() -> libc::c_int {
unsafe { *__errno() }
}
#[inline]
pub fn from_errno() -> Error {
Error::System(get_errno())
}