1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
use core::ops::{Add, Sub};
use crate::{
constant::{PAGE_SIZE, PAGE_SIZE_BIT},
mem::FrameNumber,
};
const PHYSICAL_ADDRESS_SIZE: usize = 56;
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct PhysicalAddress {
bits: usize,
}
impl PhysicalAddress {
pub fn floor(&self) -> FrameNumber {
FrameNumber {
bits: self.bits / PAGE_SIZE,
}
}
pub fn ceil(&self) -> FrameNumber {
FrameNumber {
bits: (self.bits + PAGE_SIZE - 1) / PAGE_SIZE,
}
}
pub fn page_offset(&self) -> usize {
self.bits & (PAGE_SIZE - 1)
}
pub fn is_aligned(&self) -> bool {
self.page_offset() == 0
}
pub fn as_ptr(&self) -> *const u8 {
self.bits as *const u8
}
pub fn as_ptr_mut(&self) -> *mut u8 {
self.bits as *mut u8
}
pub fn as_ref<T>(&self) -> &'static T {
unsafe { (self.bits as *const T).as_ref().unwrap() }
}
pub fn as_mut<T>(&self) -> &'static mut T {
unsafe { (self.bits as *mut T).as_mut().unwrap() }
}
}
impl Add<usize> for PhysicalAddress {
type Output = Self;
fn add(self, rhs: usize) -> Self {
Self::from(self.bits + rhs)
}
}
impl Sub<usize> for PhysicalAddress {
type Output = Self;
fn sub(self, rhs: usize) -> Self {
Self::from(self.bits - rhs)
}
}
impl From<usize> for PhysicalAddress {
fn from(value: usize) -> Self {
Self {
bits: value & ((1 << PHYSICAL_ADDRESS_SIZE) - 1),
}
}
}
impl From<PhysicalAddress> for usize {
fn from(value: PhysicalAddress) -> Self {
value.bits
}
}
impl From<FrameNumber> for PhysicalAddress {
fn from(value: FrameNumber) -> Self {
Self {
bits: usize::from(value) << PAGE_SIZE_BIT,
}
}
}