use rustc_hash::FxHashMap;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::cell::Cell;
use std::hash::{Hash, Hasher};
#[derive(Debug, Default, Copy, Clone, Eq, PartialEq)]
pub struct InternedKey(u64);
impl InternedKey {
#[inline]
pub fn from_str(s: &str) -> Self {
const FNV_OFFSET: u64 = 0xcbf29ce484222325;
const FNV_PRIME: u64 = 0x100000001b3;
let mut h = FNV_OFFSET;
for &byte in s.as_bytes() {
h ^= byte as u64;
h = h.wrapping_mul(FNV_PRIME);
}
InternedKey(h)
}
#[inline]
pub fn as_u64(&self) -> u64 {
self.0
}
#[inline]
pub fn from_u64(v: u64) -> Self {
InternedKey(v)
}
}
impl Hash for InternedKey {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
state.write_u64(self.0);
}
}
impl Serialize for InternedKey {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SERIALIZE_INTERNER.with(|cell| {
let ptr = cell
.get()
.expect("BUG: SERIALIZE_INTERNER not set during InternedKey serialization");
let interner = unsafe { &*ptr };
interner.resolve(*self).serialize(serializer)
})
}
}
impl<'de> Deserialize<'de> for InternedKey {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct KeyVisitor;
impl<'de> serde::de::Visitor<'de> for KeyVisitor {
type Value = InternedKey;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string key")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
let key = InternedKey::from_str(v);
DESERIALIZE_INTERNER.with(|cell| {
if let Some(ptr) = cell.get() {
let interner = unsafe { &mut *ptr };
interner.register(key, v);
}
});
Ok(key)
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
}
deserializer.deserialize_str(KeyVisitor)
}
}
#[derive(Debug, Clone, Default)]
pub struct StringInterner {
strings: FxHashMap<InternedKey, String>,
}
impl StringInterner {
pub fn new() -> Self {
Self::default()
}
#[inline]
pub fn register(&mut self, key: InternedKey, s: &str) {
self.strings.entry(key).or_insert_with(|| s.to_string());
#[cfg(debug_assertions)]
{
let existing = &self.strings[&key];
debug_assert_eq!(
existing, s,
"InternedKey hash collision: '{}' and '{}' have the same hash",
existing, s
);
}
}
#[inline]
pub fn get_or_intern(&mut self, s: &str) -> InternedKey {
let key = InternedKey::from_str(s);
self.register(key, s);
key
}
#[inline]
pub fn resolve(&self, key: InternedKey) -> &str {
self.strings
.get(&key)
.map(|s| s.as_str())
.unwrap_or_else(|| {
eprintln!(
"BUG: InternedKey {} not found in StringInterner ({} entries)",
key.as_u64(),
self.strings.len()
);
"<unknown>"
})
}
pub fn iter(&self) -> impl Iterator<Item = (InternedKey, &str)> {
self.strings.iter().map(|(&k, v)| (k, v.as_str()))
}
#[inline]
pub fn try_resolve(&self, key: InternedKey) -> Option<&str> {
self.strings.get(&key).map(|s| s.as_str())
}
#[inline]
pub fn try_resolve_to_key(&self, s: &str) -> Option<InternedKey> {
let key = InternedKey::from_str(s);
if self.strings.contains_key(&key) {
Some(key)
} else {
None
}
}
}
thread_local! {
static SERIALIZE_INTERNER: Cell<Option<*const StringInterner>> = const { Cell::new(None) };
static DESERIALIZE_INTERNER: Cell<Option<*mut StringInterner>> = const { Cell::new(None) };
pub(crate) static STRIP_PROPERTIES: Cell<bool> = const { Cell::new(false) };
}
pub(crate) struct SerdeSerializeGuard<'a> {
_phantom: std::marker::PhantomData<&'a StringInterner>,
}
impl<'a> SerdeSerializeGuard<'a> {
pub fn new(interner: &'a StringInterner) -> Self {
SERIALIZE_INTERNER.with(|cell| cell.set(Some(interner as *const StringInterner)));
SerdeSerializeGuard {
_phantom: std::marker::PhantomData,
}
}
}
impl Drop for SerdeSerializeGuard<'_> {
fn drop(&mut self) {
SERIALIZE_INTERNER.with(|cell| cell.set(None));
}
}
pub(crate) struct SerdeDeserializeGuard<'a> {
_phantom: std::marker::PhantomData<&'a mut StringInterner>,
}
impl<'a> SerdeDeserializeGuard<'a> {
pub fn new(interner: &'a mut StringInterner) -> Self {
DESERIALIZE_INTERNER.with(|cell| cell.set(Some(interner as *mut StringInterner)));
SerdeDeserializeGuard {
_phantom: std::marker::PhantomData,
}
}
}
impl Drop for SerdeDeserializeGuard<'_> {
fn drop(&mut self) {
DESERIALIZE_INTERNER.with(|cell| cell.set(None));
}
}
pub(crate) struct StripPropertiesGuard;
impl StripPropertiesGuard {
pub fn new() -> Self {
STRIP_PROPERTIES.with(|cell| cell.set(true));
StripPropertiesGuard
}
}
impl Drop for StripPropertiesGuard {
fn drop(&mut self) {
STRIP_PROPERTIES.with(|cell| cell.set(false));
}
}