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, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
11#[repr(u8)]
12pub enum PrivilegeLevel {
13    /// User / application mode (least privileged)
14    User = 0b00,
15    /// Supervisor mode
16    Supervisor = 0b01,
17    /// Machine mode (most privileged)
18    #[default]
19    Machine = 0b11,
20}
21
22impl PrivilegeLevel {
23    /// Create a privilege level from its bit representation
24    #[inline(always)]
25    pub fn from_bits(bits: u8) -> Option<Self> {
26        match bits {
27            0b00 => Some(Self::User),
28            0b01 => Some(Self::Supervisor),
29            0b11 => Some(Self::Machine),
30            _ => None,
31        }
32    }
33}