Skip to content

Commit

Permalink
Added splicing helper that uses Clone instead of Copy.
Browse files Browse the repository at this point in the history
  • Loading branch information
Michael Rodler committed Jan 24, 2024
1 parent 958ba95 commit 20470ab
Showing 1 changed file with 39 additions and 0 deletions.
39 changes: 39 additions & 0 deletions src/mutators/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,45 @@ pub fn splice_extend<C: Copy>(
Some(((dst_start..dst_end), (src_start..src_end)))
}

/// Copy a random sub-slice from `src` into a random subslice of `dst`.
/// This will potentially grow or shrink the destination vector.
/// This will call clone on every element. Use [`splice_extend`] if your type is `Copy` for better
/// performance.
#[inline]
pub fn splice_clone_extend<C: Clone>(
dst: &mut Vec<C>,
src: &[C],
rng: &mut impl rand::Rng,
) -> Option<(std::ops::Range<usize>, std::ops::Range<usize>)> {
if src.is_empty() {
return None;
}

let src_start = rng.gen_range(0..src.len());
let src_end = rng.gen_range(src_start..=src.len());
if dst.is_empty() {
dst.extend(
src.iter()
.skip(src_start)
.take(src_end - src_start)
.cloned(),
);
return Some((0..0, src_start..src_end));
}

let dst_start = rng.gen_range(0..dst.len());
let dst_end = rng.gen_range(dst_start..=dst.len());

dst.splice(
dst_start..dst_end,
src.iter()
.skip(src_start)
.take(src_end - src_start)
.cloned(),
);
Some(((dst_start..dst_end), (src_start..src_end)))
}

/// Copy sub-slice from another slice into the current one.
///
/// # returns
Expand Down

0 comments on commit 20470ab

Please sign in to comment.