frame_mem_utils
This crate provides methods to work with memory allocation without directly calling heap methods. This allows making arenas entirely on the stack, and it is up to you to decide where the memory would come from.
All types used are actively avoiding dereferencing their internal pointers which allows making references to them elsewhere, this allows for some fairly neat things with unsafe code.
Usage
Here are a couple of examples demonstrating how to use frame_mem_utils.
Saving Slices
You can use StackAlloc to save slices of data of any type that is Clone. This is useful for storing variable-sized data in a stack-based arena.
use StackAlloc;
use make_storage;
use MaybeUninit;
// 1. Create a backing memory buffer on the stack.
// `make_storage` is a convenience function to create an uninitialized array.
let mut buffer: = make_storage;
// 2. Create a StackAlloc arena from the buffer.
let mut arena = from_slice;
// 3. Save a slice of data into the arena.
let saved_slice = arena.save.expect;
// The saved vec is a `RefBox`, which acts like a Box<Vec> and would be cleaned up.
assert_eq!;
// You can also save other data types, like a string slice.
let my_string = "hello world";
let saved_string_slice = arena.save_slice.expect;
assert_eq!;
Writing Formatted Strings
For building strings, StackWriter provides an efficient way to write formatted text directly into the arena, similar to std::fmt::Write.
use ;
use make_storage;
use MaybeUninit;
use Write;
// 1. Create a backing memory buffer.
let mut buffer: = make_storage;
// 2. Create a StackAlloc arena.
let mut arena = from_slice;
// 3. Create a writer.
let mut writer = new;
// 4. Write formatted strings into the arena.
write!.unwrap;
let formatted_str = writer.finish;
assert_eq!;
// The arena can still be used for other allocations.
let data = arena.save.expect;
assert_eq!;
Using StackVec
StackVec provides a Vec-like API on a fixed-size buffer, growing upwards. It's useful when you need a standard vector-like structure without heap allocation.
use ;
use MaybeUninit;
// 1. Create a backing memory buffer on the stack.
let mut buffer: = make_storage;
// 2. Create a StackVec from the buffer.
let mut vec = from_slice;
// 3. Push some values.
vec.push.unwrap;
vec.push.unwrap;
vec.push_slice.unwrap;
// 4. Access elements like a slice.
assert_eq!;
assert_eq!;
// 5. Pop values off the end.
assert_eq!;
assert_eq!;
assert_eq!;