use crate::{VmMeta, VPN};
use core::fmt;
#[derive(Clone, Copy)]
pub struct Pos<Meta: VmMeta> {
pub vpn: VPN<Meta>,
pub level: usize,
}
impl<Meta: VmMeta> Pos<Meta> {
#[inline]
pub const fn new(vpn: VPN<Meta>, level: usize) -> Self {
Self { vpn, level }
}
#[inline]
pub const fn stop() -> Self {
Self {
vpn: VPN::ZERO,
level: Meta::MAX_LEVEL + 1,
}
}
#[inline]
pub fn prev(self) -> Self {
let delta = match self.level {
0 => 1,
n => Meta::pages_in_table(n - 1),
};
match self.vpn.val().checked_sub(delta) {
Some(vpn) => Self {
vpn: VPN::new(vpn),
..self
},
None => panic!("prev: vpn overflow"),
}
}
#[inline]
pub fn next(self) -> Self {
let delta = match self.level {
0 => 1,
n => Meta::pages_in_table(n - 1),
};
match self.vpn.val().checked_add(delta) {
Some(vpn) => Self {
vpn: VPN::new(vpn),
..self
},
None => panic!("next: vpn overflow"),
}
}
#[inline]
pub fn up(self) -> Self {
match self.level.checked_add(1) {
Some(level) => Self { level, ..self },
None => panic!("up: level overflow"),
}
}
#[inline]
pub fn down(self) -> Self {
match self.level.checked_sub(1) {
Some(level) => Self { level, ..self },
None => panic!("down: level overflow"),
}
}
}
impl<Meta: VmMeta> fmt::Debug for Pos<Meta> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"Pos {{ vpn = {:#x}, level = {:#x} }}",
self.vpn.val(),
self.level
)
}
}