Skip to content

Commit ee880bd

Browse files
haraldhnpmccallum
authored andcommitted
feat: Implement fmt::Pointer, Address::as_ptr and Address::as_mut_ptr
1 parent c7eec07 commit ee880bd

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/address.rs

+41
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
// SPDX-License-Identifier: Apache-2.0
22

33
use super::*;
4+
use core::fmt::{self, Formatter};
45
use core::marker::PhantomData;
56
use core::mem::align_of;
67
use core::ops::*;
@@ -48,6 +49,40 @@ impl<T, U> Address<T, U> {
4849
}
4950
}
5051

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+
5186
pub struct AlignmentError;
5287

5388
impl<T, U> Address<T, U>
@@ -266,4 +301,10 @@ mod test {
266301
assert_eq!(Address::from(7usize).raise::<u32>().raw(), 8);
267302
assert_eq!(Address::from(7usize).lower::<u32>().raw(), 4);
268303
}
304+
305+
#[test]
306+
fn print_pointer() {
307+
println!("{:p}", Address::from(4usize).raise::<Page>());
308+
println!("{:p}", Address::from(7u64).lower::<u32>());
309+
}
269310
}

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
//! * Offsets
77
//! * Pages
88
9-
#![no_std]
9+
#![cfg_attr(not(test), no_std)]
1010
#![deny(clippy::all)]
1111
#![deny(missing_docs)]
1212

0 commit comments

Comments
 (0)