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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
use failure::{Backtrace, Context, Fail};
use crate::d3d::{Blob, IBlob};
use winapi::um::d3dcommon::ID3DBlob;
use winapi::ctypes::c_void;
use winapi::um::winbase::*;
use winapi::um::winnt::HRESULT;
use com_ptr::ComPtr;

#[derive(Clone, PartialEq, Eq, Debug, Fail)]
pub enum HResultKind {
    #[fail(display = "0x{:x}", 0)]
    Successed(HRESULT),
    #[fail(display = "0x{:x}", 0)]
    Failed(HRESULT),
}
impl HResultKind {
    fn is_successed(&self) -> bool {
        match self {
            HResultKind::Successed(_) => true,
            HResultKind::Failed(_) => false,
        }
    }
    fn is_failed(&self) -> bool {
        !self.is_successed()
    }
    fn code(&self) -> HRESULT {
        match self {
            HResultKind::Successed(v) => v,
            HResultKind::Failed(v) => v,
        }
        .clone()
    }
}
impl From<HRESULT> for HResultKind {
    fn from(src: HRESULT) -> HResultKind {
        if src < 0 {
            HResultKind::Failed(src)
        } else {
            HResultKind::Successed(src)
        }
    }
}

/// wrapped around `HRESULT`
#[derive(Debug)]
pub struct HResult {
    inner: Context<HResultKind>,
}
impl HResult {
    pub fn new(inner: Context<HResultKind>) -> HResult {
        HResult { inner }
    }
    pub fn kind(&self) -> &HResultKind {
        self.inner.get_context()
    }
    pub fn is_successed(&self) -> bool {
        self.kind().is_successed()
    }
    pub fn is_failed(&self) -> bool {
        self.kind().is_failed()
    }
    pub fn code(&self) -> HRESULT {
        self.kind().code()
    }
}
impl Fail for HResult {
    fn cause(&self) -> Option<&dyn Fail> {
        self.inner.cause()
    }
    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}
impl std::fmt::Display for HResult {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let msg = unsafe {
            let mut p: *mut u16 = std::ptr::null_mut();
            let len = FormatMessageW(
                FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
                std::ptr::null(),
                std::mem::transmute(self.code()),
                0,
                std::mem::transmute(&mut p),
                0,
                std::ptr::null_mut(),
            ) as usize;
            if len == 0 {
                return Err(std::fmt::Error);
            }
            let msg = String::from_utf16(std::slice::from_raw_parts(p, len - 1));
            LocalFree(p as *mut c_void);
            if let Err(_) = msg {
                return Err(std::fmt::Error);
            }
            msg.unwrap()
        };
        write!(f, "{}: {}", self.inner, msg)
    }
}
impl From<HRESULT> for HResult {
    fn from(code: HRESULT) -> HResult {
        HResult {
            inner: Context::new(code.into()),
        }
    }
}
impl From<HResultKind> for HResult {
    fn from(kind: HResultKind) -> HResult {
        HResult {
            inner: Context::new(kind),
        }
    }
}
impl From<Context<HResultKind>> for HResult {
    fn from(inner: Context<HResultKind>) -> HResult {
        HResult { inner }
    }
}
impl PartialEq for HResult {
    fn eq(&self, other: &Self) -> bool {
        self.kind() == other.kind()
    }
}
impl PartialEq<HRESULT> for HResult {
    fn eq(&self, other: &HRESULT) -> bool {
        self.code() == *other
    }
}
impl PartialEq<HResultKind> for HResult {
    fn eq(&self, other: &HResultKind) -> bool {
        self.kind() == other
    }
}

pub fn hresult<T>(obj: T, res: HRESULT) -> Result<T, HResult> {
    com_ptr::hresult(obj, res).map_err(|res| res.into())
}

#[derive(Debug, Fail)]
pub struct ErrorMessageObject {
    hresult: HResult,
    message: Option<String>,
}
impl ErrorMessageObject {
    pub(crate) fn new(hresult: HResult, message: *mut ID3DBlob) -> Self {
        let msg = if message != std::ptr::null_mut() {
            unsafe { Some(Blob(ComPtr::from_raw(message))) }
        } else {
            None
        };
        Self {
            hresult,
            message: if let Some(blob) = msg {
                if let Ok(cstr) = blob.as_cstr() {
                    if let Ok(s) = cstr.to_str() {
                        Some(s.into())
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            },
        }
    }
}
impl std::fmt::Display for ErrorMessageObject {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if let Some(s) = &self.message {
            write!(f, "{}", s)
        } else {
            write!(f, "{}", self.hresult)
        }
    }
}

#[derive(Debug)]
pub struct ErrorMessage {
    inner: Context<ErrorMessageObject>,
}
impl ErrorMessage {
    pub fn new(inner: Context<ErrorMessageObject>) -> Self {
        Self { inner }
    }
    pub fn hresult(&self) -> &HResult {
        &self.inner.get_context().hresult
    }
    pub fn message(&self) -> Option<&str> {
        if let Some(s) = &self.inner.get_context().message {
            Some(s.as_str())
        } else {
            None
        }
    }
}
impl Fail for ErrorMessage {
    fn cause(&self) -> Option<&dyn Fail> {
        self.inner.cause()
    }
    fn backtrace(&self) -> Option<&Backtrace> {
        self.inner.backtrace()
    }
}
impl std::fmt::Display for ErrorMessage {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(f, "{}", self.inner.get_context())
    }
}
impl From<ErrorMessageObject> for ErrorMessage {
    fn from(src: ErrorMessageObject) -> ErrorMessage {
        ErrorMessage::new(Context::new(src))
    }
}
impl From<Context<ErrorMessageObject>> for ErrorMessage {
    fn from(src: Context<ErrorMessageObject>) -> ErrorMessage {
        ErrorMessage::new(src)
    }
}