zephyr/
error.rs

1// Copyright (c) 2024 Linaro LTD
2// SPDX-License-Identifier: Apache-2.0
3
4//! # Zephyr errors
5//!
6//! This module contains an `Error` and `Result` type for use in wrapped Zephyr calls.  Many
7//! operations in Zephyr return an int result where negative values correspond with errnos.
8//! Convert those to a `Result` type where the `Error` condition maps to errnos.
9//!
10//! Initially, this will just simply wrap the numeric error code, but it might make sense to make
11//! this an enum itself, however, it would probably be better to auto-generate this enum instead of
12//! trying to maintain the list manually.
13
14use core::ffi::c_int;
15use core::fmt;
16
17// This is a little messy because the constants end up as u32 from bindgen, although the values are
18// negative.
19
20/// A Zephyr error.
21///
22/// Represents an error result returned within Zephyr.
23pub struct Error(pub u32);
24
25impl core::error::Error for Error {}
26
27impl fmt::Display for Error {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        write!(f, "zephyr error errno:{}", self.0)
30    }
31}
32
33impl fmt::Debug for Error {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        write!(f, "zephyr error errno:{}", self.0)
36    }
37}
38
39/// Wraps a value with a possible Zephyr error.
40pub type Result<T> = core::result::Result<T, Error>;
41
42/// Map a return result from Zephyr into an Result.
43///
44/// Negative return results being considered errors.
45#[inline(always)]
46pub fn to_result(code: c_int) -> Result<c_int> {
47    if code < 0 {
48        Err(Error(-code as u32))
49    } else {
50        Ok(code)
51    }
52}
53
54/// Map a return result, with a void result.
55#[inline(always)]
56pub fn to_result_void(code: c_int) -> Result<()> {
57    to_result(code).map(|_| ())
58}