nvngx_sys/
error.rs

1//! The errors the NGX crate might have.
2
3use crate as bindings;
4
5/// The result type used within the crate.
6pub type Result<T = ()> = std::result::Result<T, Error>;
7
8/// The error type.
9#[derive(Debug, Clone)]
10pub enum Error {
11    /// An internal NVIDIA NGX error, not related to the crate.
12    Internal(bindings::NVSDK_NGX_Result),
13    /// Any other error which doesn't originate from the NVIDIA NGX.
14    Other(String),
15}
16
17impl std::fmt::Display for Error {
18    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19        f.write_str(&match self {
20            Self::Internal(code) => {
21                format!("Internal error: code={code}")
22            }
23            Self::Other(s) => format!("Other error: {s}"),
24        })
25    }
26}
27
28impl From<bindings::NVSDK_NGX_Result> for Error {
29    fn from(value: bindings::NVSDK_NGX_Result) -> Self {
30        Self::Internal(value)
31    }
32}
33
34impl From<String> for Error {
35    fn from(value: String) -> Self {
36        Self::Other(value)
37    }
38}
39
40impl<'a> From<&'a str> for Error {
41    fn from(value: &'a str) -> Self {
42        Self::Other(value.to_owned())
43    }
44}
45
46impl From<bindings::NVSDK_NGX_Result> for Result {
47    fn from(value: bindings::NVSDK_NGX_Result) -> Self {
48        match value {
49            bindings::NVSDK_NGX_Result::NVSDK_NGX_Result_Success => Ok(()),
50            code => Err(Error::Internal(code)),
51        }
52    }
53}
54
55impl std::fmt::Display for bindings::NVSDK_NGX_Result {
56    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57        let chars = unsafe { bindings::GetNGXResultAsString(*self as _) };
58        let length = unsafe { libc::wcslen(chars) };
59        let string = unsafe { widestring::WideCString::from_ptr(chars.cast(), length) }
60            .map_err(|_| std::fmt::Error)?;
61        let string = string.to_string().map_err(|_| std::fmt::Error)?;
62        f.write_str(&string)?;
63        // unsafe {
64        //     libc::free(chars as *mut _);
65        // }
66        Ok(())
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use crate as bindings;
73
74    #[test]
75    fn test_error_message() {
76        let string =
77            bindings::NVSDK_NGX_Result::NVSDK_NGX_Result_FAIL_FeatureNotSupported.to_string();
78        assert_eq!(string, "NVSDK_NGX_Result_FAIL_FeatureNotSupported");
79    }
80}