split-spare

Crates.iosplit-spare
lib.rssplit-spare
version0.1.0
created_at2025-10-01 23:24:26.163413+00
updated_at2025-10-01 23:24:26.163413+00
descriptionA trait to allow referencing the already initialized part of a collection while pushing into it's reserved capacity.
homepage
repositoryhttps://github.com/mickvangelderen/split-spare
max_upload_size
id1863635
size10,959
Mick van Gelderen (mickvangelderen)

documentation

README

Allows referring to already initialized elements in a Vec<T> and similar data-types while pushing more elements into its reserved capacity.

// Create a vec with 3 elements.
let mut vec = vec![1, 2, 3];

// Reserve room for 3 more elements and split the vec into initialized and spare parts.
let (init, mut spare) = vec.reserve_split_spare(3);

assert_eq!(init, &[1, 2, 3]);

// Add the initial vec length to the initial elements, and push those new elements into the reserved space.
spare.extend(init.iter().copied().map(|i| i + init.len()));

assert_eq!(vec, &[1, 2, 3, 4, 5, 6]);

Without this library, you can't use Extend because it mutably borrows the Vec<T> that you need to read items out of (index). You would have to write something like:

let mut vec = vec![1, 2, 3];

let init_len = vec.len();

vec.reserve(init_len);

for i in 0..init_len {
    let item = vec[i];
    vec.push(item + init_len);
}

assert_eq!(vec, &[1, 2, 3, 4, 5, 6]);
Commit count: 0

cargo fmt