6

If I have a vector such as

let mut bytes = vec![0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];

I want to separate the vector by the 0x40 separator. Is there a clean way of doing this functionality?

expected output: [[0x01, 0x02, 0x03], [0x04, 0x05], [0x06]]

felipsmartins
  • 12,429
  • 4
  • 44
  • 52
  • Take a look at [`Vec::split`](https://doc.rust-lang.org/std/vec/struct.Vec.html#method.split) – Brian Feb 17 '20 at 16:39

1 Answers1

6

Use slice::split:

fn main() {
    let bytes = [0x01, 0x02, 0x03, 0x40, 0x04, 0x05, 0x40, 0x06, 0x40];
    let pieces: Vec<_> = bytes
        .split(|&e| e == 0x40)
        .filter(|v| !v.is_empty())
        .collect();
    println!("{:?}", pieces)
}

See also:

Shepmaster
  • 326,504
  • 69
  • 892
  • 1,159