Crate ustr

source ·
Expand description

Fast, FFI-friendly string interning. A Ustr (Unique Str) is a lightweight handle representing a static, immutable entry in a global string cache, allowing for:

  • Extremely fast string assignment and comparisons – it’s just a pointer comparison.
  • Efficient storage – only one copy of the string is held in memory, and getting access to it is just a pointer indirection.
  • Fast hashing – the precomputed hash is stored with the string
  • Fast FFI – the string is stored with a terminating null byte so can be passed to C directly without doing the CString dance.

The downside is no strings are ever freed, so if you’re creating lots and lots of strings, you might run out of memory. On the other hand, War and Peace is only 3MB, so it’s probably fine.

This crate is based on OpenImageIO’s ustring but it is NOT binary-compatible (yet). The underlying hash map implementation is directy ported from OIIO.

Usage

use ustr::{Ustr, ustr, ustr as u};

// Creation is quick and easy using either `Ustr::from` or the ustr function
// and only one copy of any string is stored
let u1 = Ustr::from("the quick brown fox");
let u2 = ustr("the quick brown fox");

// Comparisons and copies are extremely cheap
let u3 = u1;
assert_eq!(u2, u3);

// You can pass straight to FFI
let len = unsafe {
    libc::strlen(u1.as_char_ptr())
};
assert_eq!(len, 19);

// Use as_str() to get a &str
let words: Vec<&str> = u1.as_str().split_whitespace().collect();
assert_eq!(words, ["the", "quick", "brown", "fox"]);

// For best performance when using Ustr as key for a HashMap or HashSet,
// you'll want to use the precomputed hash. To make this easier, just use
// the UstrMap and UstrSet exports:
use ustr::UstrMap;

// Key type is always Ustr
let mut map: UstrMap<usize> = UstrMap::default();
map.insert(u1, 17);
assert_eq!(*map.get(&u1).unwrap(), 17);

By enabling the "serde" feature you can serialize individual Ustrs or the whole cache with serde.

use ustr::{Ustr, ustr};
let u_ser = ustr("serde");
let json = serde_json::to_string(&u_ser).unwrap();
let u_de : Ustr = serde_json::from_str(&json).unwrap();
assert_eq!(u_ser, u_de);

Since the cache is global, use the ustr::DeserializedCache dummy object to drive the deserialization.

use ustr::{Ustr, ustr};
ustr("Send me to JSON and back");
let json = serde_json::to_string(ustr::cache()).unwrap();

// ... some time later ...
let _: ustr::DeserializedCache = serde_json::from_str(&json).unwrap();
assert_eq!(ustr::num_entries(), 1);
assert_eq!(ustr::string_cache_iter().collect::<Vec<_>>(), vec!["Send me to JSON and back"]);

Why?

It is common in certain types of applications to use strings as identifiers, but not really do any processing with them. To paraphrase from OIIO’s Ustring documentation – compared to standard strings, Ustrs have several advantages:

  • Each individual Ustr is very small – in fact, we guarantee that a Ustr is the same size and memory layout as an ordinary *u8.
  • Storage is frugal, since there is only one allocated copy of each unique character sequence, throughout the lifetime of the program.
  • Assignment from one Ustr to another is just copy of the pointer; no allocation, no character copying, no reference counting.
  • Equality testing (do the strings contain the same characters) is a single operation, the comparison of the pointer.
  • Memory allocation only occurs when a new Ustr is constructed from raw characters the FIRST time – subsequent constructions of the same string just finds it in the canonial string set, but doesn’t need to allocate new storage. Destruction of a Ustr is trivial, there is no de-allocation because the canonical version stays in the set. Also, therefore, no user code mistake can lead to memory leaks.

But there are some problems, too. Canonical strings are never freed from the table. So in some sense all the strings “leak”, but they only leak one copy for each unique string that the program ever comes across.

On the whole, Ustrs are a really great string representation

  • if you tend to have (relatively) few unique strings, but many copies of those strings;
  • if the creation of strings from raw characters is relatively rare compared to copying or comparing to existing strings;
  • if you tend to make the same strings over and over again, and if it’s relatively rare that a single unique character sequence is used only once in the entire lifetime of the program;
  • if your most common string operations are assignment and equality testing and you want them to be as fast as possible;
  • if you are doing relatively little character-by-character assembly of strings, string concatenation, or other “string manipulation” (other than equality testing).

Ustrs are not so hot

  • if your program tends to have very few copies of each character sequence over the entire lifetime of the program;
  • if your program tends to generate a huge variety of unique strings over its lifetime, each of which is used only a short time and then discarded, never to be needed again;
  • if you don’t need to do a lot of string assignment or equality testing, but lots of more complex string manipulation.

Safety and Compatibility

This crate contains a significant amount of unsafe but usage has been checked and is well-documented. It is also run through Miri as part of the CI process. I use it regularly on 64-bit systems, and it has passed Miri on a 32-bit system as well, bit 32-bit is not checked regularly. If you want to use it on 32-bit, please make sure to run Miri and open and issue if you find any problems.

Structs

  • A handle representing a string in the global string cache.

Functions

  • Utility function to get a reference to the main cache object for use with serialization.
  • Create a new Ustr from the given &str but only if it already exists in the string cache.
  • Returns the number of unique strings in the cache
  • Return an iterator over the entire string cache.
  • Returns the total amount of memory allocated and in use by the cache in bytes
  • Returns the total amount of memory reserved by the cache in bytes
  • Create a new Ustr from the given &str.

Type Aliases

  • A standard HashMap using Ustr as the key type with a custom Hasher that just uses the precomputed hash for speed instead of calculating it
  • A standard HashSet using Ustr as the key type with a custom Hasher that just uses the precomputed hash for speed instead of calculating it