1use std::{borrow::Cow, ffi::NulError, fmt};
2
3#[derive(Debug)]
4#[non_exhaustive]
5pub enum Error {
7 Native(i32),
9 NativeAt(&'static str, i32),
11 Invalid(Cow<'static, str>),
16 Unsupported(&'static str),
18 Nul(NulError),
20 Io(std::io::Error),
22}
23pub type Result<T> = std::result::Result<T, Error>;
25impl fmt::Display for Error {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 match self {
28 Self::Native(code) => write!(f, "ncnn returned {code}"),
29 Self::NativeAt(operation, code) => write!(f, "ncnn {operation} returned {code}"),
30 Self::Invalid(message) => f.write_str(message.as_ref()),
31 Self::Unsupported(message) => write!(f, "Unsupported capability: {message}"),
32 Self::Nul(error) => error.fmt(f),
33 Self::Io(error) => error.fmt(f),
34 }
35 }
36}
37impl Error {
38 pub(crate) fn invalid(message: impl Into<Cow<'static, str>>) -> Self {
40 Self::Invalid(message.into())
41 }
42 pub fn native_code(&self) -> Option<i32> {
44 match self {
45 Self::Native(code) | Self::NativeAt(_, code) => Some(*code),
46 _ => None,
47 }
48 }
49}
50impl std::error::Error for Error {}
51impl From<NulError> for Error {
52 fn from(e: NulError) -> Self {
53 Self::Nul(e)
54 }
55}
56impl From<std::io::Error> for Error {
57 fn from(e: std::io::Error) -> Self {
58 Self::Io(e)
59 }
60}
61pub(crate) fn status_at(operation: &'static str, code: i32) -> Result<()> {
62 if code == 0 {
63 Ok(())
64 } else {
65 Err(Error::NativeAt(operation, code))
66 }
67}
68pub(crate) fn status(code: i32) -> Result<()> {
69 if code == 0 {
70 Ok(())
71 } else {
72 Err(Error::Native(code))
73 }
74}