From 8e10e25ded956bf5dcb7f6752e227de4714e0dea Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Sun, 11 Aug 2024 03:31:45 +0000 Subject: [PATCH] feat(allocator): introduce `Address` (#4810) Closes #4807. Introduce `Address`. `Address` can be obtained from a `Box` and can act as a unique identifier for an AST node in arena. NB: It will also be unique across 2 ASTs in different allocators as long as neither allocator is dropped. --- crates/oxc_allocator/src/arena.rs | 15 +++++++++++++++ crates/oxc_allocator/src/lib.rs | 2 +- 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/oxc_allocator/src/arena.rs b/crates/oxc_allocator/src/arena.rs index 81459678c..350fbf74d 100644 --- a/crates/oxc_allocator/src/arena.rs +++ b/crates/oxc_allocator/src/arena.rs @@ -212,6 +212,21 @@ impl<'alloc, T: Hash> Hash for Vec<'alloc, T> { } } +/// Memory address of an AST node in arena. +/// +/// `Address` is generated from a `Box`. +/// AST nodes in a `Box` in an arena are guaranteed to never move in memory, +/// so this address acts as a unique identifier for the duration of the arena's existence. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Address(usize); + +impl<'a, T> Box<'a, T> { + #[inline] + pub fn address(&self) -> Address { + Address(ptr::addr_of!(**self) as usize) + } +} + #[cfg(test)] mod test { use std::hash::{DefaultHasher, Hash, Hasher}; diff --git a/crates/oxc_allocator/src/lib.rs b/crates/oxc_allocator/src/lib.rs index 7ab4c8ff6..4093dd75d 100644 --- a/crates/oxc_allocator/src/lib.rs +++ b/crates/oxc_allocator/src/lib.rs @@ -9,7 +9,7 @@ mod convert; use bumpalo::Bump; -pub use arena::{Box, String, Vec}; +pub use arena::{Address, Box, String, Vec}; pub use clone_in::CloneIn; pub use convert::{FromIn, IntoIn};