25 releases

0.11.0 Sep 29, 2024
0.10.0 Oct 14, 2023
0.9.1 Oct 4, 2023
0.9.0 Feb 24, 2023
0.1.1 Mar 29, 2022

#36 in Memory management

Download history 14477/week @ 2024-07-11 15529/week @ 2024-07-18 16772/week @ 2024-07-25 16517/week @ 2024-08-01 15107/week @ 2024-08-08 16208/week @ 2024-08-15 16078/week @ 2024-08-22 17322/week @ 2024-08-29 19716/week @ 2024-09-05 17532/week @ 2024-09-12 19231/week @ 2024-09-19 18056/week @ 2024-09-26 18492/week @ 2024-10-03 19371/week @ 2024-10-10 17660/week @ 2024-10-17 14353/week @ 2024-10-24

73,145 downloads per month
Used in 174 crates (28 directly)

MIT license

63KB
1.5K SLoC

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

  • nightly: enables the allocator backend for the memory buffers.

Examples

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

// 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 stack = DynStack::new(&mut buf);

{
    // We can have nested allocations.
    // 3×`i32`
    let (array_i32, substack) = stack.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.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.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

~140KB