alloc-once 0.1.0-rc.1

Allocate several different-typed values in one bump allocation, returned as a self-owning guard.
Documentation
  • Coverage
  • 100%
    2 out of 2 items documented1 out of 2 items with examples
  • Size
  • Source code size: 10.13 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 312.53 kB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 5s Average build duration of successful builds.
  • all releases: 5s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • tinybeachthor/alloc-once
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • tinybeachthor

alloc-once

Allocate several values of different types in a single bump allocation, and get back a guard that owns the memory and frees it (running destructors) when it drops.

use alloc_once::alloc_once;

let mut guard = alloc_once!(
    7i32,
    [1u8, 2, 3, 4],
    "hello",
);

// Deref to the tuple, then destructure into independent &mut references.
let (count, bytes, label) = &mut *guard;
*count += 100;
bytes[0] = 99;

assert_eq!(*count, 107);
assert_eq!(bytes[0], 99);
assert_eq!(*label, "hello");

// `guard` drops here: it runs each value's destructor, then frees the arena.

No arena to thread through your code, no bumpalo in your dependency list — alloc_once! hides all of it.

How it works

alloc_once!(a, b, c) packs the values into one tuple (a, b, c), creates a bumpalo arena sized to exactly the bytes that tuple needs (Bump::with_capacity(size_of_val(&tuple))), allocates the tuple in a single bump, and returns an AllocOnce<T> guard.

  • One allocation, exact size. The tuple layout is fixed at compile time, so the arena reserves a single chunk of precisely the needed bytes.
  • A guard that owns the arena. AllocOnce<T> derefs to the tuple (&*guard / &mut *guard). When it drops it runs the value's destructor and then frees the arena — unlike a raw Bump::alloc, whose values are never dropped.
  • bumpalo stays hidden. You depend only on alloc-once; the macro expands to paths inside this crate, so your code and Cargo.toml never mention bumpalo.

Caveats

  • Exact capacity is a request. bumpalo may round the underlying chunk up slightly for its own bookkeeping; the guarantee is that the bundle fits in the first chunk with no second allocation.
  • Lifetime is the guard's. All references borrow from the guard, so the guard must outlive them (the borrow checker enforces this).

License

Licensed under either of MIT or Apache-2.0 at your option.