I have src: Vec<Foo>
and dst: &mut [Foo]
. I want to move as many elements as possible from src
into dst
. Specifically:
src
is shorter than dst
, then the beginning of dst
should be replaced with what was in src
(leaving the rest of dst
as-is), and src
should end up empty.src
and dst
are the same length, all of the values in dst
should be replaced with what was in src
, and src
should end up empty.src
is longer than dst
, all of the values in dst
should be replaced with what was in the beginning of src
, and src
should be left with only the elements that didn't fit.For example, pretending Foo
was i32
(but it should work for non-Copy
types too):
src
starts as [1,2]
and dst
starts as [7,8,9,10]
, src
should end up as []
and dst
should end up as [1,2,9,10]
.src
starts as [1,2,3,4]
and dst
starts as [7,8,9,10]
, src
should end up as []
and dst
should end up as [1,2,3,4]
.src
starts as [1,2,3,4,5,6]
and dst
starts as [7,8,9,10]
, src
should end up as [5,6]
and dst
should end up as [1,2,3,4]
.I know I could loop manually and move one element at a time, but it seems like there should be a Drain
-like approach instead.
This is easy to do just by figuring out how many elements you can move (which is the minimum of both lengths) and then using drain
to remove those elements and place them in the destination.
pub fn move_many<T>(src: &mut Vec<T>, dst: &mut [T]) {
let count = src.len().min(dst.len());
for (s, d) in src.drain(0..count).zip(dst) {
*d = s;
}
}