Skip to main content

dolang_winterop/
error.rs

1//! Win32 error code name/value lookup, generated from MS-ERREF.
2//!
3//! The lookup table is static and works on non-Windows targets as well, which
4//! is useful when decoding an error returned by a remote Windows peer.
5
6macro_rules! error_codes {
7    (
8        $by_code:ident,
9        $by_name:ident,
10        $ty:ty,
11        { $($value:literal => $name:literal,)* },
12        { $($alias:literal => $alias_value:literal,)* }
13    ) => {
14        pub(crate) static $by_code: phf::Map<$ty, &'static str> = phf::phf_map! {
15            $($value => $name,)*
16        };
17        pub(crate) static $by_name: phf::Map<&'static str, $ty> = phf::phf_map! {
18            $($name => $value,)*
19            $($alias => $alias_value,)*
20        };
21    };
22}
23
24mod generated;
25
26/// Looks up the symbolic name of a Win32 error code (e.g.
27/// `ERROR_FILE_NOT_FOUND` for `2`).
28///
29/// The name is the Win32 symbolic constant, not a localized system message.
30pub fn win_error_name(code: u32) -> Option<&'static str> {
31    generated::WIN_ERROR_BY_CODE.get(&code).copied()
32}
33
34/// Looks up the numeric value of a Win32 error code by its symbolic name
35/// (e.g. `2` for `ERROR_FILE_NOT_FOUND`), including known aliases.
36///
37/// Matching is exact and case-sensitive.
38pub fn win_error_code(name: &str) -> Option<u32> {
39    generated::WIN_ERROR_BY_NAME.get(name).copied()
40}
41
42#[cfg(test)]
43mod tests {
44    use super::{win_error_code, win_error_name};
45
46    #[test]
47    fn known_codes_round_trip() {
48        assert_eq!(win_error_name(2), Some("ERROR_FILE_NOT_FOUND"));
49        assert_eq!(win_error_code("ERROR_FILE_NOT_FOUND"), Some(2));
50    }
51
52    #[test]
53    fn unknown_code_returns_none() {
54        assert_eq!(win_error_name(u32::MAX), None);
55        assert_eq!(win_error_code("NOT_A_REAL_ERROR_CODE"), None);
56    }
57}