use std::{
borrow::Cow,
fmt::{self, Debug, Display},
hash::{Hash, Hasher},
marker::PhantomData,
ops::Deref,
ptr::NonNull,
slice, str,
};
use oxc_allocator::{
Allocator, ArenaStringBuilder, CloneIn, CloneInSemanticIds, Dummy, FromIn, GetAllocator,
};
#[cfg(feature = "serialize")]
use oxc_estree::{ESTree, JsonSafeString, Serializer as ESTreeSerializer};
#[cfg(feature = "serialize")]
use serde::{Serialize, Serializer as SerdeSerializer};
use crate::{
CompactStr, Str,
ident_hasher::{IdentBuildHasher, ident_hash},
};
#[cfg(target_pointer_width = "64")]
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(transparent)]
struct LenAndHash(u64);
#[cfg(target_pointer_width = "64")]
#[expect(clippy::inline_always)] impl LenAndHash {
#[inline(always)]
const fn new(len: u32, hash: u32) -> Self {
Self((len as u64) | ((hash as u64) << 32))
}
#[inline(always)]
const fn unhashed(len: usize) -> Self {
Self(len as u64)
}
#[expect(clippy::cast_possible_truncation)]
#[inline(always)]
const fn len(self) -> u32 {
self.0 as u32
}
#[inline(always)]
const fn hash(self) -> u32 {
(self.0 >> 32) as u32
}
#[inline(always)]
const fn to_u64(self) -> u64 {
self.0
}
}
#[cfg(not(target_pointer_width = "64"))]
#[derive(Clone, Copy, PartialEq, Eq)]
#[repr(C)]
struct LenAndHash {
len: u32,
hash: u32,
}
#[cfg(not(target_pointer_width = "64"))]
#[expect(clippy::inline_always)] impl LenAndHash {
#[inline(always)]
const fn new(len: u32, hash: u32) -> Self {
Self { len, hash }
}
#[expect(clippy::cast_possible_truncation)]
#[inline(always)]
const fn unhashed(len: usize) -> Self {
Self { len: len as u32, hash: 0 }
}
#[inline(always)]
const fn len(self) -> u32 {
self.len
}
#[inline(always)]
const fn hash(self) -> u32 {
self.hash
}
#[inline(always)]
const fn to_u64(self) -> u64 {
(self.len as u64) | ((self.hash as u64) << 32)
}
}
#[repr(C)]
pub struct Ident<'a> {
ptr: NonNull<u8>,
len_and_hash: LenAndHash,
_marker: PhantomData<&'a str>,
}
#[expect(clippy::inline_always, clippy::cast_possible_truncation)]
#[inline(always)]
pub const fn new_const_ident(s: &str) -> Ident<'_> {
let bytes = s.as_bytes();
let len = bytes.len() as u32;
let hash = ident_hash(bytes);
let ptr = NonNull::from_ref(bytes).cast::<u8>();
unsafe { Ident::from_raw(ptr, len, hash) }
}
impl<'a> Ident<'a> {
#[inline]
pub fn from_str_in(s: &str, allocator: &impl GetAllocator<'a>) -> Self {
new_const_ident(allocator.allocator().alloc_str(s))
}
#[inline]
pub const fn new_unhashed(s: &'a str) -> Self {
let bytes = s.as_bytes();
let ptr = NonNull::from_ref(bytes).cast::<u8>();
Self { ptr, len_and_hash: LenAndHash::unhashed(bytes.len()), _marker: PhantomData }
}
#[inline]
const unsafe fn from_raw(ptr: NonNull<u8>, len: u32, hash: u32) -> Self {
Self { ptr, len_and_hash: LenAndHash::new(len, hash), _marker: PhantomData }
}
#[inline]
const fn ident_len(&self) -> u32 {
self.len_and_hash.len()
}
#[inline]
const fn ident_hash_value(&self) -> u32 {
self.len_and_hash.hash()
}
#[inline]
pub const fn empty() -> Self {
unsafe { Self::from_raw(NonNull::dangling(), 0, ident_hash(b"")) }
}
#[expect(clippy::inline_always)]
#[inline(always)] pub fn as_str(&self) -> &'a str {
let len = self.ident_len() as usize;
unsafe { str::from_utf8_unchecked(slice::from_raw_parts(self.ptr.as_ptr(), len)) }
}
#[expect(clippy::inline_always)]
#[inline(always)] pub fn as_arena_str(&self) -> Str<'a> {
Str::from(self.as_str())
}
#[inline]
pub fn into_string(self) -> String {
String::from(self.as_str())
}
#[inline]
pub fn into_compact_str(self) -> CompactStr {
CompactStr::new(self.as_str())
}
#[inline]
pub fn to_compact_str(self) -> CompactStr {
CompactStr::new(self.as_str())
}
#[expect(clippy::inline_always)]
#[inline(always)]
pub fn from_strs_array_in<const N: usize>(
strings: [&str; N],
allocator: &impl GetAllocator<'a>,
) -> Ident<'a> {
Self::from(allocator.allocator().alloc_concat_strs_array(strings))
}
#[inline]
pub fn from_cow_in(value: &Cow<'a, str>, allocator: &impl GetAllocator<'a>) -> Ident<'a> {
match value {
Cow::Borrowed(s) => Ident::from(*s),
Cow::Owned(s) => Ident::from_str_in(s, allocator),
}
}
}
unsafe impl Send for Ident<'_> {}
unsafe impl Sync for Ident<'_> {}
impl Deref for Ident<'_> {
type Target = str;
#[expect(clippy::inline_always)]
#[inline(always)]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl AsRef<str> for Ident<'_> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn as_ref(&self) -> &str {
self.as_str()
}
}
#[expect(clippy::expl_impl_clone_on_copy)]
impl Clone for Ident<'_> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn clone(&self) -> Self {
*self
}
}
impl Copy for Ident<'_> {}
impl<'a> From<&'a str> for Ident<'a> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn from(s: &'a str) -> Self {
new_const_ident(s)
}
}
impl<'alloc> From<ArenaStringBuilder<'alloc>> for Ident<'alloc> {
#[inline]
fn from(s: ArenaStringBuilder<'alloc>) -> Self {
Self::from(s.into_str())
}
}
impl<'a> From<Ident<'a>> for &'a str {
#[expect(clippy::inline_always)]
#[inline(always)]
fn from(s: Ident<'a>) -> Self {
s.as_str()
}
}
impl<'a> From<Ident<'a>> for Str<'a> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn from(s: Ident<'a>) -> Self {
s.as_arena_str()
}
}
impl<'a> From<Str<'a>> for Ident<'a> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn from(s: Str<'a>) -> Self {
Self::from(s.as_str())
}
}
impl From<Ident<'_>> for CompactStr {
#[inline]
fn from(val: Ident<'_>) -> Self {
val.into_compact_str()
}
}
impl From<Ident<'_>> for String {
#[inline]
fn from(val: Ident<'_>) -> Self {
val.into_string()
}
}
impl<'a> From<Ident<'a>> for Cow<'a, str> {
#[inline]
fn from(value: Ident<'a>) -> Self {
Cow::Borrowed(value.as_str())
}
}
impl PartialEq for Ident<'_> {
#[inline]
fn eq(&self, other: &Ident<'_>) -> bool {
self.len_and_hash == other.len_and_hash && self.as_str() == other.as_str()
}
}
impl Eq for Ident<'_> {}
impl PartialEq<str> for Ident<'_> {
#[inline]
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for Ident<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<Ident<'_>> for &str {
#[inline]
fn eq(&self, other: &Ident<'_>) -> bool {
*self == other.as_str()
}
}
impl PartialEq<Ident<'_>> for Cow<'_, str> {
#[inline]
fn eq(&self, other: &Ident<'_>) -> bool {
self.as_ref() == other.as_str()
}
}
impl PartialEq<&Ident<'_>> for Ident<'_> {
#[inline]
fn eq(&self, other: &&Ident<'_>) -> bool {
self == *other
}
}
impl PartialEq<Str<'_>> for Ident<'_> {
#[inline]
fn eq(&self, other: &Str<'_>) -> bool {
self.as_str() == other.as_str()
}
}
impl Hash for Ident<'_> {
#[inline]
fn hash<H: Hasher>(&self, hasher: &mut H) {
hasher.write_u64(self.len_and_hash.to_u64());
}
}
impl Display for Ident<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Display::fmt(self.as_str(), f)
}
}
impl Debug for Ident<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(self.as_str(), f)
}
}
impl<'new_alloc> CloneIn<'new_alloc> for Ident<'_> {
type Cloned = Ident<'new_alloc>;
#[inline]
fn clone_in_impl(
&self,
_with_semantic_ids: CloneInSemanticIds,
allocator: &'new_alloc Allocator,
) -> Self::Cloned {
let s = allocator.alloc_str(self.as_str());
let ptr = NonNull::from_ref(s).cast::<u8>();
unsafe { Ident::from_raw(ptr, self.ident_len(), self.ident_hash_value()) }
}
}
impl<'a> Dummy<'a> for Ident<'a> {
#[expect(clippy::inline_always)]
#[inline(always)]
fn dummy(_allocator: &'a Allocator) -> Self {
Ident::empty()
}
}
impl<'alloc> FromIn<'alloc, &str> for Ident<'alloc> {
#[inline]
fn from_in(s: &str, allocator: &'alloc Allocator) -> Self {
Self::from(allocator.alloc_str(s))
}
}
impl<'alloc> FromIn<'alloc, String> for Ident<'alloc> {
#[inline]
fn from_in(s: String, allocator: &'alloc Allocator) -> Self {
Self::from_in(s.as_str(), allocator)
}
}
impl<'alloc> FromIn<'alloc, &String> for Ident<'alloc> {
#[inline]
fn from_in(s: &String, allocator: &'alloc Allocator) -> Self {
Self::from_in(s.as_str(), allocator)
}
}
impl<'alloc> FromIn<'alloc, Cow<'_, str>> for Ident<'alloc> {
#[inline]
fn from_in(s: Cow<'_, str>, allocator: &'alloc Allocator) -> Self {
Self::from_in(&*s, allocator)
}
}
impl oxc_allocator::hash_map::Equivalent<Ident<'_>> for str {
#[inline]
fn equivalent(&self, key: &Ident<'_>) -> bool {
self == key.as_str()
}
}
#[cfg(feature = "serialize")]
impl Serialize for Ident<'_> {
#[inline] fn serialize<S: SerdeSerializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
Serialize::serialize(self.as_str(), serializer)
}
}
#[cfg(feature = "serialize")]
impl ESTree for Ident<'_> {
#[inline] fn serialize<S: ESTreeSerializer>(&self, serializer: S) {
ESTree::serialize(&JsonSafeString(self.as_str()), serializer);
}
}
pub type IdentHashMap<'a, V> = hashbrown::HashMap<Ident<'a>, V, IdentBuildHasher>;
pub type ArenaIdentHashMap<'alloc, V> =
oxc_allocator::ArenaHashMap<'alloc, Ident<'alloc>, V, IdentBuildHasher>;
pub type IdentHashSet<'a> = hashbrown::HashSet<Ident<'a>, IdentBuildHasher>;
pub type ArenaIdentHashSet<'alloc> =
oxc_allocator::ArenaHashSet<'alloc, Ident<'alloc>, IdentBuildHasher>;
#[macro_export]
macro_rules! static_ident {
($s:literal) => {
$crate::__internal::new_const_ident($s)
};
}
#[macro_export]
macro_rules! format_ident {
($alloc:expr, $($arg:tt)*) => {{
let mut s = $crate::__internal::ArenaStringBuilder::new_in($alloc);
::std::fmt::Write::write_fmt(&mut s, ::std::format_args!($($arg)*)).unwrap();
$crate::Ident::from(s)
}}
}
#[cfg(test)]
mod test {
use std::hash::BuildHasher;
use oxc_allocator::Allocator;
use oxc_data_structures::types::implements;
use super::*;
#[test]
fn ident_size() {
#[cfg(target_pointer_width = "64")]
assert_eq!(std::mem::size_of::<Ident<'_>>(), 16);
#[cfg(target_pointer_width = "32")]
assert_eq!(std::mem::size_of::<Ident<'_>>(), 12);
}
#[test]
fn ident_send_sync() {
assert!(implements!(Ident: Send));
assert!(implements!(Ident: Sync));
}
#[test]
fn ident_copy() {
assert!(implements!(Ident: Copy));
}
#[test]
fn ident_from_str() {
let s = "hello";
let ident = Ident::from(s);
assert_eq!(ident.as_str(), "hello");
}
#[test]
fn ident_empty() {
let ident = Ident::empty();
assert_eq!(ident.as_str(), "");
assert_eq!(ident.ident_len(), 0);
}
#[test]
fn ident_new_const() {
let ident = new_const_ident("world");
assert_eq!(ident.as_str(), "world");
}
#[test]
fn ident_eq() {
let a = Ident::from("foo");
let b = Ident::from("foo");
let c = Ident::from("bar");
assert_eq!(a, b);
assert_ne!(a, c);
}
#[test]
fn ident_eq_str() {
let ident = Ident::from("hello");
assert_eq!(ident, "hello");
assert_ne!(ident, "world");
}
#[test]
fn ident_hash_consistency() {
let build_hasher = IdentBuildHasher;
let ident = Ident::from("fooBar");
let ident_hash_val = build_hasher.hash_one(ident);
let str_hash = build_hasher.hash_one("fooBar");
assert_eq!(ident_hash_val, str_hash);
}
#[test]
fn ident_hashmap_str_lookup() {
let mut map = IdentHashMap::default();
map.insert(Ident::from("key1"), 1);
map.insert(Ident::from("key2"), 2);
assert_eq!(map.get("key1"), Some(&1));
assert_eq!(map.get("key2"), Some(&2));
assert_eq!(map.get("key3"), None);
}
#[test]
fn ident_hashmap_ident_lookup() {
let mut map = IdentHashMap::default();
map.insert(Ident::from("key1"), 1);
let key = Ident::from("key1");
assert_eq!(map.get(&key), Some(&1));
}
#[test]
fn ident_clone_in() {
let allocator = Allocator::new();
let original = Ident::from("test");
let cloned = original.clone_in(&allocator);
assert_eq!(original.as_str(), cloned.as_str());
assert_eq!(original, cloned);
assert_eq!(original.ident_hash_value(), cloned.ident_hash_value());
}
#[test]
fn ident_deref() {
let ident = Ident::from("hello");
assert!(ident.starts_with("hel")); assert_eq!(ident.len(), 5);
}
#[test]
fn ident_display() {
let ident = Ident::from("test");
assert_eq!(format!("{ident}"), "test");
}
#[test]
fn ident_debug() {
let ident = Ident::from("test");
assert_eq!(format!("{ident:?}"), "\"test\"");
}
#[test]
fn static_ident_correct() {
let ident = static_ident!("require");
assert_eq!(ident.as_str(), "require");
assert_eq!(ident, Ident::from("require"));
}
#[test]
fn static_ident_const_context() {
const IDENT: Ident<'static> = static_ident!("hello");
assert_eq!(IDENT.as_str(), "hello");
}
#[test]
#[expect(clippy::items_after_statements)]
fn ident_from_str_in() {
let allocator = Allocator::new();
let allocator: &Allocator = &allocator;
let ident = Ident::from_str_in("world", &allocator);
assert_eq!(ident.as_str(), "world");
assert_eq!(ident, Ident::from("world"));
struct Wrapper<'a>(&'a Allocator);
impl<'a> GetAllocator<'a> for Wrapper<'a> {
fn allocator(&self) -> &'a Allocator {
self.0
}
}
let wrapper = Wrapper(allocator);
let ident = Ident::from_str_in("hello", &wrapper);
assert_eq!(ident.as_str(), "hello");
assert_eq!(ident, Ident::from("hello"));
}
#[test]
#[expect(clippy::items_after_statements)]
fn ident_from_strs_array_in() {
let allocator = Allocator::new();
let allocator = &allocator;
let ident = Ident::from_strs_array_in(["hello", " ", "world", "!"], &allocator);
assert_eq!(ident.as_str(), "hello world!");
assert_eq!(ident, Ident::from("hello world!"));
struct Wrapper<'a>(&'a Allocator);
impl<'a> GetAllocator<'a> for Wrapper<'a> {
fn allocator(&self) -> &'a Allocator {
self.0
}
}
let wrapper = Wrapper(allocator);
let ident = Ident::from_strs_array_in(["foo", "_", "bar"], &wrapper);
assert_eq!(ident.as_str(), "foo_bar");
assert_eq!(ident, Ident::from("foo_bar"));
}
#[test]
#[expect(clippy::items_after_statements)]
fn ident_from_cow_in() {
let allocator = Allocator::new();
let allocator = &allocator;
let borrowed = "world";
let used_before = allocator.used_bytes();
let ident = Ident::from_cow_in(&Cow::Borrowed(borrowed), &allocator);
assert_eq!(ident.as_str(), "world");
assert_eq!(ident, Ident::from("world"));
assert_eq!(ident.as_str().as_ptr(), borrowed.as_ptr());
assert_eq!(allocator.used_bytes(), used_before);
let owned = "owned".to_string();
let owned_ptr = owned.as_ptr();
let ident = Ident::from_cow_in(&Cow::Owned(owned), &allocator);
assert_eq!(ident.as_str(), "owned");
assert_eq!(ident, Ident::from("owned"));
assert_ne!(ident.as_str().as_ptr(), owned_ptr);
assert!(allocator.used_bytes() > used_before);
struct Wrapper<'a>(&'a Allocator);
impl<'a> GetAllocator<'a> for Wrapper<'a> {
fn allocator(&self) -> &'a Allocator {
self.0
}
}
let wrapper = Wrapper(allocator);
let ident = Ident::from_cow_in(&Cow::Borrowed("hello"), &wrapper);
assert_eq!(ident.as_str(), "hello");
assert_eq!(ident, Ident::from("hello"));
}
#[test]
fn arena_ident_hashmap() {
let allocator = Allocator::new();
let mut map = ArenaIdentHashMap::new_in(&allocator);
let key = Ident::from_in("hello", &allocator);
map.insert(key, 42);
assert_eq!(map.get("hello"), Some(&42));
assert_eq!(map.get(&Ident::from("hello")), Some(&42));
}
#[test]
fn arena_ident_hashset() {
let allocator = Allocator::new();
let mut set = ArenaIdentHashSet::new_in(&allocator);
set.insert(Ident::from_in("hello", &allocator));
assert!(set.contains("hello"));
assert!(set.contains(&Ident::from("hello")));
assert!(!set.contains("world"));
let set =
ArenaIdentHashSet::from_iter_in([Ident::from("foo"), Ident::from("bar")], &allocator);
assert_eq!(set.len(), 2);
assert!(set.contains("foo"));
assert!(set.contains("bar"));
}
}