smallbox
Box dynamically-sized types on stack. Requires nightly rust.
Store or return trait-object and closure without heap allocation, and fallback to heap when thing goes too large.
Documentation
Usage
First, add the following to your Cargo.toml:
[]
= "0.2"
Next, add this to your crate root:
extern crate smallbox;
Currently smallbox by default links to the standard library, but if you would
instead like to use this crate in a #![no_std] situation or crate, and want to
opt out heap dependency and SmallBox<T> type, you can request this via:
[]
= { = "0.2", = false }
Enable heap feature for #![no_std] build to link alloc crate
and bring SmallBox<T> back.
[]
= "0.2"
= false
= ["heap"]
Feature Flags
The arraydeque crate has the following cargo feature flags:
-
std- Optional, enabled by default
- Use libstd
-
heap- Optional
- Use heap fallback and include
SmallBox<T>type, and link toalloccrate ifstdfeature flag is opted out.
Overview
This crate delivers two core type:
StackBox<T>: Represents a fixed-capacity allocation, and on stack stores dynamically-sized type.
The new method on this type allows creating a instance from a concrete type,
returning Err(value) if the instance is too large for the allocated region.
So far, the fixed-capcity is about four words (4 * sizeof(usize))
SmallBox<T>: Takes StackBox<T> as an varience, and fallback to Box<T> when type T is too large for StackBox<T>.
Example
The simplest usage can be trait object dynamic-dispatch
use StackBox;
let val: = new.unwrap;
assert!
One of the most obvious use case is to allow returning capturing closures without having to box them.
use StackBox;
let closure = make_closure;
assert_eq!;
The other use case is to eliminate heap alloction for small things, except that
the object is large enough to allocte.
In addition, the inner StackBox<T> or Box<T> can be moved out by explicitely pattern matching on SmallBox<T>.
use SmallBox;
let tiny: = new;
let big: = new;
assert_eq!;
assert_eq!;
match tiny
match big
Roadmap
- method that convert SmallBox to Box
- conveniently convert bewteen
SmallBox<T>andStackBox<T> - configurable
StackBox<T>allocation size - dowancasting for
StackBox<Any>andSmallBox<Any>
Contribution
All kinds of contribution are welcome.
- Issue Feel free to open an issue when you find typos, bugs, or have any question.
- Pull requests. Better implementation, more tests, more documents and typo fixes are all welcome.
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or http://opensource.org/licenses/MIT)
at your option.