Crate flyweights

Source
Expand description

Types implementing the flyweight pattern for reusing string allocations.

§Features

  • Supports UTF-8 strings with FlyStr and UTF-8-ish bytestrings with FlyByteStr.
  • Easy drop-in replacement for immutable strings without wiring up any additional function args.
  • Accessing the underlying string values has overhead similar to a Box<str>.
  • Cheap to clone.
  • Strings in the cache are freed when the last reference to them is dropped.
  • Heap allocations are avoided when possible with small string optimizations (SSO).
  • Hashing a flyweight and comparing it for equality against another flyweight are both O(1) operations.

§Tradeoffs

This was originally written for Fuchsia at a time when popular options didn’t fit the needs of adding caching to an existing long-running multithreaded system service that holds an unbounded number of user-controlled strings. The above features are suited to this use case, but there are many (many) alternative string caching crates to choose from if you have different constraints.

Structs§

FlyByteStr
An immutable bytestring type which only stores a single copy of each string allocated. Internally represented as a shared pointer to the backing allocation. Occupies a single pointer width.
FlyStr
An immutable string type which only stores a single copy of each string allocated. Internally represented as a shared pointer to the backing allocation. Occupies a single pointer width.