1use std::fmt;
4
5use windows_sys::{
6 core::HRESULT,
7 Win32::Foundation::{GetLastError, ERROR_SUCCESS, WIN32_ERROR},
8};
9
10#[derive(Debug, Clone, PartialEq)]
12#[non_exhaustive]
13pub enum CngError {
14 InvalidHashLength,
15 UnsupportedKeyAlgorithmGroup,
16 WindowsError(u32),
17}
18
19impl fmt::Display for CngError {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 match self {
22 CngError::InvalidHashLength => write!(f, "Invalid hash length"),
23 CngError::UnsupportedKeyAlgorithmGroup => write!(f, "Unsupported key algorithm group"),
24 CngError::WindowsError(code) => write!(f, "Error code {:08x}", code),
25 }
26 }
27}
28
29impl std::error::Error for CngError {}
30
31impl CngError {
32 pub fn from_win32_error() -> Self {
33 unsafe { Self::WindowsError(GetLastError()) }
34 }
35
36 pub fn from_hresult(result: HRESULT) -> crate::Result<()> {
37 if result as WIN32_ERROR == ERROR_SUCCESS {
38 Ok(())
39 } else {
40 Err(CngError::WindowsError(result as _))
41 }
42 }
43}