Skip to main content

ncnn_rust/
error.rs

1use std::{borrow::Cow, ffi::NulError, fmt};
2
3#[derive(Debug)]
4#[non_exhaustive]
5/// Failure from the native layer or from a validated Rust check.
6pub enum Error {
7    /// A native call failed without a named operation.
8    Native(i32),
9    /// A native call failed during a named operation.
10    NativeAt(&'static str, i32),
11    /// A caller argument or state failed validation.
12    ///
13    /// Borrowed text covers constant failures; owned text carries the offending names,
14    /// shapes or lengths.
15    Invalid(Cow<'static, str>),
16    /// The platform lacks the requested capability.
17    Unsupported(&'static str),
18    /// A string could not be converted to a C string.
19    Nul(NulError),
20    /// A file or buffer operation failed.
21    Io(std::io::Error),
22}
23/// Result of a fallible wrapper operation.
24pub 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    /// Builds a validation failure from constant text or from formatted detail.
39    pub(crate) fn invalid(message: impl Into<Cow<'static, str>>) -> Self {
40        Self::Invalid(message.into())
41    }
42    /// Returns the upstream ncnn status code carried by a native failure.
43    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}