glib/
exit_code.rs
1#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
4pub struct ExitCode(u8);
5
6impl ExitCode {
7 const MIN: i32 = u8::MIN as i32;
8 const MAX: i32 = u8::MAX as i32;
9
10 pub const SUCCESS: Self = Self(libc::EXIT_SUCCESS as u8);
13
14 pub const FAILURE: Self = Self(libc::EXIT_FAILURE as u8);
17
18 pub const fn new(code: u8) -> Self {
19 Self(code)
20 }
21
22 pub const fn get(&self) -> u8 {
23 self.0
24 }
25}
26
27#[derive(Clone, Copy, PartialEq, Eq, Debug, PartialOrd, Ord)]
28pub struct InvalidExitCode(i32);
29
30impl InvalidExitCode {
31 pub const fn new(code: i32) -> Option<Self> {
32 match code {
33 ExitCode::MIN..=ExitCode::MAX => None,
34 _ => Some(Self(code)),
35 }
36 }
37
38 pub const fn get(&self) -> i32 {
39 self.0
40 }
41}
42
43impl std::fmt::Display for InvalidExitCode {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 let Self(code) = self;
46 write!(f, "{code} is not a valid glib exit code")
47 }
48}
49
50impl std::error::Error for InvalidExitCode {}
51
52impl From<u8> for ExitCode {
53 fn from(value: u8) -> Self {
54 Self(value)
55 }
56}
57
58impl TryFrom<i32> for ExitCode {
59 type Error = InvalidExitCode;
60
61 fn try_from(code: i32) -> Result<Self, Self::Error> {
62 match code {
63 ExitCode::MIN..=ExitCode::MAX => Ok(Self(code as _)),
64 _ => Err(InvalidExitCode(code)),
65 }
66 }
67}
68
69macro_rules! impl_from_exit_code_0 {
70 ($($ty:ty)*) => {
71 $(
72 impl From<ExitCode> for $ty {
73 fn from(code: ExitCode) -> Self {
74 <$ty>::from(code.0)
75 }
76 }
77 )*
78 };
79}
80
81impl_from_exit_code_0! { u8 u16 u32 u64 i16 i32 i64 std::process::ExitCode }
82
83impl std::process::Termination for ExitCode {
84 fn report(self) -> std::process::ExitCode {
85 self.into()
86 }
87}