local_vec

Crates.iolocal_vec
lib.rslocal_vec
version0.5.0
sourcesrc
created_at2021-08-23 20:25:22.384153
updated_at2022-01-22 07:47:21.750689
descriptionfixed-capacity vector allocated on the stack
homepage
repositoryhttps://github.com/m-rinaldi/local_vec
max_upload_size
id441383
size41,340
J. Rinaldi (m-rinaldi)

documentation

README

local_vec

A fixed-capacity vector whose elements are stored locally. In particular, they can be allocated on the stack.

License: MIT Build Status


LocalVec is a fixed-capacity vector, i.e., its size or length increases and decreases as elements are pushed into and popped from the vector, respectively. However, its capacity always remains the same and must be determined at compile time.

The elements of a LocalVec are stored on a local buffer inside the LocalVec itself, not on a remote buffer allocated on the heap.


LocalVec vs Vec

LocalVec's elements reside locally, i.e., inside it:

use local_vec::LocalVec;
let mut vec = LocalVec::<_, 4>::new();
vec.push(3);
vec.push(7);

vec contents in the code above are:

That is, vec has a local buffer, and the i32 values 3 and 7 are stored inside vec itself, not in a remotely-allocated buffer on the heap.

In contrast, Vec allocates a remote buffer on the heap and contains a pointer to that buffer instead of the buffer itself:

let mut v = Vec::with_capacity(4);
v.extend([3, 7]);

That is, v points to a remote buffer, and the i32 values 3 and 7 are stored on that remote buffer, which is allocated on the heap.

Compile-time capacity

Since the size of a LocalValue depends on its capacity, the capacity of a LocalVec must be determined at compile time. This is achieved with a constant generic argument thanks to const generics:

let mut vec = LocalVec::<i32, 4>::new();
                              |
    const generic argument <--|

Allocating on the Stack or the Heap

Technically, the elements LocalVec contains are stored locally in the LocalVec. Whether or not these elements are on the stack depends on whether the LocalVec itself is allocated on the stack. For example:

let vec = Box::new(LocalVec::<u8, 32>::new());

vec is allocated on the heap, and so are the elements it contains because they are stored inside vec itself. There isn't an additional heap allocation as it would have been the case with Vec, though.

Commit count: 22

cargo fmt