From be4feb4ad7af63fdee30a2d5acfc6dde553a8829 Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Sat, 21 Dec 2024 10:10:56 +0000 Subject: [PATCH] feat(syntax): add `SymbolId::new` method (#8041) Add `SymbolId::new` method, same as `ScopeId::new`. The advantage over `SymbolId::from_usize` is that `new` can be a `const` method. --- crates/oxc_syntax/src/symbol.rs | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/crates/oxc_syntax/src/symbol.rs b/crates/oxc_syntax/src/symbol.rs index d23679cbab9e7..0003f4d3d6a56 100644 --- a/crates/oxc_syntax/src/symbol.rs +++ b/crates/oxc_syntax/src/symbol.rs @@ -8,6 +8,29 @@ use serde::{Serialize, Serializer}; #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)] pub struct SymbolId(NonMaxU32); +impl SymbolId { + /// Create `SymbolId` from `u32`. + /// + /// # Panics + /// Panics if `idx` is `u32::MAX`. + pub const fn new(idx: u32) -> Self { + if let Some(idx) = NonMaxU32::new(idx) { + return Self(idx); + } + panic!(); + } + + /// Create `SymbolId` from `u32` unchecked. + /// + /// # SAFETY + /// `idx` must not be `u32::MAX`. + #[allow(clippy::missing_safety_doc, clippy::unnecessary_safety_comment)] + pub const unsafe fn new_unchecked(idx: u32) -> Self { + // SAFETY: Caller must ensure `idx` is not `u32::MAX` + Self(NonMaxU32::new_unchecked(idx)) + } +} + impl Idx for SymbolId { #[allow(clippy::cast_possible_truncation)] fn from_usize(idx: usize) -> Self {