12

Is there a safe way to left-shift elements of a vector in Rust? (vec![1, 2, 3] becomes vec![3] when left-shifted two places). I'm dealing with Copy types, and I don't want to pay a penalty higher than what I would with a memmove.

The only solution I've found is unsafe: use memmove directly via ptr::copy.

hippietrail
  • 15,848
  • 18
  • 99
  • 158
Doe
  • 585
  • 5
  • 19

1 Answers1

15

I would use Vec::drain.

You can call it with a range of the elements you want to remove, and it'll shift them over afterwards. Example: (playpen)

fn main() {
    let mut v = vec![1, 2, 3];

    v.drain(0..2);

    assert_eq!(vec![3], v);
}

One other note:

I'm dealing with Copy types, and I don't want to pay a penalty higher than what I would with a memmove.

Worth noting that moving is always a memcpy in Rust, so the Copy vs non-Copy distinction doesn't matter here. It'd be the same if the types weren't Copy.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Steve Klabnik
  • 14,521
  • 4
  • 58
  • 99