Skip to content

Commit

Permalink
perf(syntax): use NonZeroU32 for SymbolId and ReferenceId (#3970)
Browse files Browse the repository at this point in the history
  • Loading branch information
Boshen authored Jun 29, 2024
1 parent 21b964b commit 0c81fbe
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
24 changes: 21 additions & 3 deletions crates/oxc_syntax/src/reference.rs
Original file line number Diff line number Diff line change
@@ -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")]
Expand Down
24 changes: 21 additions & 3 deletions crates/oxc_syntax/src/symbol.rs
Original file line number Diff line number Diff line change
@@ -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")]
Expand Down

0 comments on commit 0c81fbe

Please sign in to comment.