Skip to content

Commit 3976e4f

Browse files
committed
refactor(allocator)!: make Address::from_ptr an unsafe method (#16021)
A further step in refactoring `Address` to make it more robust and performant. Make `Address::from_ptr` an unsafe method, with the safety invariant that the pointer must be non-null. This: 1. Further discourages use of `Address::from_ptr` - `GetAddress::address` or `UnstableAddress::unstable_address` should be used instead. 2. Opens the door to changing `Address`'s inner type from `usize` to `NonZeroUsize`, which will reduce `Option<Address>` from 16 bytes to 8.
1 parent 72660f7 commit 3976e4f

File tree

3 files changed

+306
-299
lines changed

3 files changed

+306
-299
lines changed

crates/oxc_allocator/src/address.rs

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ use std::ptr::NonNull;
66
use crate::Box;
77

88
/// Memory address of an AST node in arena.
9+
//
10+
// At present, this is a `usize`, but it could be a `NonZeroUsize` instead, so that `Address` gains a niche,
11+
// which would reduce the size of `Option<Address>` from 16 bytes to 8 bytes.
912
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1013
#[repr(transparent)]
1114
pub struct Address(usize);
@@ -47,6 +50,10 @@ impl Address {
4750
/// }
4851
/// ```
4952
///
53+
/// # SAFETY
54+
///
55+
/// Pointer must be non-null.
56+
///
5057
/// # Example
5158
///
5259
/// Demonstration of the difference between `Address::from_ptr` and `GetAddress::address`:
@@ -92,7 +99,7 @@ impl Address {
9299
/// [`Box`]: crate::Box
93100
/// [`Vec`]: crate::Vec
94101
#[inline(always)] // Because it's a no-op
95-
pub fn from_ptr<T>(p: *const T) -> Self {
102+
pub unsafe fn from_ptr<T>(p: *const T) -> Self {
96103
Self(p as usize)
97104
}
98105
}
@@ -110,8 +117,8 @@ impl<T> GetAddress for Box<'_, T> {
110117
/// so this address acts as a unique identifier for the duration of the arena's existence.
111118
#[inline(always)] // Because it's only 1 instruction
112119
fn address(&self) -> Address {
113-
let ptr = Box::as_non_null(self).as_ptr().cast_const();
114-
Address::from_ptr(ptr)
120+
let ptr = Box::as_non_null(self);
121+
Address(ptr.addr().get())
115122
}
116123
}
117124

crates/oxc_traverse/scripts/lib/ancestor.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ export default function generateAncestorsCode(types) {
6666
impl${lifetimes} GetAddress for ${structName} {
6767
#[inline]
6868
fn address(&self) -> Address {
69-
Address::from_ptr(self.0)
69+
unsafe { Address::from_ptr(self.0) }
7070
}
7171
}
7272
`;

0 commit comments

Comments
 (0)