use std::fmt::Debug;
use std::hash::Hash;
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, Weak};
use derive_deftly::define_derive_deftly;
use derive_more::{Deref, Display, Into};
type WeakHashSet<T> = weak_table::WeakHashSet<T, std::hash::RandomState>;
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Display, Into, Deref)]
pub struct Intern<T: ?Sized>(Arc<T>);
impl<T: ?Sized> Intern<T> {
pub fn new_uncached_uninterned(value: Arc<T>) -> Intern<T> {
Intern(value)
}
}
impl<'a, T: ?Sized> From<&'a Intern<T>> for &'a Arc<T> {
fn from(value: &'a Intern<T>) -> Self {
&value.0
}
}
pub trait GloballyInternable: Sized {
fn intern_cache() -> &'static InternCache<Self>;
fn into_intern(self) -> Intern<Self>
where
Self: Eq + Hash + 'static,
{
Self::intern_cache().intern(self)
}
}
define_derive_deftly! {
export GloballyInternable for struct:
impl $crate::intern::GloballyInternable for $ttype {
fn intern_cache() -> &'static $crate::intern::InternCache<Self> {
static S: $crate::intern::InternCache::<$ttype> = $crate::intern::InternCache::new();
&S
}
}
}
pub struct InternCache<T: ?Sized> {
cache: OnceLock<Mutex<WeakHashSet<Weak<T>>>>,
}
impl<T: ?Sized> InternCache<T> {
pub const fn new() -> Self {
InternCache {
cache: OnceLock::new(),
}
}
}
impl<T: ?Sized> Default for InternCache<T> {
fn default() -> Self {
Self::new()
}
}
impl<T: Eq + Hash + ?Sized> InternCache<T> {
fn cache(&self) -> MutexGuard<'_, WeakHashSet<Weak<T>>> {
let cache = self.cache.get_or_init(|| Mutex::new(WeakHashSet::new()));
cache.lock().expect("Poisoned lock lock for cache")
}
}
impl<T: Eq + Hash> InternCache<T> {
pub fn intern(&self, value: T) -> Intern<T> {
let mut cache = self.cache();
if let Some(pp) = cache.get(&value) {
Intern(pp)
} else {
let arc = Arc::new(value);
cache.insert(Arc::clone(&arc));
Intern(arc)
}
}
}
impl<T: Hash + Eq + ?Sized> InternCache<T> {
pub fn intern_ref<'a, V>(&self, value: &'a V) -> Intern<T>
where
V: Hash + Eq + ?Sized,
&'a V: Into<Arc<T>>,
T: std::borrow::Borrow<V>,
{
let mut cache = self.cache();
if let Some(arc) = cache.get(value) {
Intern(arc)
} else {
let arc = value.into();
cache.insert(Arc::clone(&arc));
Intern(arc)
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use super::*;
#[test]
fn interning_by_value() {
let c: InternCache<String> = InternCache::new();
let s1: Arc<String> = c.intern("abc".to_string()).into();
let s2 = c.intern("def".to_string()).into();
let s3 = c.intern("abc".to_string()).into();
assert!(Arc::ptr_eq(&s1, &s3));
assert!(!Arc::ptr_eq(&s1, &s2));
assert_eq!(s2.as_ref(), "def");
assert_eq!(s3.as_ref(), "abc");
}
#[test]
fn interning_by_ref() {
let c: InternCache<str> = InternCache::new();
let s1: Arc<str> = c.intern_ref("abc").into();
let s2 = c.intern_ref("def").into();
let s3 = c.intern_ref("abc").into();
assert!(Arc::ptr_eq(&s1, &s3));
assert!(!Arc::ptr_eq(&s1, &s2));
assert_eq!(&*s2, "def");
assert_eq!(&*s3, "abc");
}
}