1 unstable release
0.1.1 | Mar 27, 2024 |
---|---|
0.1.0 |
|
#715 in Memory management
21 downloads per month
Used in portal-tunneler
81KB
2K
SLoC
Types for inlining small collections for avoiding unnecessary heap allocations.
It is common to need to use a vector to store a few small elements and end up using a [Vec
].
This type allocates memory on the heap, and if you're only using a few elements then it is more
efficient to use the stack, or inline the vector into whatever structure you're operating on.
For example, domain names are typically less than 100 characters and cannot be over 255.
Instead of using String
, that allocates memory on the heap both on creation and on clone,
you can use a TinyString::<255>
, a 256-byte structure that can store up to 255
bytes using inline memory, and cloning is as simple as copying memory:
use inlined::TinyString;
use std::fmt::Write;
let mut s = TinyString::<32>::new(); // 32 is the maximum length of the string
s.push_str("Hello!");
assert_eq!(s.as_str(), "Hello!");
let _ = write!(s, " Your number is {}.", 1234);
assert_eq!(s.as_str(), "Hello! Your number is 1234.")
Provided types
This crate contains the following types:
- The
InlineVec
andInlineString
types are analogous to [Vec
] andString
from the standard library, but are inlined and have a constant, limited capacity. - The
TinyVec
andTinyString
types work much the same way, but use anu8
for the length instead of anusize
. This makes them more optimal for passing around, or inlining them into other structs. - The
CompactVec
is a type that brings together [Vec
] andTinyVec
, representing a vector that stores up toN
elements inline, but if more capacity is needed will spill into the heap and allocate memory.
Since all of these implement Deref
for either &[T]
or &str
, they
contain many of the methods you're used to having from [Vec
] and String
.
Specifying the capacity
All these types make use of const generics to specify their inline capacity. This means you can choose the maximum amount of elements you want your inlined type to store. Whether you want to store just 3, 100, or even thousands of elements, the same types have got you covered.