git.delta.rocks / jrsonnet / refs/commits / 695a2f8d51fa

difftreelog

source

crates/jrsonnet-interner/src/lib.rs2.1 KiBsourcehistory
1use rustc_hash::FxHashMap;2use serde::{Deserialize, Serialize};3use std::{4	cell::RefCell,5	fmt::{self, Display},6	hash::{BuildHasherDefault, Hash, Hasher},7	ops::Deref,8	rc::Rc,9};1011#[derive(Clone, PartialOrd, Ord, Eq)]12pub struct IStr(Rc<str>);1314impl Deref for IStr {15	type Target = str;1617	fn deref(&self) -> &Self::Target {18		&self.019	}20}2122impl PartialEq for IStr {23	fn eq(&self, other: &Self) -> bool {24		// It is ok, since all IStr should be inlined into same pool25		Rc::ptr_eq(&self.0, &other.0)26	}27}2829impl PartialEq<str> for IStr {30	fn eq(&self, other: &str) -> bool {31		&self.0 as &str == other32	}33}3435impl Hash for IStr {36	fn hash<H: Hasher>(&self, state: &mut H) {37		state.write_usize(Rc::as_ptr(&self.0) as *const () as usize)38	}39}4041impl Drop for IStr {42	fn drop(&mut self) {43		// First reference - current object, second - POOL44		if Rc::strong_count(&self.0) <= 2 {45			STR_POOL.with(|pool| pool.borrow_mut().remove(&self.0));46		}47	}48}4950impl fmt::Debug for IStr {51	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {52		write!(f, "{:?}", &self.0)53	}54}5556impl Display for IStr {57	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {58		f.write_str(&self.0)59	}60}6162thread_local! {63	static STR_POOL: RefCell<FxHashMap<Rc<str>, ()>> = RefCell::new(FxHashMap::with_capacity_and_hasher(200, BuildHasherDefault::default()));64}6566impl From<&str> for IStr {67	fn from(str: &str) -> Self {68		IStr(STR_POOL.with(|pool| {69			let mut pool = pool.borrow_mut();70			if let Some((k, _)) = pool.get_key_value(str) {71				return k.clone();72			} else {73				let rc: Rc<str> = str.into();74				pool.insert(rc.clone(), ());75				rc76			}77		}))78	}79}8081impl From<String> for IStr {82	fn from(str: String) -> Self {83		(&str as &str).into()84	}85}8687impl Serialize for IStr {88	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>89	where90		S: serde::Serializer,91	{92		(&self.0 as &str).serialize(serializer)93	}94}9596impl<'de> Deserialize<'de> for IStr {97	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>98	where99		D: serde::Deserializer<'de>,100	{101		let s = <&str>::deserialize(deserializer)?;102		Ok(s.into())103	}104}