Crates.io | local_vec |
lib.rs | local_vec |
version | 0.5.0 |
source | src |
created_at | 2021-08-23 20:25:22.384153 |
updated_at | 2022-01-22 07:47:21.750689 |
description | fixed-capacity vector allocated on the stack |
homepage | |
repository | https://github.com/m-rinaldi/local_vec |
max_upload_size | |
id | 441383 |
size | 41,340 |
local_vec
A fixed-capacity vector whose elements are stored locally. In particular, they can be allocated on the stack.
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.
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 <--|
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.