Skip to main content

etw_wrapper/
error.rs

1//! The error type returned by provider registration and event writing.
2
3use std::fmt;
4
5use crate::bindings::{ERROR_ARITHMETIC_OVERFLOW, ERROR_INVALID_DATA};
6
7/// An error reported while registering a provider or writing an event.
8///
9/// Every variant maps to a Win32 error code through [`Error::win32_code`], so an error can still
10/// be reported through interfaces that expect one.
11#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
12#[non_exhaustive]
13pub enum Error {
14    /// A derived length does not fit in the integer type of the field that carries it.
15    LengthOverflow,
16    /// An encoded value's length does not match the length declared by another field.
17    LengthMismatch,
18    /// Array elements sharing a single length field have differing lengths.
19    MismatchedArrayLengths,
20    /// A string field is missing its NUL terminator.
21    MissingNulTerminator,
22    /// A fixed-length string field has no room for a NUL terminator.
23    EmptyFixedLengthString,
24    /// A Windows API call failed with this Win32 error code.
25    Windows(u32),
26}
27
28impl Error {
29    /// Returns the Win32 error code that corresponds to this error.
30    ///
31    /// [`Error::LengthOverflow`] maps to `ERROR_ARITHMETIC_OVERFLOW`; the other input validation
32    /// failures map to `ERROR_INVALID_DATA`.
33    #[must_use]
34    pub const fn win32_code(&self) -> u32 {
35        match self {
36            Error::LengthOverflow => ERROR_ARITHMETIC_OVERFLOW,
37            Error::LengthMismatch
38            | Error::MismatchedArrayLengths
39            | Error::MissingNulTerminator
40            | Error::EmptyFixedLengthString => ERROR_INVALID_DATA,
41            Error::Windows(code) => *code,
42        }
43    }
44}
45
46impl fmt::Display for Error {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        match self {
49            Error::LengthOverflow => f.write_str("length does not fit in the declared length type"),
50            Error::LengthMismatch => {
51                f.write_str("value length does not match the declared length field")
52            }
53            Error::MismatchedArrayLengths => {
54                f.write_str("array elements sharing a length field have differing lengths")
55            }
56            Error::MissingNulTerminator => f.write_str("string is not NUL terminated"),
57            Error::EmptyFixedLengthString => {
58                f.write_str("fixed-length string has no room for a NUL terminator")
59            }
60            // Defers to the OS for a localized message.
61            Error::Windows(code) => {
62                fmt::Display::fmt(&std::io::Error::from_raw_os_error(*code as i32), f)
63            }
64        }
65    }
66}
67
68impl std::error::Error for Error {}
69
70impl From<Error> for std::io::Error {
71    fn from(error: Error) -> Self {
72        std::io::Error::from_raw_os_error(error.win32_code() as i32)
73    }
74}
75
76/// A specialized [`Result`](std::result::Result) for this crate's fallible operations.
77pub type Result<T> = std::result::Result<T, Error>;
78
79/// Converts a Win32 status code returned by an ETW API into a [`Result`].
80pub(crate) fn win32_result(code: u32) -> Result<()> {
81    if code == 0 {
82        Ok(())
83    } else {
84        Err(Error::Windows(code))
85    }
86}
87
88#[cfg(test)]
89mod tests {
90    use super::*;
91
92    #[test]
93    fn win32_result_maps_zero_to_success() {
94        assert_eq!(win32_result(0), Ok(()));
95        assert_eq!(win32_result(5), Err(Error::Windows(5)));
96    }
97
98    #[test]
99    fn io_error_conversion_preserves_the_win32_code() {
100        // ERROR_ACCESS_DENIED
101        let io: std::io::Error = Error::Windows(5).into();
102        assert_eq!(io.raw_os_error(), Some(5));
103
104        let io: std::io::Error = Error::LengthOverflow.into();
105        assert_eq!(io.raw_os_error(), Some(ERROR_ARITHMETIC_OVERFLOW as i32));
106    }
107
108    #[test]
109    fn windows_errors_display_the_os_message() {
110        let message = Error::Windows(5).to_string();
111        assert!(!message.is_empty());
112        assert!(!message.contains("Windows"));
113    }
114}