Skip to main content

ab_riscv_primitives/
privilege.rs

1//! RISC-V privilege levels
2
3/// Privilege level of the hart.
4///
5/// Variants are assigned their architectural 2-bit encoding as discriminants
6/// so that `level as u8` yields the value that appears in CSR address bits
7/// `[9:8]` and in `mstatus`/`sstatus` privilege fields.
8///
9/// The encoding `0b10` is architecturally reserved and is therefore absent.
10#[derive(Debug, Clone, Copy)]
11#[derive_const(Default, PartialEq, Eq, PartialOrd, Ord)]
12#[repr(u8)]
13pub enum PrivilegeLevel {
14    /// User / application mode (least privileged)
15    User = 0b00,
16    /// Supervisor mode
17    Supervisor = 0b01,
18    /// Machine mode (most privileged)
19    #[default]
20    Machine = 0b11,
21}
22
23impl PrivilegeLevel {
24    /// Create a privilege level from its bit representation
25    #[inline(always)]
26    pub const fn from_bits(bits: u8) -> Option<Self> {
27        match bits {
28            0b00 => Some(Self::User),
29            0b01 => Some(Self::Supervisor),
30            0b11 => Some(Self::Machine),
31            _ => None,
32        }
33    }
34
35    /// Encode to a 2-bit field value
36    pub const fn to_bits(self) -> u8 {
37        self as u8
38    }
39}