4 releases (2 stable)

1.1.0 Sep 1, 2020
1.0.0 Aug 15, 2020
0.2.1 Aug 10, 2020
0.2.0 Aug 10, 2020
0.1.0 Aug 5, 2020

#405 in Memory management

GPL-3.0-or-later

115KB
2.5K SLoC

Heapnotize

A Rust library providing memory allocation on the stack.

Heapnotize can be used to store values somewhere in memory while keeping a reference to them. Like Box, it can be used for nested types for which indirection is required. Unlike Box, this library is implemented with #[no_std] and thus it can help with memory management on microcontrollers.

The two main data types of Heapnotize are Rack and Unit. Rack is used to allocate predefined chunk of the stack for a predefined type. Unit provides an ownership for values stored there. Unit also ensures that once it goes out of scope, the value it refers to will be properly dropped.

Documentation:

Usage

Add the following to your Cargo.toml:

[dependencies]
heapnotize = "1.1"

In order to store values on the stack, we first need to initialize the Rack with a specific capacity. Available capacities are currently powers of 2 from 1 up to 1024. The whole size will be allocated when a Rack is created. After that, it is possible to store values on the rack and get a handle on them as Unit object. It is the possible to derefence the Unit to get access to the value. Once the Unit gets out of scope, the value would be freed from the rack:

fn main() {
    let rack = Rack64::new();
    let unit = rack.must_add(10);
    assert_eq!(*unit, 10);
}

Where Heapnotize may become really handy is when dealing with recursive types, where a type contains a value of the same time. Rust cannot know how much memory a recursive type requires on compile time, therefore, indirection must be used. This is nicely covered in The Book where Box is used to enable this, that however requires use of the heap. The following example shows how to handle recursive types on the stack using Rack and Unit:

enum List<'a> {
    Cons(i32, Unit<'a, List<'a>>),
    Nil,
}

use List::{Cons, Nil};

fn main() {
    let rack = Rack64::new();
    let list = Cons(1, rack.must_add(Cons(2, rack.must_add(Cons(3, rack.must_add(Nil))))));
}

See the documentation to learn more.

License

Heapnotize is distributed under the terms of the General Public License version 3. See LICENSE for details.

Changelog

Read the CHANGELOG.md to learn about changes introduced in each release.

No runtime deps