2 ms·
What about using a HashSet<Rc<str>>. And returning a type that implements Drop. The drop method can remove the string from the cache when the last reference is
by bombela 5y ago
What about using a HashSet<Rc<str>>. And returning a type that implements Drop. The drop method can remove the string from the cache when the last reference is dropped. Since the cache must be accessed by the interning function and drop, I used interior mutability. By putting the cache behind a Rc<RefCell<>>.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=abfe8779f8dd5b8391489f5fa19c746c https://play.rust-lang.org/?version=stable&mode=debug&editio...
With the same principle, we can use a static, arc and mutex to use a the cache as a global variable. And implement thread-safe string interning. Here, locking the cache at the wrong time during the drop can lead to a race condition.
https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=50d7697dd7abc69e756668962dbe36f9 https://play.rust-lang.org/?version=stable&mode=debug&editio...
To make the InternedStr behaves a bit more like &str or an immutable String, I implemented Clone, Display, Pointer, conversion from &Interned to &str. Ideally it should probably resemble how String de-references to &str for everything (Deref<Target = str>).