forked from jojonv/rust-win32error
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.rs
227 lines (193 loc) · 5.59 KB
/
lib.rs
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
221
222
223
224
225
226
227
//! Error-like wrapper around win32 GetLastError and FormatMessage
extern crate winapi;
extern crate kernel32;
use std::ptr;
use std::fmt;
use std::error::Error;
use kernel32::{GetLastError, FormatMessageW};
use winapi::FORMAT_MESSAGE_IGNORE_INSERTS;
use winapi::FORMAT_MESSAGE_FROM_SYSTEM;
use winapi::FORMAT_MESSAGE_ARGUMENT_ARRAY;
const UNKNOWN_ERROR_TEXT: &'static str = "Unknown error";
/// Generic wrapper around Result type
///
/// # Examples
///
/// ```
/// use win32_error::*;
/// fn get_error() -> Win32Result<u32> {
/// Err(Win32Error::new())
/// }
/// ```
pub type Win32Result<T> = Result<T, Win32Error>;
#[derive(Debug, Clone)]
pub struct Win32Error {
// Error code returned by GetLastError or passed as an arg
error_code: u32,
// Message returned by FormatMessage
description: Option<String>,
}
fn init_from_error_code(errno: u32) -> Win32Error {
unsafe {
let mut buff = [0u16; 256];
let buff_size = 256;
// Should be zero or num of chars copied
let chars_copied = FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_ARGUMENT_ARRAY,
ptr::null(),
errno,
0,
buff.as_mut_ptr(),
(buff_size + 1) as u32,
ptr::null_mut());
// Very likely wrong err number was passed, and no message exists
if chars_copied == 0 {
return Win32Error {
error_code: errno,
description: None,
};
}
// Remove newline - "\r\n" and punctuation or space from the message
let mut curr_char = chars_copied as usize;
while curr_char > 0 {
let ch = buff[curr_char];
if ch >= ' ' as u16 {
break;
}
curr_char -= 1;
}
let err_msg = String::from_utf16(&buff);
let description = match err_msg {
Ok(s) => Some(s),
_ => None,
};
Win32Error {
error_code: errno,
description: description,
}
}
}
macro_rules! impl_from_trait
{
($($t:ty), +) =>
{
$(
impl From<$t> for Win32Error
{
fn from(errno: $t) -> Self
{
init_from_error_code(errno as u32)
}
}
)+
};
}
macro_rules! impl_into_trait
{
($($t:ty), +) =>
{
$(
impl Into<$t> for Win32Error
{
fn into(self) -> $t
{
self.error_code as $t
}
}
)+
};
}
impl_from_trait!(i32, i16, i8, u32, u16, u8);
impl_into_trait!(i32, i16, i8, u32, u16, u8);
// Type is immutable
//
unsafe impl Sync for Win32Error {}
unsafe impl Send for Win32Error {}
impl fmt::Display for Win32Error {
/// Prints an error description in the following format:
/// **Error code**: **Error message**, eg. 5: Access denied
///
/// # Examples
///
/// ```
/// use win32_error::*;
/// let err = Win32Error::new();
/// println!("{}", err);
/// ```
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self.description.as_ref() {
Some(s) => format!("{}: {}", self.error_code, s),
None => format!("{}: {}", self.error_code, UNKNOWN_ERROR_TEXT),
}
.fmt(f)
}
}
impl Win32Error {
/// Initializes new Win32Error instance.
/// Function behind the scenes calls native GetLastError, and uses error
/// code it returned.
///
/// # Examples
///
/// ```
/// use win32_error::*;
/// let err = Win32Error::new();
/// ```
pub fn new() -> Self {
Self::from(unsafe { GetLastError() })
}
/// Retrieves error code returned by GetLastError, or one that was passed
/// through `std::convert::From::from` call
/// # Examples
///
/// ```
/// use win32_error::*;
/// let err = Win32Error::new();
/// assert_eq!(err.get_error_code(), 0);
/// ```
pub fn get_error_code(&self) -> u32 {
self.error_code
}
}
/// Retrieves localized description of the error, with one exception that's
/// description of the error couldn't be retrieved, in which case
/// *Unknown error* (in english) is returned.
impl Error for Win32Error {
fn description(&self) -> &str {
match self.description.as_ref() {
Some(s) => s,
None => UNKNOWN_ERROR_TEXT,
}
}
fn cause(&self) -> Option<&Error> {
None
}
}
#[cfg(test)]
mod test {
use std::error::Error;
use super::*;
// ugly duplication
const UNKNOWN_ERROR_TEXT: &'static str = "Unknown error";
#[test]
fn win32error_new_test() {
let err = Win32Error::new();
assert_eq!(0, err.get_error_code());
}
// Test whether passed error code is returned from get_error_code
#[test]
#[allow(unused_variables)]
fn win32error_from_test_unknown_error_code() {
let errno = 99999;
let err = Win32Error::from(errno);
assert_eq!(err.get_error_code(), errno);
}
#[test]
#[allow(unused_variables)]
fn win32error_from_test_unknown_error_description() {
let errno = 99999;
let err = Win32Error::from(errno);
assert_eq!(err.description(), UNKNOWN_ERROR_TEXT);
}
}