#in-place #vec #array #array-vec

inplace-vec-builder

Build a vec from a vec, in place

2 releases

0.1.1 Nov 27, 2021
0.1.0 Nov 25, 2021

#1785 in Data structures

Download history 7655/week @ 2024-03-14 8073/week @ 2024-03-21 8881/week @ 2024-03-28 8855/week @ 2024-04-04 9806/week @ 2024-04-11 8948/week @ 2024-04-18 8574/week @ 2024-04-25 8686/week @ 2024-05-02 7380/week @ 2024-05-09 7596/week @ 2024-05-16 5990/week @ 2024-05-23 7970/week @ 2024-05-30 8421/week @ 2024-06-06 6710/week @ 2024-06-13 5780/week @ 2024-06-20 5913/week @ 2024-06-27

28,509 downloads per month
Used in 38 crates (3 directly)

MIT/Apache

21KB
450 lines

Inplace-Vec-Builder

A small library to build a Vec or SmallVec out of itself without allocating.

This is useful when writing in place operations that do not allocate.

Imagine you have a vec that contains some numbers. You now want to apply some transformation on these elements, like mapping, filtering, adding some elements, and then store the result in the same place.

The simplest way to do this would be something like this:

        let mut res = self
            .elements
            .iter()
            .filter(|x| **x > 5)
            .map(|x| *x * 2)
            .chain(std::iter::once(123))
            .collect();
        std::mem::swap(&mut self.elements, &mut res);

But this does allocate a new vector. Usually not a big deal, but if this is some very frequently used code, you want to avoid it.

Note that in many cases where you do filtering combined with a transformation, retain can be used. If that is the case using retain is of course preferable.

This crate provides a helper that allows doing something like the above without allocations. It is fairly low level, since it is intended to be used from other libraries.

        let mut t = InPlaceVecBuilder::from(&mut self.elements);
        while let Some(elem) = t.pop_front() {
            if elem > 5 {
                t.push(elem * 2);
            }
        }
        t.push(123);

Features

  • stdvec (default): std Vec support
  • smallvec: SmallVec support

Dependencies

~19KB