Skip to main content

pawkit_interner/
lib.rs

1#![feature(str_from_raw_parts)]
2
3use core::{fmt, str};
4use std::{
5    alloc::{Layout, alloc, dealloc},
6    fmt::{Debug, Display},
7    hint::cold_path,
8    mem::forget,
9    ops::Deref,
10    ptr::{self, NonNull, copy_nonoverlapping},
11    str::FromStr,
12    sync::{
13        LazyLock,
14        atomic::{AtomicUsize, Ordering},
15    },
16};
17
18use dashmap::{DashMap, Entry};
19#[cfg(feature = "serde")]
20use serde::{Deserialize, Serialize, de::Visitor};
21
22pub mod lazy;
23
24const MAX_REFCOUNT: usize = (isize::MAX) as usize;
25
26struct InternInner {
27    strong: AtomicUsize,
28    weak: AtomicUsize,
29    len: usize,
30}
31
32/// Represents an interned string.
33/// Similar to an Arc<str>, but it also deduplicates strings.
34/// It is designed for fast forward lookup and cloning, with reverse lookup being prioritized over insertions / deletions.
35#[derive(PartialEq, Eq, Hash)]
36pub struct InternString {
37    inner: NonNull<InternInner>,
38}
39
40/// A weak interned string.
41/// Similar to Weak<str>, but references an InternString instead
42#[derive(PartialEq, Eq, Hash)]
43pub struct WeakInternString {
44    inner: NonNull<InternInner>,
45}
46
47/// # SAFETY
48/// The keys are casted to a static lifetime, and reference the underlying InternInner data,
49/// but the keys are removed before the InternInner is freed.
50static DATA: LazyLock<DashMap<&'static str, WeakInternString>> = LazyLock::new(Default::default);
51
52impl InternInner {
53    unsafe fn data_ptr<'a>(value: NonNull<Self>) -> *const u8 {
54        unsafe {
55            return value.as_ptr().add(1) as *const u8;
56        }
57    }
58
59    unsafe fn data_ptr_mut<'a>(value: NonNull<Self>) -> *mut u8 {
60        unsafe {
61            return value.as_ptr().add(1) as *mut u8;
62        }
63    }
64
65    unsafe fn data_mut<'a>(value: NonNull<Self>) -> &'a mut str {
66        unsafe {
67            return str::from_raw_parts_mut(Self::data_ptr_mut(value), (*value.as_ptr()).len);
68        }
69    }
70
71    unsafe fn data<'a>(value: NonNull<Self>) -> &'a str {
72        unsafe {
73            return str::from_raw_parts(Self::data_ptr(value), (*value.as_ptr()).len);
74        }
75    }
76
77    fn layout_for(len: usize) -> Layout {
78        return Layout::new::<Self>()
79            .extend(Layout::array::<u8>(len).unwrap())
80            .unwrap()
81            .0
82            .pad_to_align();
83    }
84
85    fn layout(value: NonNull<Self>) -> Layout {
86        unsafe {
87            return Self::layout_for((*value.as_ptr()).len);
88        }
89    }
90
91    unsafe fn alloc(s: &str) -> (NonNull<Self>, &'static str) {
92        unsafe {
93            let layout = Self::layout_for(s.len());
94
95            let ptr = alloc(layout) as *mut Self;
96
97            let value = &mut *ptr;
98
99            value.strong = AtomicUsize::new(1);
100            value.weak = AtomicUsize::new(1);
101            value.len = s.len();
102
103            let ptr = NonNull::new_unchecked(ptr);
104            let data = InternInner::data_mut(ptr);
105
106            copy_nonoverlapping(s.as_ptr(), data.as_mut_ptr(), s.len());
107
108            return (ptr, data);
109        }
110    }
111
112    unsafe fn dealloc(value: NonNull<Self>) {
113        unsafe {
114            let ptr = value.as_ptr();
115            let layout = Self::layout(value);
116
117            dealloc(ptr as *mut u8, layout);
118        }
119    }
120}
121
122impl InternString {
123    fn inner(&self) -> &InternInner {
124        unsafe {
125            return &*self.inner.as_ptr();
126        }
127    }
128
129    /// Consumes the `InternString`, returning the wrapped pointer.
130    ///
131    /// To avoid a memory leak the pointer must be converted back to an `InternString` using
132    /// [`InternString::from_raw`].
133    pub fn into_raw(self) -> *const u8 {
134        let ptr = self.inner.as_ptr() as *const u8;
135
136        forget(self);
137
138        return ptr;
139    }
140
141    /// Constructs an `InternString` from a raw pointer.
142    ///
143    /// The raw pointer must have been previously returned by a call to [`InternString::into_raw`].
144    pub unsafe fn from_raw(value: *const u8) -> Option<Self> {
145        let inner = NonNull::new(value as *mut InternInner)?;
146        if !inner.is_aligned() {
147            return None;
148        }
149
150        return Some(Self { inner: inner });
151    }
152
153    /// Creates a new intern string from the provided string
154    /// If an intern string exists with the same content, it returns a clone of that.
155    pub fn new(s: &str) -> Self {
156        loop {
157            // When dropping an intern string, it holds a handle to the entry,
158            // ensuring that the strong count will be in a safe state when we acquire it
159            if let Some(weak) = DATA.get(s) {
160                if let Some(value) = weak.into_strong() {
161                    return value;
162                }
163
164                cold_path();
165
166                // The allocation is dying, we should retry.
167                // In theory, this shouldn't be reachable,
168                // but there might be an edge case I haven't accounted for where it is.
169                continue;
170            }
171
172            let (ptr, str) = unsafe { InternInner::alloc(s) };
173
174            match DATA.entry(str) {
175                // If a thread created a new intern string by the time we get here,
176                // we want to deallocate ours and return theirs.
177                Entry::Occupied(occupied) => {
178                    cold_path();
179
180                    let value = occupied.get().into_strong();
181
182                    drop(occupied);
183
184                    unsafe {
185                        InternInner::dealloc(ptr);
186                    }
187
188                    if let Some(value) = value {
189                        return value;
190                    }
191
192                    cold_path();
193
194                    // The allocation is dying, we should retry.
195                    // In theory, this shouldn't be reachable,
196                    // but there might be an edge case I haven't accounted for where it is.
197                    continue;
198                }
199                Entry::Vacant(vacant) => {
200                    vacant.insert(WeakInternString { inner: ptr });
201
202                    let value = Self { inner: ptr };
203
204                    return value;
205                }
206            }
207        }
208    }
209
210    /// Retruns the underlying string data.
211    pub fn as_str<'a>(&'a self) -> &'a str {
212        unsafe {
213            return InternInner::data(self.inner);
214        }
215    }
216
217    /// Converts into a weak reference
218    pub fn into_weak(&self) -> WeakInternString {
219        let weak = WeakInternString { inner: self.inner };
220
221        self.inner().weak.fetch_add(1, Ordering::Relaxed);
222
223        return weak;
224    }
225}
226
227impl WeakInternString {
228    fn inner(&self) -> &InternInner {
229        unsafe {
230            return &*self.inner.as_ptr();
231        }
232    }
233
234    /// Returns true if the string is still alive
235    /// The string is considered dead if there are no strong references
236    pub fn is_alive(&self) -> bool {
237        return self.inner().strong.load(Ordering::Acquire) != 0;
238    }
239
240    /// Invokes the function if the underlying allocation is still alive.
241    pub fn with_str<R>(&self, f: impl FnOnce(&str) -> R) -> Option<R> {
242        let strong = self.into_strong()?;
243        return Some(f(strong.as_str()));
244    }
245
246    /// Converts to a strong reference if the string is still alive
247    pub fn into_strong(&self) -> Option<InternString> {
248        #[inline]
249        fn checked_increment(n: usize) -> Option<usize> {
250            if n == 0 {
251                return None;
252            }
253            assert!(n <= MAX_REFCOUNT);
254            return Some(n + 1);
255        }
256
257        self.inner()
258            .strong
259            .try_update(Ordering::Acquire, Ordering::Relaxed, checked_increment)
260            .ok()?;
261
262        return Some(InternString { inner: self.inner });
263    }
264}
265
266unsafe impl Send for InternString {}
267unsafe impl Sync for InternString {}
268
269unsafe impl Send for WeakInternString {}
270unsafe impl Sync for WeakInternString {}
271
272impl Drop for InternString {
273    fn drop(&mut self) {
274        // SAFETY: The allocation remains alive through `self` for this method.
275        // The weak reference held by the map keeps it alive at least until the map removes the key
276        let key: &'static str = unsafe { std::mem::transmute(self.as_str()) };
277
278        let Entry::Occupied(entry) = DATA.entry(key) else {
279            unreachable!("A strong handle should always have a corresponding map entry")
280        };
281
282        let old = self.inner().strong.fetch_sub(1, Ordering::Release);
283
284        if old != 1 {
285            return;
286        }
287
288        self.inner().strong.load(Ordering::Acquire);
289
290        if ptr::addr_eq(entry.get().inner.as_ptr(), self.inner.as_ptr()) {
291            debug_assert!(
292                ptr::addr_eq(entry.get().inner.as_ptr(), self.inner.as_ptr()),
293                "InternString allocation does not match its map entry",
294            );
295
296            drop(entry.remove());
297        }
298    }
299}
300
301impl Drop for WeakInternString {
302    fn drop(&mut self) {
303        if self.inner().weak.fetch_sub(1, Ordering::Release) == 1 {
304            self.inner().weak.load(Ordering::Acquire);
305
306            unsafe {
307                InternInner::dealloc(self.inner);
308            }
309        }
310    }
311}
312
313impl Clone for InternString {
314    fn clone(&self) -> Self {
315        let ref_count = self.inner().strong.fetch_add(1, Ordering::Relaxed);
316
317        assert!(ref_count < MAX_REFCOUNT);
318
319        return Self {
320            inner: self.inner.clone(),
321        };
322    }
323}
324
325impl Clone for WeakInternString {
326    fn clone(&self) -> Self {
327        let ref_count = self.inner().weak.fetch_add(1, Ordering::Relaxed);
328
329        assert!(ref_count < MAX_REFCOUNT);
330
331        return Self {
332            inner: self.inner.clone(),
333        };
334    }
335}
336
337impl PartialEq<WeakInternString> for InternString {
338    fn eq(&self, other: &WeakInternString) -> bool {
339        return ptr::addr_eq(self.inner.as_ptr(), other.inner.as_ptr());
340    }
341}
342
343impl PartialEq<InternString> for WeakInternString {
344    fn eq(&self, other: &InternString) -> bool {
345        return ptr::addr_eq(self.inner.as_ptr(), other.inner.as_ptr());
346    }
347}
348
349impl PartialEq<&str> for InternString {
350    fn eq(&self, other: &&str) -> bool {
351        return self.as_str() == *other;
352    }
353}
354
355impl PartialEq<&str> for WeakInternString {
356    fn eq(&self, other: &&str) -> bool {
357        return self.with_str(|it| it == *other).unwrap_or(false);
358    }
359}
360
361impl Deref for InternString {
362    type Target = str;
363
364    fn deref(&self) -> &Self::Target {
365        return self.as_str();
366    }
367}
368
369impl Debug for InternString {
370    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
371        return f.debug_tuple("InternString").field(&self.as_str()).finish();
372    }
373}
374
375impl Display for InternString {
376    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
377        return f.write_str(self.as_str());
378    }
379}
380
381impl Debug for WeakInternString {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        let mut t = f.debug_tuple("WeakInternString");
384
385        return self
386            .with_str(|s| t.field(&s).finish())
387            .unwrap_or_else(|| t.field(&"<dead>").finish());
388    }
389}
390
391impl Display for WeakInternString {
392    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
393        return self
394            .with_str(|s| f.write_str(s))
395            .unwrap_or_else(|| f.write_str(&"<dead>"));
396    }
397}
398
399impl FromStr for InternString {
400    type Err = ();
401
402    fn from_str(s: &str) -> Result<Self, Self::Err> {
403        return Ok(Self::new(s));
404    }
405}
406
407impl From<&str> for InternString {
408    fn from(value: &str) -> Self {
409        return Self::new(value);
410    }
411}
412
413impl From<String> for InternString {
414    fn from(value: String) -> Self {
415        return Self::new(&value);
416    }
417}
418
419#[cfg(feature = "serde")]
420impl Serialize for InternString {
421    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
422    where
423        S: serde::Serializer,
424    {
425        return serializer.serialize_str(self);
426    }
427}
428
429#[cfg(feature = "serde")]
430struct InternStringVisitor;
431
432#[cfg(feature = "serde")]
433impl<'a> Visitor<'a> for InternStringVisitor {
434    type Value = InternString;
435
436    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
437        formatter.write_str("a string")
438    }
439
440    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
441    where
442        E: serde::de::Error,
443    {
444        Ok(v.into())
445    }
446
447    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
448    where
449        E: serde::de::Error,
450    {
451        Ok(v.into())
452    }
453
454    fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
455    where
456        E: serde::de::Error,
457    {
458        match str::from_utf8(v) {
459            Ok(s) => Ok(s.into()),
460            Err(_) => Err(serde::de::Error::invalid_value(
461                serde::de::Unexpected::Bytes(v),
462                &self,
463            )),
464        }
465    }
466
467    fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
468    where
469        E: serde::de::Error,
470    {
471        match String::from_utf8(v) {
472            Ok(s) => Ok(s.into()),
473            Err(e) => Err(serde::de::Error::invalid_value(
474                serde::de::Unexpected::Bytes(&e.into_bytes()),
475                &self,
476            )),
477        }
478    }
479}
480
481#[cfg(feature = "serde")]
482impl<'de> Deserialize<'de> for InternString {
483    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
484    where
485        D: serde::Deserializer<'de>,
486    {
487        return deserializer.deserialize_string(InternStringVisitor);
488    }
489}
490
491#[cfg(test)]
492mod tests {
493    use super::*;
494    use std::sync::{Arc, Barrier, Mutex};
495    use std::thread;
496
497    #[test]
498    fn basic_interning() {
499        let s1 = InternString::new("hello");
500        let s2 = InternString::new("hello");
501        let s3 = InternString::new("world");
502
503        assert_eq!(s1, s2);
504        assert_ne!(s1, s3);
505
506        assert_eq!(s1.as_str(), "hello");
507        assert_eq!(s3.as_str(), "world");
508    }
509
510    #[test]
511    fn weak_references() {
512        let s1 = InternString::new("weak_test");
513        let w1 = s1.into_weak();
514
515        assert!(w1.is_alive());
516        assert_eq!(w1.with_str(|s| assert_eq!(s, "weak_test")), Some(()));
517
518        drop(s1);
519
520        assert!(!w1.is_alive());
521        assert_eq!(w1.with_str(|_| unreachable!()), None);
522    }
523
524    #[test]
525    fn cloning_strong() {
526        let s1 = InternString::new("clone_test");
527        let s2 = s1.clone();
528        let s3 = s2.clone();
529
530        assert_eq!(s1.inner.as_ptr(), s2.inner.as_ptr());
531        assert_eq!(s2.inner.as_ptr(), s3.inner.as_ptr());
532
533        assert_eq!(s1.as_str(), "clone_test");
534    }
535
536    #[test]
537    fn cloning_weak() {
538        let s1 = InternString::new("weak_clone");
539        let w1 = s1.into_weak();
540        let w2 = w1.clone();
541
542        assert_eq!(w1.inner.as_ptr(), w2.inner.as_ptr());
543
544        drop(s1);
545
546        assert!(!w1.is_alive());
547        assert!(!w2.is_alive());
548    }
549
550    #[test]
551    fn eq_partial() {
552        let s = InternString::new("eq_test");
553        let w = s.into_weak();
554
555        assert_eq!(s, w);
556        assert_eq!(w, s);
557
558        assert_eq!(s, "eq_test");
559        assert_eq!(w, "eq_test");
560    }
561
562    #[test]
563    fn data_deduplication() {
564        let s1 = InternString::new("dedup");
565        let s2 = InternString::new("dedup");
566
567        assert!(ptr::addr_eq(s1.inner.as_ptr(), s2.inner.as_ptr()));
568    }
569
570    #[test]
571    fn drop_cleans_data() {
572        let s = InternString::new("cleanup_test");
573
574        drop(s);
575
576        assert!(DATA.get("cleanup_test").is_none());
577    }
578
579    #[test]
580    fn multithreaded_usage() {
581        let s = Arc::new(InternString::new("thread_test"));
582
583        let mut handles = vec![];
584
585        for _ in 0..10 {
586            let s_clone = Arc::clone(&s);
587            handles.push(thread::spawn(move || {
588                let local = s_clone.clone();
589                assert_eq!(local.as_str(), "thread_test");
590            }));
591        }
592
593        for handle in handles {
594            handle.join().unwrap();
595        }
596
597        assert_eq!(s.as_str(), "thread_test");
598    }
599
600    #[test]
601    fn weak_after_drop_multithreaded() {
602        let s = InternString::new("weak_thread");
603        let w = s.into_weak();
604
605        let handle = thread::spawn(move || {
606            drop(s);
607        });
608
609        handle.join().unwrap();
610
611        assert!(!w.is_alive());
612        assert_eq!(w.with_str(|_| unreachable!()), None);
613    }
614
615    #[test]
616    fn simultaneous_intern() {
617        let barrier = Arc::new(Barrier::new(2));
618        let s1 = Arc::new(Mutex::new(None));
619        let s2 = Arc::new(Mutex::new(None));
620
621        let b1 = barrier.clone();
622        let s1c = s1.clone();
623        let t1 = thread::spawn(move || {
624            b1.wait();
625            *s1c.lock().unwrap() = Some(InternString::new("race_test"));
626        });
627
628        let b2 = barrier.clone();
629        let s2c = s2.clone();
630        let t2 = thread::spawn(move || {
631            b2.wait();
632            *s2c.lock().unwrap() = Some(InternString::new("race_test"));
633        });
634
635        t1.join().unwrap();
636        t2.join().unwrap();
637
638        let s1 = s1.lock().unwrap().take().unwrap();
639        let s2 = s2.lock().unwrap().take().unwrap();
640
641        assert!(ptr::addr_eq(s1.inner.as_ptr(), s2.inner.as_ptr()));
642    }
643
644    #[test]
645    fn weak_upgrade() {
646        let s = InternString::new("upgrade_test");
647        let w = s.into_weak();
648
649        let s2 = w.into_strong().expect("Should upgrade");
650        assert_eq!(s2.as_str(), "upgrade_test");
651
652        drop(s);
653        drop(s2);
654
655        assert!(w.into_strong().is_none());
656    }
657
658    #[test]
659    fn hammer_interning_concurrency() {
660        const THREADS: usize = 8;
661        const ROUNDS: usize = 5_000;
662        const UPGRADE_ATTEMPTS: usize = 64;
663
664        let barrier = Arc::new(Barrier::new(THREADS));
665
666        thread::scope(|scope| {
667            for thread_id in 0..THREADS {
668                let barrier = Arc::clone(&barrier);
669
670                scope.spawn(move || {
671                    for round in 0..ROUNDS {
672                        // All threads use the same key during each round.
673                        // Rotating keys also exercises independent map entries.
674                        let key = format!("hammer-{}", round % 16);
675
676                        let value = InternString::new(&key);
677                        let ptr = value.inner.as_ptr();
678
679                        // Keep all strong handles alive simultaneously.
680                        barrier.wait();
681
682                        // The map must point to the same allocation that we acquired.
683                        let entry = DATA
684                            .get(key.as_str())
685                            .expect("interned string missing from map");
686
687                        assert!(
688                            ptr::addr_eq(entry.inner.as_ptr(), ptr),
689                            "thread {thread_id}, round {round}: map points to another allocation"
690                        );
691
692                        drop(entry);
693
694                        // Exercise strong cloning and weak-reference creation.
695                        let cloned = value.clone();
696                        let weak = value.into_weak();
697                        let weak_clone = weak.clone();
698
699                        assert!(ptr::addr_eq(cloned.inner.as_ptr(), ptr));
700                        assert!(weak.is_alive());
701
702                        for _ in 0..UPGRADE_ATTEMPTS {
703                            let upgraded = weak_clone
704                                .into_strong()
705                                .expect("upgrade failed while strong handles were alive");
706
707                            assert!(ptr::addr_eq(upgraded.inner.as_ptr(), ptr));
708                            assert_eq!(upgraded.as_str(), key);
709
710                            drop(upgraded);
711                        }
712
713                        drop(weak_clone);
714                        drop(cloned);
715                        drop(value);
716
717                        // Every thread has dropped its strong handles before proceeding.
718                        barrier.wait();
719
720                        assert!(
721                            !weak.is_alive(),
722                            "thread {thread_id}, round {round}: weak reference stayed alive"
723                        );
724
725                        assert!(weak.into_strong().is_none());
726
727                        drop(weak);
728                    }
729                });
730            }
731        });
732    }
733
734    #[test]
735    fn hammer_weak_upgrade() {
736        const THREADS: usize = 16;
737        const ATTEMPTS: usize = 100_000;
738
739        let barrier = Arc::new(Barrier::new(THREADS + 1));
740
741        let value = InternString::new("hammer-weak-drop-race");
742        let weak = value.into_weak();
743
744        thread::scope(|scope| {
745            // This thread owns the original strong handle and drops it as
746            // the other threads begin attempting weak upgrades.
747            let owner_barrier = Arc::clone(&barrier);
748
749            scope.spawn(move || {
750                owner_barrier.wait();
751                drop(value);
752            });
753
754            for thread_id in 0..THREADS {
755                let barrier = Arc::clone(&barrier);
756                let weak = weak.clone();
757
758                scope.spawn(move || {
759                    barrier.wait();
760
761                    for attempt in 0..ATTEMPTS {
762                        match weak.into_strong() {
763                            Some(strong) => {
764                                assert_eq!(
765                                    strong.as_str(),
766                                    "hammer-weak-drop-race",
767                                    "thread {thread_id}, attempt {attempt}"
768                                );
769                            }
770                            None => break,
771                        }
772
773                        if attempt % 64 == 0 {
774                            thread::yield_now();
775                        }
776                    }
777                });
778            }
779        });
780
781        assert!(!weak.is_alive());
782        assert!(weak.into_strong().is_none());
783    }
784}