|
| 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 | +
|
| 14 | +use core::ffi::c_int; |
| 15 | +use 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. |
| 23 | +pub struct Error(pub u32); |
| 24 | + |
| 25 | +impl core::error::Error for Error {} |
| 26 | + |
| 27 | +impl 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 | + |
| 33 | +impl 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. |
| 40 | +pub 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 | +pub fn to_result(code: c_int) -> Result<c_int> { |
| 46 | + if code < 0 { |
| 47 | + Err(Error(code as u32)) |
| 48 | + } else { |
| 49 | + Ok(code) |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +/// Map a return result, with a void result. |
| 54 | +pub fn to_result_void(code: c_int) -> Result<()> { |
| 55 | + to_result(code).map(|_| ()) |
| 56 | +} |
0 commit comments