cubeb_core/
error.rs

1use ffi;
2use std::ffi::NulError;
3use std::os::raw::c_int;
4use std::{error, fmt};
5
6pub type Result<T> = ::std::result::Result<T, Error>;
7
8/// An enumeration of possible errors that can happen when working with cubeb.
9#[derive(PartialEq, Eq, Clone, Debug, Copy)]
10pub enum Error {
11    /// GenericError
12    Error = ffi::CUBEB_ERROR as isize,
13    /// Requested format is invalid
14    InvalidFormat = ffi::CUBEB_ERROR_INVALID_FORMAT as isize,
15    /// Requested parameter is invalid
16    InvalidParameter = ffi::CUBEB_ERROR_INVALID_PARAMETER as isize,
17    /// Requested operation is not supported
18    NotSupported = ffi::CUBEB_ERROR_NOT_SUPPORTED as isize,
19    /// Requested device is unavailable
20    DeviceUnavailable = ffi::CUBEB_ERROR_DEVICE_UNAVAILABLE as isize,
21}
22
23impl Error {
24    pub fn wrap(code: c_int) -> Result<()> {
25        let inner = match code {
26            ffi::CUBEB_OK => return Ok(()),
27            ffi::CUBEB_ERROR_INVALID_FORMAT => Error::InvalidFormat,
28            ffi::CUBEB_ERROR_INVALID_PARAMETER => Error::InvalidParameter,
29            ffi::CUBEB_ERROR_NOT_SUPPORTED => Error::NotSupported,
30            ffi::CUBEB_ERROR_DEVICE_UNAVAILABLE => Error::DeviceUnavailable,
31            // Everything else is just the generic error
32            _ => {
33                debug_assert!(code == Error::Error as c_int);
34                Error::Error
35            }
36        };
37
38        Err(inner)
39    }
40}
41
42impl error::Error for Error {
43    fn description(&self) -> &str {
44        match self {
45            Error::Error => "Error",
46            Error::InvalidFormat => "Invalid format",
47            Error::InvalidParameter => "Invalid parameter",
48            Error::NotSupported => "Not supported",
49            Error::DeviceUnavailable => "Device unavailable",
50        }
51    }
52}
53
54impl fmt::Display for Error {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        write!(f, "{self:?}")
57    }
58}
59
60impl From<NulError> for Error {
61    fn from(_: NulError) -> Error {
62        Error::Error
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use ffi;
70
71    #[test]
72    fn test_from_raw() {
73        macro_rules! test {
74            ( $($raw:ident => $err:ident),* ) => {{
75                $(
76                    let e = Error::wrap(ffi::$raw);
77                    assert_eq!(e.unwrap_err() as c_int, ffi::$raw);
78                )*
79            }};
80        }
81        test!(CUBEB_ERROR => Error,
82              CUBEB_ERROR_INVALID_FORMAT => InvalidFormat,
83              CUBEB_ERROR_INVALID_PARAMETER => InvalidParameter,
84              CUBEB_ERROR_NOT_SUPPORTED => NotSupported,
85              CUBEB_ERROR_DEVICE_UNAVAILABLE => DeviceUnavailable
86        );
87    }
88}