kernel/
utils.rs

1//! Utility functions and definitions for the kernel.
2#![cfg_attr(feature = "nightly", feature(likely_unlikely))]
3
4use core::fmt::Debug;
5
6/// These two definitions are copied from https://github.com/rust-lang/hashbrown
7#[cfg(not(feature = "nightly"))]
8#[allow(unused_imports)]
9pub(crate) use core::convert::{identity as likely, identity as unlikely};
10
11#[cfg(feature = "nightly")]
12pub(crate) use core::hint::{likely, unlikely};
13
14/// This is a macro that is used to panic when a bug is detected.
15/// It is similar to the BUG() macro in the Linux kernel. Link: [https://www.kernel.org/]()
16#[macro_export]
17macro_rules! BUG {
18    () => {
19        panic!("BUG triggered at {}:{}", file!(), line!());
20    };
21    ($msg:expr) => {
22        panic!("BUG triggered: {} at {}:{}", $msg, file!(), line!());
23    };
24}
25
26/// This is a macro that is used to panic when a condition is true.
27/// It is similar to the BUG_ON() macro in the Linux kernel.  Link: [https://www.kernel.org/]()
28#[macro_export]
29macro_rules! BUG_ON {
30    ($cond:expr) => {{
31        let cond = $cond;
32        #[allow(unused_unsafe)]
33        if unsafe { $crate::utils::unlikely(cond) } {
34            BUG!();
35        }
36    }};
37    ($cond:expr, $msg:expr) => {{
38        let cond = $cond;
39        #[allow(unused_unsafe)]
40        if unsafe { $crate::utils::unlikely(cond) } {
41            BUG!($msg);
42        }
43    }};
44}
45
46/// The error type that is returned when an error in the kernel occurs.
47#[derive(PartialEq, Eq, Clone)]
48pub enum KernelError {
49    /// The alignment is invalid.
50    InvalidAlign,
51    /// The kernel is out of memory.
52    OutOfMemory,
53    InvalidSize,
54    InvalidAddress,
55    InvalidArgument,
56    HalError(hal::Error),
57}
58
59/// Debug msg implementation for KernelError.
60impl Debug for KernelError {
61    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62        match self {
63            KernelError::InvalidAlign => write!(f, "Invalid alignment"),
64            KernelError::OutOfMemory => write!(f, "Out of memory"),
65            KernelError::InvalidSize => write!(f, "Invalid size"),
66            KernelError::InvalidAddress => write!(f, "Invalid address"),
67            KernelError::InvalidArgument => write!(f, "Invalid argument"),
68            KernelError::HalError(e) => write!(f, "{e} (in HAL)"),
69        }
70    }
71}
72
73impl From<hal::Error> for KernelError {
74    fn from(err: hal::Error) -> Self {
75        KernelError::HalError(err)
76    }
77}