xref: /DragonOS/kernel/crates/rbpf/src/no_std_error.rs (revision fae6e9ade46a52976ad5d099643d51cc20876448)
1*fae6e9adSlinfeng // SPDX-License-Identifier: (Apache-2.0 OR MIT)
2*fae6e9adSlinfeng 
3*fae6e9adSlinfeng //! This module provides a simple implementation of the Error struct that is
4*fae6e9adSlinfeng //! used as a drop-in replacement for `std::io::Error` when using `rbpf` in `no_std`.
5*fae6e9adSlinfeng 
6*fae6e9adSlinfeng use alloc::string::String;
7*fae6e9adSlinfeng 
8*fae6e9adSlinfeng /// Implementation of Error for no_std applications.
9*fae6e9adSlinfeng /// Ensures that the existing code can use it with the same interface
10*fae6e9adSlinfeng /// as the Error from std::io::Error.
11*fae6e9adSlinfeng #[derive(Debug)]
12*fae6e9adSlinfeng pub struct Error {
13*fae6e9adSlinfeng     #[allow(dead_code)]
14*fae6e9adSlinfeng     kind: ErrorKind,
15*fae6e9adSlinfeng     #[allow(dead_code)]
16*fae6e9adSlinfeng     error: String,
17*fae6e9adSlinfeng }
18*fae6e9adSlinfeng 
19*fae6e9adSlinfeng impl Error {
20*fae6e9adSlinfeng     /// New function exposing the same signature as `std::io::Error::new`.
21*fae6e9adSlinfeng     #[allow(dead_code)]
new<S: Into<String>>(kind: ErrorKind, error: S) -> Error22*fae6e9adSlinfeng     pub fn new<S: Into<String>>(kind: ErrorKind, error: S) -> Error {
23*fae6e9adSlinfeng         Error {
24*fae6e9adSlinfeng             kind,
25*fae6e9adSlinfeng             error: error.into(),
26*fae6e9adSlinfeng         }
27*fae6e9adSlinfeng     }
28*fae6e9adSlinfeng }
29*fae6e9adSlinfeng 
30*fae6e9adSlinfeng /// The current version of `rbpf` only uses the [`Other`](ErrorKind::Other) variant
31*fae6e9adSlinfeng /// from the [std::io::ErrorKind] enum. If a dependency on other variants were
32*fae6e9adSlinfeng /// introduced in the future, this enum needs to be updated accordingly to maintain
33*fae6e9adSlinfeng /// compatibility with the real `ErrorKind`. The reason all available variants
34*fae6e9adSlinfeng /// aren't included in the first place is that [std::io::ErrorKind] exposes
35*fae6e9adSlinfeng /// 40 variants, and not all of them are meaningful under `no_std`.
36*fae6e9adSlinfeng #[derive(Debug)]
37*fae6e9adSlinfeng pub enum ErrorKind {
38*fae6e9adSlinfeng     /// The no_std code only uses this variant.
39*fae6e9adSlinfeng     #[allow(dead_code)]
40*fae6e9adSlinfeng     Other,
41*fae6e9adSlinfeng }
42