|
1 | 1 | // SPDX-License-Identifier: Apache-2.0
|
2 | 2 |
|
3 | 3 | use super::*;
|
| 4 | +use core::fmt::{self, Formatter}; |
4 | 5 | use core::marker::PhantomData;
|
5 | 6 | use core::mem::align_of;
|
6 | 7 | use core::ops::*;
|
@@ -48,6 +49,40 @@ impl<T, U> Address<T, U> {
|
48 | 49 | }
|
49 | 50 | }
|
50 | 51 |
|
| 52 | +impl<T, U> Address<T, U> |
| 53 | +where |
| 54 | + Address<usize, U>: From<Address<T, U>>, |
| 55 | + Address<T, U>: Copy, |
| 56 | +{ |
| 57 | + /// Returns a raw pointer to its inner type |
| 58 | + /// |
| 59 | + /// # Safety |
| 60 | + /// Behavior is undefined, if the pointer is used and |
| 61 | + /// is not aligned or points to uninitialized memory. |
| 62 | + pub fn as_ptr(&self) -> *const U { |
| 63 | + Address::<usize, U>::from(*self).0 as *const U |
| 64 | + } |
| 65 | + |
| 66 | + /// Returns a raw pointer to its inner type |
| 67 | + /// |
| 68 | + /// # Safety |
| 69 | + /// Behavior is undefined, if the pointer is used and |
| 70 | + /// is not aligned or points to uninitialized memory. |
| 71 | + pub fn as_mut_ptr(&self) -> *mut U { |
| 72 | + Address::<usize, U>::from(*self).0 as *mut U |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +impl<T: Copy, U> fmt::Pointer for Address<T, U> |
| 77 | +where |
| 78 | + Address<usize, U>: From<Address<T, U>>, |
| 79 | + Address<T, U>: Copy, |
| 80 | +{ |
| 81 | + fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 82 | + write!(f, "{:p}", self.as_ptr()) |
| 83 | + } |
| 84 | +} |
| 85 | + |
51 | 86 | pub struct AlignmentError;
|
52 | 87 |
|
53 | 88 | impl<T, U> Address<T, U>
|
@@ -266,4 +301,10 @@ mod test {
|
266 | 301 | assert_eq!(Address::from(7usize).raise::<u32>().raw(), 8);
|
267 | 302 | assert_eq!(Address::from(7usize).lower::<u32>().raw(), 4);
|
268 | 303 | }
|
| 304 | + |
| 305 | + #[test] |
| 306 | + fn print_pointer() { |
| 307 | + println!("{:p}", Address::from(4usize).raise::<Page>()); |
| 308 | + println!("{:p}", Address::from(7u64).lower::<u32>()); |
| 309 | + } |
269 | 310 | }
|
0 commit comments