split-spare 0.1.0

A trait to allow referencing the already initialized part of a collection while pushing into it's reserved capacity.
Documentation
  • Coverage
  • 12.5%
    1 out of 8 items documented0 out of 5 items with examples
  • Size
  • Source code size: 10.46 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.46 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Links
  • mickvangelderen/split-spare
    0 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • mickvangelderen

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]);