Skip to content

Commit

Permalink
fix(syntax): fix unsound use of NonZeroU32 (#4466)
Browse files Browse the repository at this point in the history
`NonZeroU32::new_unchecked(idx as u32 + 1)` is unsound because if `idx == u32::MAX`, `idx + 1` wraps around back to zero. So unfortunately we need to use the checked version `NonZeroU32::new(idx as u32 + 1).unwrap()` to avoid UB in this edge case.
  • Loading branch information
overlookmotel committed Jul 26, 2024
1 parent 81384f5 commit 82ba2a0
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
6 changes: 3 additions & 3 deletions crates/oxc_syntax/src/reference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ 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.

unsafe { Self(NonZeroU32::new_unchecked(idx as u32 + 1)) }
// NB: We can't use `NonZeroU32::new_unchecked(idx as u32 + 1)`
// because if `idx == u32::MAX`, `+ 1` would make it wrap around back to 0
Self(NonZeroU32::new(idx as u32 + 1).unwrap())
}

fn index(self) -> usize {
Expand Down
12 changes: 6 additions & 6 deletions crates/oxc_syntax/src/symbol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ 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.

unsafe { Self(NonZeroU32::new_unchecked(idx as u32 + 1)) }
// NB: We can't use `NonZeroU32::new_unchecked(idx as u32 + 1)`
// because if `idx == u32::MAX`, `+ 1` would make it wrap around back to 0
Self(NonZeroU32::new(idx as u32 + 1).unwrap())
}

fn index(self) -> usize {
Expand All @@ -30,9 +30,9 @@ pub struct RedeclarationId(NonZeroU32);
impl Idx for RedeclarationId {
#[allow(clippy::cast_possible_truncation)]
fn from_usize(idx: usize) -> Self {
// SAFETY: + 1 is always non-zero.

unsafe { Self(NonZeroU32::new_unchecked(idx as u32 + 1)) }
// NB: We can't use `NonZeroU32::new_unchecked(idx as u32 + 1)`
// because if `idx == u32::MAX`, `+ 1` would make it wrap around back to 0
Self(NonZeroU32::new(idx as u32 + 1).unwrap())
}

fn index(self) -> usize {
Expand Down

0 comments on commit 82ba2a0

Please sign in to comment.