Skip to content

Commit d64cc5a

Browse files
authored
Merge pull request #369 from rust-osdev/const
Make more VirtAddr and PhysAddr methods const
2 parents 6ae5b6a + 469864b commit d64cc5a

File tree

1 file changed

+14
-13
lines changed

1 file changed

+14
-13
lines changed

src/addr.rs

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -138,14 +138,14 @@ impl VirtAddr {
138138
/// Converts the address to a raw pointer.
139139
#[cfg(target_pointer_width = "64")]
140140
#[inline]
141-
pub fn as_ptr<T>(self) -> *const T {
141+
pub const fn as_ptr<T>(self) -> *const T {
142142
self.as_u64() as *const T
143143
}
144144

145145
/// Converts the address to a mutable raw pointer.
146146
#[cfg(target_pointer_width = "64")]
147147
#[inline]
148-
pub fn as_mut_ptr<T>(self) -> *mut T {
148+
pub const fn as_mut_ptr<T>(self) -> *mut T {
149149
self.as_ptr::<T>() as *mut T
150150
}
151151

@@ -420,13 +420,12 @@ impl PhysAddr {
420420
///
421421
/// This function panics if a bit in the range 52 to 64 is set.
422422
#[inline]
423-
pub fn new(addr: u64) -> PhysAddr {
424-
assert_eq!(
425-
addr.get_bits(52..64),
426-
0,
427-
"physical addresses must not have any bits in the range 52 to 64 set"
428-
);
429-
PhysAddr(addr)
423+
pub const fn new(addr: u64) -> Self {
424+
// TODO: Replace with .ok().expect(msg) when that works on stable.
425+
match Self::try_new(addr) {
426+
Ok(p) => p,
427+
Err(_) => panic!("physical addresses must not have any bits in the range 52 to 64 set"),
428+
}
430429
}
431430

432431
/// Creates a new physical address, throwing bits 52..64 away.
@@ -449,10 +448,12 @@ impl PhysAddr {
449448
///
450449
/// Fails if any bits in the range 52 to 64 are set.
451450
#[inline]
452-
pub fn try_new(addr: u64) -> Result<PhysAddr, PhysAddrNotValid> {
453-
match addr.get_bits(52..64) {
454-
0 => Ok(PhysAddr(addr)), // address is valid
455-
_ => Err(PhysAddrNotValid(addr)),
451+
pub const fn try_new(addr: u64) -> Result<Self, PhysAddrNotValid> {
452+
let p = Self::new_truncate(addr);
453+
if p.0 == addr {
454+
Ok(p)
455+
} else {
456+
Err(PhysAddrNotValid(addr))
456457
}
457458
}
458459

0 commit comments

Comments
 (0)