From 0c81fbeac679b38b233e131f4927ae306f127cfb Mon Sep 17 00:00:00 2001 From: Boshen Date: Sat, 29 Jun 2024 17:29:02 +0800 Subject: [PATCH] perf(syntax): use `NonZeroU32` for `SymbolId` and `ReferenceId` (#3970) closes https://github.com/oxc-project/backlog/issues/55 closes https://github.com/oxc-project/oxc/issues/3318 --- crates/oxc_syntax/src/reference.rs | 24 +++++++++++++++++++++--- crates/oxc_syntax/src/symbol.rs | 24 +++++++++++++++++++++--- 2 files changed, 42 insertions(+), 6 deletions(-) diff --git a/crates/oxc_syntax/src/reference.rs b/crates/oxc_syntax/src/reference.rs index 9738e3666d808..ce6226fc051f4 100644 --- a/crates/oxc_syntax/src/reference.rs +++ b/crates/oxc_syntax/src/reference.rs @@ -1,10 +1,28 @@ +use std::num::NonZeroU32; + use bitflags::bitflags; -use oxc_index::define_index_type; #[cfg(feature = "serialize")] use serde::Serialize; -define_index_type! { - pub struct ReferenceId = u32; +use oxc_index::Idx; + +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +pub struct ReferenceId(NonZeroU32); + +impl Idx for ReferenceId { + #[allow(clippy::cast_possible_truncation)] + fn from_usize(idx: usize) -> Self { + // SAFETY: + 1 is always non-zero. + #[allow(unsafe_code)] + unsafe { + Self(NonZeroU32::new_unchecked(idx as u32 + 1)) + } + } + + fn index(self) -> usize { + self.0.get() as usize - 1 + } } #[cfg(feature = "serialize")] diff --git a/crates/oxc_syntax/src/symbol.rs b/crates/oxc_syntax/src/symbol.rs index 528aee31eb50a..7a9a45337fd4b 100644 --- a/crates/oxc_syntax/src/symbol.rs +++ b/crates/oxc_syntax/src/symbol.rs @@ -1,10 +1,28 @@ +use std::num::NonZeroU32; + use bitflags::bitflags; -use oxc_index::define_index_type; #[cfg(feature = "serialize")] use serde::Serialize; -define_index_type! { - pub struct SymbolId = u32; +use oxc_index::Idx; + +#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] +#[cfg_attr(feature = "serialize", derive(Serialize))] +pub struct SymbolId(NonZeroU32); + +impl Idx for SymbolId { + #[allow(clippy::cast_possible_truncation)] + fn from_usize(idx: usize) -> Self { + // SAFETY: + 1 is always non-zero. + #[allow(unsafe_code)] + unsafe { + Self(NonZeroU32::new_unchecked(idx as u32 + 1)) + } + } + + fn index(self) -> usize { + self.0.get() as usize - 1 + } } #[cfg(feature = "serialize")]