Crate inlinable_string [−] [src]
The inlinable_string crate provides the
InlinableString type — an owned,
grow-able UTF-8 string that stores small strings inline and avoids
heap-allocation — and the
StringExt trait which abstracts
string operations over both std::string::String and InlinableString (or
even your own custom string type).
StringExt's API is mostly identical to std::string::String; unstable and
deprecated methods are not included. A StringExt implementation is
provided for both std::string::String and InlinableString. This enables
InlinableString to generally work as a drop-in replacement for
std::string::String and &StringExt to work with references to either
type.
Examples
use inlinable_string::{InlinableString, StringExt}; // Small strings are stored inline and don't perform heap-allocation. let mut s = InlinableString::from("small"); assert_eq!(s.capacity(), inlinable_string::INLINE_STRING_CAPACITY); // Inline strings are transparently promoted to heap-allocated strings when // they grow too big. s.push_str("a really long string that's bigger than `INLINE_STRING_CAPACITY`"); assert!(s.capacity() > inlinable_string::INLINE_STRING_CAPACITY); // This method can work on strings potentially stored inline on the stack, // on the heap, or plain old `std::string::String`s! fn takes_a_string_reference(string: &mut StringExt) { // Do something with the string... string.push_str("it works!"); } let mut s1 = String::from("this is a plain std::string::String"); let mut s2 = InlinableString::from("inline"); // Both work! takes_a_string_reference(&mut s1); takes_a_string_reference(&mut s2);
Porting Your Code
If
my_stringis always on the stack:let my_string = String::new();→let my_string = InlinableString::new();fn foo(string: &mut String) { ... }→fn foo(string: &mut StringExt) { ... }fn foo(string: &str) { ... }does not need to be modified.struct S { member: String }is a little trickier. IfSis always stack allocated, it probably makes sense to makememberbe of typeInlinableString. IfSis heap-allocated andmemberis always small, consider using the more restrictiveInlineStringtype. Ifmemberis not always small, then it should probably be left as aString.
Serialization
InlinableString implements serde's Serialize and Deserialize traits.
Add the serde feature to your Cargo.toml to enable serialization.
Reexports
pub use inline_string::INLINE_STRING_CAPACITY; |
pub use inline_string::InlineString; |
pub use string_ext::StringExt; |
Modules
| inline_string |
A short UTF-8 string that uses inline storage and does no heap
allocation. It may be no longer than |
| string_ext |
A trait that exists to abstract string operations over any number of concrete string type implementations. |
Enums
| InlinableString |
An owned, grow-able UTF-8 string that allocates short strings inline on the stack. |