#stack #allocation #unsized #array #slice

dyn-stack

Dynamic stack wrapper for unsized allocations

21 releases (7 breaking)

Uses new Rust 2021

0.8.3 Oct 2, 2022
0.7.0 Aug 19, 2022
0.5.2 Jul 27, 2022
0.1.1 Mar 29, 2022

#210 in Rust patterns

Download history 203/week @ 2022-10-07 239/week @ 2022-10-14 258/week @ 2022-10-21 250/week @ 2022-10-28 439/week @ 2022-11-04 192/week @ 2022-11-11 426/week @ 2022-11-18 464/week @ 2022-11-25 321/week @ 2022-12-02 364/week @ 2022-12-09 120/week @ 2022-12-16 131/week @ 2022-12-23 217/week @ 2022-12-30 184/week @ 2023-01-06 135/week @ 2023-01-13 233/week @ 2023-01-20

794 downloads per month
Used in 14 crates (9 directly)

MIT license

45KB
979 lines

dynstack

Stack that allows users to allocate dynamically sized arrays.

The stack wraps a buffer of bytes that it uses as a workspace. Allocating an array takes a chunk of memory from the stack, which can be reused once the array is dropped.

Features

  • std: enables a std::error::Error implementation for error types.
  • nightly: enables a drop check eye patch for DynArray and enables the allocator backend for the memory buffers.

Examples

use core::mem::MaybeUninit;
use dynstack::{DynStack, StackReq};
use reborrow::ReborrowMut;

// We allocate enough storage for 3 `i32` and 4 `u8`.
let mut buf = [MaybeUninit::uninit();
    StackReq::new::<i32>(3)
        .and(StackReq::new::<u8>(4))
        .unaligned_bytes_required()];
let mut stack = DynStack::new(&mut buf);

{
    // We can have nested allocations.
    // 3×`i32`
    let (array_i32, substack) = stack.rb_mut().make_with::<i32, _>(3, |i| i as i32);
    // and 4×`u8`
    let (mut array_u8, _) = substack.make_with::<u8, _>(4, |_| 0);

    // We can read from the arrays,
    assert_eq!(array_i32[0], 0);
    assert_eq!(array_i32[1], 1);
    assert_eq!(array_i32[2], 2);

    // and write to them.
    array_u8[0] = 1;

    assert_eq!(array_u8[0], 1);
    assert_eq!(array_u8[1], 0);
    assert_eq!(array_u8[2], 0);
    assert_eq!(array_u8[3], 0);
}

{
    // We can also have disjoint allocations.
    // 3×`i32`
    let (mut array_i32, _) = stack.rb_mut().make_with::<i32, _>(3, |i| i as i32);
    assert_eq!(array_i32[0], 0);
    assert_eq!(array_i32[1], 1);
    assert_eq!(array_i32[2], 2);
}

{
    // or 4×`u8`
    let (mut array_u8, _) = stack.rb_mut().make_with::<i32, _>(4, |i| i as i32 + 3);
    assert_eq!(array_u8[0], 3);
    assert_eq!(array_u8[1], 4);
    assert_eq!(array_u8[2], 5);
    assert_eq!(array_u8[3], 6);
}

Dependencies