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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
use crate::ffi;
use std::error;
use std::ffi::CStr;
use std::fmt;
use std::io;
use std::result;

macro_rules! raw_ffi {
    ($func:ident ($($arg:expr),*)) => ({
        #[allow(unused_unsafe)]
        unsafe { ffi::$func($($arg),*) }
    })
}

macro_rules! ffi {
    ($func:ident ($($arg:expr),*)) => ({
        let result = raw_ffi!($func($($arg),*));
        crate::error::IntoResult::into_result(result)
    })
}

macro_rules! ffi_check {
    ($func:ident ($($arg:expr),*) != $error:expr) => ({
        let result = raw_ffi!($func($($arg),*));
        if result != $error {
            Ok(result)
        } else {
            Err(crate::Error::last())
        }
    })
}

pub type Result<T> = result::Result<T, Error>;

pub(crate) trait IntoResult: Sized {
    fn into_result(self) -> Result<Self>;
}

impl IntoResult for libc::c_int {
    #[inline]
    fn into_result(self) -> Result<Self> {
        if self < 0 {
            Err(Error::last())
        } else {
            Ok(self)
        }
    }
}

impl IntoResult for isize {
    #[inline]
    fn into_result(self) -> Result<Self> {
        if self < 0 {
            Err(Error::last())
        } else {
            Ok(self)
        }
    }
}

impl<T> IntoResult for *const T {
    #[inline]
    fn into_result(self) -> Result<Self> {
        if self.is_null() {
            Err(Error::last())
        } else {
            Ok(self)
        }
    }
}

impl<T> IntoResult for *mut T {
    #[inline]
    fn into_result(self) -> Result<Self> {
        if self.is_null() {
            Err(Error::last())
        } else {
            Ok(self)
        }
    }
}

#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
}

#[derive(Debug)]
enum ErrorKind {
    Dw(libc::c_int),
    Io(io::Error),
}

impl From<io::Error> for Error {
    fn from(error: io::Error) -> Error {
        Error {
            kind: ErrorKind::Io(error),
        }
    }
}

impl Error {
    #[inline]
    pub fn last() -> Error {
        let errno = raw_ffi!(dwarf_errno());
        Error {
            kind: ErrorKind::Dw(errno),
        }
    }

    #[inline]
    pub fn check() -> Option<Error> {
        let error = Error::last();
        if let ErrorKind::Dw(0) = error.kind {
            None
        } else {
            Some(error)
        }
    }
}

#[inline]
fn errmsg(errno: libc::c_int) -> &'static CStr {
    // Normalize 0 to -1, which behaves the same except it always returns a legal string
    let errno = match errno {
        0 => -1,
        e => e,
    };
    let msg = raw_ffi!(dwarf_errmsg(errno));
    unsafe { CStr::from_ptr(msg) }
}

impl error::Error for Error {
    #[inline]
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match self.kind {
            ErrorKind::Dw(_) => None,
            ErrorKind::Io(ref error) => Some(error),
        }
    }
}

impl fmt::Display for Error {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.kind {
            ErrorKind::Dw(errno) => {
                let msg = errmsg(errno);
                match msg.to_str() {
                    Ok(s) => fmt::Display::fmt(s, f),
                    Err(_) => fmt::Debug::fmt(msg, f),
                }
            }
            ErrorKind::Io(ref error) => fmt::Display::fmt(&error, f),
        }
    }
}