smartstring
A drop-in replacement for Rust's String that inlines short strings on the stack
Repository Health
Technical Analysis
smartstring provides SmartString, a wrapper around Rust’s standard String that stores short strings inline in the same stack space a String would occupy, automatically promoting to a heap-allocated String once the text grows past the inline capacity (up to 23 bytes on 64-bit platforms). This avoids heap allocations for short strings and keeps data on the stack for better cache locality.
Crucially, a SmartString is exactly the same size as a String and needs no external discriminant, so converting between the two is a zero-cost operation. It is source-compatible with std::string::String, making it a near drop-in replacement in performance-sensitive code.
What You Get
- A
SmartStringtype that is source-compatible withstd::string::String - Inline storage of short strings (up to 23 bytes on 64-bit) with no heap allocation
- The same stack size as
Stringand zero-cost conversion between the two - Configurable layout via the
CompactandLazyCompactmodes - Optional serde, proptest, and arbitrary integrations, plus
no_stdsupport
Common Use Cases
- Replacing
Stringin hot paths that handle many short strings - Reducing allocator pressure in parsers, tokenizers, and interpreters
- Improving cache locality for string-heavy data structures
Under The Hood
Architecture - The crate splits its representation across inline.rs (stack-stored short strings), boxed.rs (heap-promoted String), and marker_byte.rs, which encodes whether a value is inline or boxed inside the string’s own bytes so no extra discriminant is needed. casts.rs reinterprets between the two layouts, config.rs defines the Compact/LazyCompact promotion policies, and ops.rs/iter.rs reimplement the String operations over this union.
Tech Stack - Written in Rust (edition 2021, rust-version 1.57) with a build.rs. It depends only on static_assertions to compile-time-verify size and layout invariants; serde, arbitrary, and proptest are optional integration features. Benchmarks are wired through a custom harness.
Code Quality - This is layout-sensitive unsafe code, and the crate guards it accordingly: static_assertions enforce size guarantees, and the test suite uses proptest (with checked-in regression seeds) plus arbitrary for fuzzing string operations against the standard String. The design is documented carefully because correctness hinges on the marker-byte trick.
API Design - SmartString deliberately mirrors std::string::String, so most code can switch by changing a type alias, and conversions to/from String are From impls that are zero-cost. The only real decision a user makes is choosing Compact versus LazyCompact. Documentation on docs.rs is detailed, and the same-size, same-API framing keeps the learning curve low despite the sophisticated internals.