#vec #allocation #data #recycle #lifetime #extension #change

recycle_vec

Provides a method for Vec to recycle it's backing allocation for use with another Vec of different type

8 stable releases

1.1.2 Oct 28, 2024
1.1.1 Mar 16, 2024
1.0.4 Nov 3, 2019
1.0.1 Nov 2, 2019
1.0.0 Oct 31, 2019

#130 in Memory management

Download history 1/week @ 2024-09-17 8/week @ 2024-09-24 3/week @ 2024-10-01 74/week @ 2024-10-22 65/week @ 2024-10-29 2/week @ 2024-11-05

141 downloads per month
Used in vec_storage_reuse

MIT license

9KB
65 lines

recycle_vec

Note: There used to be an RFC for making this functionality a part of the standard library. However, it was closed because 1) an additional API as little as this doesn't need a full RFC anymore 2) but the capabilities of the language around checking invariants statically aren't there yet, so the API would be suboptimal and therefore it's best to wait for the const generics and static checking stuff to catch up.

This crate provides a recycle extension method for Vec. It's intended to change the type of the Vec while "recycling" the underlying allocation. This is a trick that is useful especially when storing data with short lifetimes in Vec:

    let mut objects: Vec<Object<'static>> = Vec::new();

    while let Some(byte_chunk) = stream.next() { // byte_chunk only lives this scope
        let mut objects_temp: Vec<Object<'_>> = objects.recycle();

        // Zero-copy parsing; Object has references to chunk
        deserialize(byte_chunk, &mut objects_temp)?;
        process(&objects_temp)?;

        objects = objects_temp.recycle();
    } // byte_chunk lifetime ends

Notes about safety

This crate uses internally unsafe to achieve it's functionality. However, it provides a safe interface. To achieve safety, it does the following precautions:

  1. It truncates the Vec to zero length, dropping all the values. This ensures that no values of arbitrary types are transmuted accidentally.
  2. It checks that the sizes and alignments of the source and target types match. This ensures that the underlying block of memory backing Vec is compatible layout-wise. The sizes and alignments are checked statically, so if the compile will fail in case of a mismatch.
  3. It creates a new Vec value using from_raw_parts instead of transmuting, an operation whose soundness would be questionable.

No runtime deps