1use std::fmt;
4
5use crate::bindings::{ERROR_ARITHMETIC_OVERFLOW, ERROR_INVALID_DATA};
6
7#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
12#[non_exhaustive]
13pub enum Error {
14 LengthOverflow,
16 LengthMismatch,
18 MismatchedArrayLengths,
20 MissingNulTerminator,
22 EmptyFixedLengthString,
24 Windows(u32),
26}
27
28impl Error {
29 #[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 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
76pub type Result<T> = std::result::Result<T, Error>;
78
79pub(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 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}