Skip to main content

ohos_window_manager_binding/
error.rs

1use std::fmt::{Display, Formatter};
2
3use ohos_native_window_manager_sys::WindowManager_ErrorCode_OK;
4
5pub type Result<T> = std::result::Result<T, Error>;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum Error {
9    Native(i64),
10    UnexpectedNull,
11    InteriorNul,
12}
13
14impl Error {
15    pub const fn code(&self) -> Option<i64> {
16        match self {
17            Self::Native(code) => Some(*code),
18            Self::UnexpectedNull | Self::InteriorNul => None,
19        }
20    }
21}
22
23impl Display for Error {
24    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
25        match self {
26            Self::Native(code) => write!(f, "window manager error code {code}"),
27            Self::UnexpectedNull => f.write_str("window manager returned a null pointer"),
28            Self::InteriorNul => f.write_str("string contains an interior NUL byte"),
29        }
30    }
31}
32
33impl std::error::Error for Error {}
34
35#[cfg(any(feature = "api-15", test))]
36pub(crate) fn check(code: i32) -> Result<()> {
37    if i64::from(code) == i64::from(WindowManager_ErrorCode_OK) {
38        Ok(())
39    } else {
40        Err(Error::Native(i64::from(code)))
41    }
42}
43
44pub(crate) fn check_status(code: u32) -> Result<()> {
45    if code == WindowManager_ErrorCode_OK {
46        Ok(())
47    } else {
48        Err(Error::Native(i64::from(code)))
49    }
50}
51
52#[cfg(test)]
53mod tests {
54    use super::*;
55
56    #[test]
57    fn preserves_signed_native_status() {
58        assert_eq!(check(0), Ok(()));
59        assert_eq!(check(-7), Err(Error::Native(-7)));
60        assert_eq!(check(801), Err(Error::Native(801)));
61        assert_eq!(
62            check(-7).unwrap_err().to_string(),
63            "window manager error code -7"
64        );
65    }
66
67    #[test]
68    fn preserves_unsigned_native_status() {
69        assert_eq!(check_status(0), Ok(()));
70        assert_eq!(check_status(1000), Err(Error::Native(1000)));
71    }
72}