bumpalo-intern 0.2.1

String intern utility combined with Bumpalo.
Documentation

bumpalo-intern

crates.io docs.rs CI

String interner for bumpalo.

This library provides 2 ways of intern.

direct

Direct intern is to use the wrapped &str as the key of interning.

use bumpalo_intern::direct::{InternedStr, FromInterned, DirectInternStore};

// You should have a simple &str wrapper.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
struct MyInterned<'a>(InternedStr<'a>);

// And the type must implement FromInterned.
impl<'arena> FromInterned<'arena> for MyInterned<'arena> {
    fn from_interned(v: InternedStr<'arena>) -> Self {
       Self(v)
   }

   fn as_interned(&self) -> InternedStr<'arena> {
       self.0
   }
}

let arena = bumpalo::Bump::new();
let mut interner = DirectInternStore::new(&arena);

let foo: MyInterned<'_> = interner.ensure(&"foo".to_string());
let foo2 = interner.ensure(&"foo".to_string());
let bar = interner.ensure(&"bar".to_string());

assert_eq!(foo, foo2);
assert_ne!(foo, bar);
assert_eq!(foo.as_interned().as_str(), "foo");
assert_eq!(bar.as_interned().as_str(), "bar");

This is simple to use given you can use a wrapped &str which is guaranteed to be unique. If you want to put some metadata, or have guarantee to have dense index for the interned value, see the next dense.

dense

use bumpalo_intern::dense::{Interned,Keyed,InternTag,DenseInternStore};

// You should have a type (either struct or enum) with a unique str key.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
struct MyInterned<'a>(&'a str);

impl<'a> Keyed<'a> for MyInterned<'a> {
    fn intern_key(&self) -> &'a str {
        self.0
    }
}

impl<'a> Interned<'a> for MyInterned<'a> {
    type View<'b> = MyInterned<'b>;

    fn intern_from<'b>(arena: &'a bumpalo::Bump, value: Self::View<'b>) -> (&'a str, Self) {
        let key = arena.alloc_str(value.0);
        (key, MyInterned(key))
    }
}

let arena = bumpalo::Bump::new();
let mut interner = DenseInternStore::new(&arena);

let tag: InternTag<MyInterned<'_>> = interner.ensure(MyInterned(&"foo".to_string()));

assert!(matches!(interner.get(tag), Some(MyInterned("foo"))));