kvarn_async::prelude

Crate compact_str

Expand description

compact_str

A memory efficient string type that can store up to 24* bytes on the stack.

version on crates.io Minimum supported Rust Version: 1.60 mit license
Continuous Integration Status Cross Platform Status Minimum Supported Rust Version Status Clippy Status

* 12 bytes for 32-bit architectures


§About

A CompactString is a more memory efficient string type, that can store smaller strings on the stack, and transparently stores longer strings on the heap (aka a small string optimization). It can mostly be used as a drop in replacement for String and are particularly useful in parsing, deserializing, or any other application where you may have smaller strings.

§Properties

A CompactString specifically has the following properties:

  • size_of::<CompactString>() == size_of::<String>()
  • Stores up to 24 bytes on the stack
    • 12 bytes if running on a 32 bit architecture
  • Strings longer than 24 bytes are stored on the heap
  • Clone is O(n)
  • From<String> or From<Box<str>> re-uses underlying buffer
    • Eagerly inlines small strings
  • O(1) creation from &'static str with CompactString::const_new
  • Heap based string grows at a rate of 1.5x
    • The std library String grows at a rate of 2x
  • Space optimized for Option<_>
    • size_of::<CompactString>() == size_of::<Option<CompactString>>()
  • Uses branchless instructions for string accesses
  • Supports no_std environments

§Traits

This crate exposes two traits, ToCompactString and CompactStringExt.

§ToCompactString

Provides the to_compact_string(&self) method for converting types into a CompactString. This trait is automatically implemented for all types that are std::fmt::Display, with specialized higher performance impls for:

  • u8, u16, u32, u64, usize, u128
  • i8, i16, i32, i64