collect/
collect.rs

1/* Dumb program to show one of the uses of the TinyVec.
2 *
3 * Sometimes you need to collect some elements (e.g. Collecting an
4 * iterator), temporarily. But you are not going to store them for a
5 * long time.
6 * The naive approach is to use a Vec. The problem is that when we are
7 * dealing with an small amount of elements, a vec can be overkill.
8 *
9 * In the example bellow, we perform 2 runs. One with the default stack
10 * size for the vector. This is, using only the minimun required stack size.
11 * 24 bytes. 8 bytes for a poiter, 8 for the length and 8 for capacity.
12 *
13 * By using tiny-vec, we managed to avoid memory allocations in two cases.
14 *
15 * The second run uses a slightly higher stack buffer (32 bytes), and only
16 * needs to allocate memory on 1 of the iterations.
17 *
18 * I think is really useful, and amazing! Specially the first case, since it
19 * doesn't even use extra stack space, but avoids allocations for iterators
20 * with up to 8 elements.
21 *
22 * NOTE: I know this is a dumb example, since all those operations could've been
23 * done without any kind of vector, just maping the iterator. But the TinyVec has
24 * practical applications... I PROMISE!
25 */
26
27use core::mem;
28use core::ops::Range;
29
30use tiny_vec::{TinyVec};
31
32fn mutate_slice(slice: &mut [u16]) {
33    for e in slice {
34        *e *= 2;
35    }
36}
37
38fn process_iter<const N: usize>(range: Range<u16>) {
39    let mut collected: TinyVec<u16, N> = range.clone().collect();
40    mutate_slice(&mut collected);
41    println!("\n  Range: {range:?} ({} elements)", range.end - range.start);
42    println!("  Result: {collected:?}\n  Used heap: {}", !collected.lives_on_stack());
43}
44
45fn run<const N: usize>() {
46    process_iter::<N>(0..10);
47    process_iter::<N>(3..11);
48    process_iter::<N>(0..30);
49    process_iter::<N>(4..7);
50}
51
52pub fn main() {
53    const DEF: usize = tiny_vec::n_elements_for_stack::<u16>();
54    let stack_size: usize = mem::size_of::<TinyVec<u16, DEF>>();
55    println!("Using a TinyVec with the default stack size ({DEF}). (Size = {stack_size})");
56    run::<DEF>();
57
58    let stack_size: usize = mem::size_of::<TinyVec<u16, 10>>();
59    println!("\nUsing a TinyVec with a custom stack size of 10. (Size = {stack_size})");
60    run::<10>();
61}