I have two adjacent slices in memory. I know they are adjacent because I just created them from a single slice with split_at
. I want to concatenate them together to get a slice covering the whole range again. Is there any way I can do that safely? Ideally, some function that takes multiple slices, sees if they are adjacent to each other, and merges them together if possible.
fn main() {
let original_slice: &[u8] = &[1, 2, 3, 4];
let (left, right) = original_slice.split_at(2);
let rejoined_slice = todo!("take left and right and return an Option or similar")
assert_eq!(original_slice, rejoined_slice);
assert_eq!(original_slice.as_ptr(), rejoined_slice.as_ptr());
}
This is coming up for me using the zerocopy
crate to do some zero-copy parsing. I sometimes end up with multiple slices of the same type that I know are next to each other (after all, I just parsed them, checked their alignment, etc.), and it would be useful to fuse them together.
Not a duplicate of this question: I don't want to end up with a new Vec
, I want to fuse the already-adjacent slices in place without copying.