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
use core::ops::{Add, AddAssign, Sub};
use crate::{
constant::{PAGE_SIZE, PAGE_SIZE_BIT},
mem::PageNumber,
};
const VIRTUAL_ADDRESS_SIZE: usize = 39;
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub struct VirtualAddress {
bits: usize,
}
impl VirtualAddress {
pub fn floor(&self) -> PageNumber {
PageNumber::from(self.bits / PAGE_SIZE)
}
pub fn ceil(&self) -> PageNumber {
PageNumber::from((self.bits - 1 + PAGE_SIZE) / 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
}
}
impl Add<usize> for VirtualAddress {
type Output = Self;
fn add(self, rhs: usize) -> Self {
Self::from(self.bits + rhs)
}
}
impl AddAssign<usize> for VirtualAddress {
fn add_assign(&mut self, rhs: usize) {
self.bits += rhs;
}
}
impl Sub<usize> for VirtualAddress {
type Output = Self;
fn sub(self, rhs: usize) -> Self {
Self::from(self.bits - rhs)
}
}
impl From<usize> for VirtualAddress {
fn from(value: usize) -> Self {
assert!(
(value >> VIRTUAL_ADDRESS_SIZE) == 0
|| (value >> VIRTUAL_ADDRESS_SIZE) == (1 << 25) - 1
);
Self { bits: value }
}
}
impl From<VirtualAddress> for usize {
fn from(value: VirtualAddress) -> Self {
value.bits
}
}
impl From<PageNumber> for VirtualAddress {
fn from(value: PageNumber) -> Self {
let mut bits = usize::from(value) << PAGE_SIZE_BIT;
if (bits >> (VIRTUAL_ADDRESS_SIZE - 1)) == 1 {
bits |= !((1 << VIRTUAL_ADDRESS_SIZE) - 1);
}
Self { bits }
}
}