#array #vec #inplace

inplace-vec-builder

Build a vec from a vec, in place

2 releases

Uses new Rust 2021

0.1.1 Nov 27, 2021
0.1.0 Nov 25, 2021

#1086 in Data structures

Download history 18/week @ 2022-01-24 24/week @ 2022-01-31 25/week @ 2022-02-07 10/week @ 2022-02-14 9/week @ 2022-02-21 12/week @ 2022-02-28 67/week @ 2022-03-07 15/week @ 2022-03-14 73/week @ 2022-03-21 15/week @ 2022-03-28 13/week @ 2022-04-04 18/week @ 2022-04-11 16/week @ 2022-04-18 405/week @ 2022-04-25 26/week @ 2022-05-02 17/week @ 2022-05-09

466 downloads per month
Used in 6 crates (2 directly)

MIT/Apache

20KB
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

~20KB