11 releases (6 breaking)

0.7.0 Dec 1, 2021
0.6.0 Nov 26, 2021
0.5.1 Apr 19, 2021
0.5.0 Jul 16, 2020

#1443 in Rust patterns

Download history 7622/week @ 2024-03-14 2331/week @ 2024-03-21 19384/week @ 2024-03-28 3275/week @ 2024-04-04 4452/week @ 2024-04-11 4641/week @ 2024-04-18 4385/week @ 2024-04-25 3102/week @ 2024-05-02 2483/week @ 2024-05-09 10660/week @ 2024-05-16 10323/week @ 2024-05-23 4022/week @ 2024-05-30 10501/week @ 2024-06-06 6231/week @ 2024-06-13 6340/week @ 2024-06-20 8005/week @ 2024-06-27

32,099 downloads per month
Used in 7 crates (3 directly)

MIT license

17KB
251 lines

Rust

An interner that deallocates unused values.

This crate is a fork of David Roundy's internment crate. It provides an alternative implementation of the internment::ArcIntern type. It inherits David's high-level design and API; however it is built completely on Rust's standard Arc type and the dashmap crate and does not contain any unsafe code.

Interning reduces the memory footprint of an application by storing a unique copy of each distinct value. It speeds up equality comparison and hashing operations, as only pointers rather than actual values need to be compared. On the flip side, object creation is slower, as it involves lookup in the interned object pool.

Interning is most commonly applied to strings; however it can also be useful for other object types. This library supports interning of arbitrary objects.

There exist several interning libraries for Rust, each with its own set of tradeoffs. This library makes the following design choices:

  • Interned objects are reference counted. When the last reference to an interned object is dropped, the object is deallocated. This prevents unbounded growth of the interned object pool in applications where the set of interned values changes dynamically at the cost of some CPU and memory overhead (due to storing and maintaining an atomic counter).
  • Multithreading. A single pool of interned objects is shared by all threads in the program. The pool is implemented as a DashMap for safe concurrent access and low contention.
  • Not just strings: this library allows interning any data type that satisfies the Eq + Hash + Send + Sync trait bound.
  • Safe: this library is built on Arc and DashMap types and does not contain any unsafe code.

Example

use arc_interner::ArcIntern;
let x = ArcIntern::new("hello");
let y = ArcIntern::new("world");
assert_ne!(x, y);
assert_eq!(x, ArcIntern::new("hello"));
assert_eq!(*x, "hello"); // dereference an ArcIntern like a pointer

Dependencies

~425–740KB
~16K SLoC