page_table_generic/
addr.rs

1use core::ptr::NonNull;
2
3macro_rules! def_addr {
4    ($name:ident, $t:ty) => {
5        #[repr(transparent)]
6        #[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
7        pub struct $name($t);
8
9        impl From<$t> for $name {
10            #[inline(always)]
11            fn from(value: $t) -> Self {
12                Self(value)
13            }
14        }
15
16        impl $name {
17            #[inline(always)]
18            pub fn raw(&self) -> $t {
19                self.0
20            }
21
22            #[inline(always)]
23            pub const fn new(value: $t) -> Self {
24                Self(value)
25            }
26        }
27
28        impl core::ops::Add<$t> for $name {
29            type Output = Self;
30
31            #[inline(always)]
32            fn add(self, rhs: $t) -> Self::Output {
33                Self(self.0 + rhs)
34            }
35        }
36
37        impl core::ops::AddAssign<$t> for $name {
38            #[inline(always)]
39            fn add_assign(&mut self, rhs: $t) {
40                self.0 += rhs;
41            }
42        }
43
44        impl core::ops::Sub<$t> for $name {
45            type Output = Self;
46
47            #[inline(always)]
48            fn sub(self, rhs: $t) -> Self::Output {
49                Self(self.0 - rhs)
50            }
51        }
52
53        impl core::ops::Sub<Self> for $name {
54            type Output = $t;
55
56            #[inline(always)]
57            fn sub(self, rhs: Self) -> Self::Output {
58                self.0 - rhs.0
59            }
60        }
61
62        impl core::fmt::Debug for $name {
63            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
64                write!(f, "0x{:0>16x}", self.0)
65            }
66        }
67    };
68}
69
70def_addr!(PhysAddr, usize);
71def_addr!(VirtAddr, usize);
72
73impl VirtAddr {
74    #[inline(always)]
75    pub fn as_ptr(self) -> *mut u8 {
76        self.0 as _
77    }
78}
79
80impl From<*mut u8> for VirtAddr {
81    #[inline(always)]
82    fn from(val: *mut u8) -> Self {
83        Self(val as _)
84    }
85}
86
87impl From<NonNull<u8>> for VirtAddr {
88    #[inline(always)]
89    fn from(val: NonNull<u8>) -> Self {
90        Self(val.as_ptr() as _)
91    }
92}
93
94impl From<*const u8> for VirtAddr {
95    #[inline(always)]
96    fn from(val: *const u8) -> Self {
97        Self(val as _)
98    }
99}
100
101#[cfg(target_pointer_width = "64")]
102impl From<u64> for PhysAddr {
103    #[inline(always)]
104    fn from(value: u64) -> Self {
105        Self(value as _)
106    }
107}
108
109#[cfg(target_pointer_width = "32")]
110impl From<u32> for PhysAddr {
111    #[inline(always)]
112    fn from(value: u32) -> Self {
113        Self(value as _)
114    }
115}