How to easily copy a non-mut &[u8] into to a &mut [u8]

738 views Asked by At

I want to do some manipulations on a &mut [u8].

In my testing code I have:

#[test]
fn test_swap_bytes() {
    let input: &[u8] = b"abcdef";
    let result: &mut[u8] = ?;
    do_something(result);
    assert_eq!(b"fedcba", result);
}

How can I easily get a mutable u8 slice in this case? What should I put on the place of the question mark?

2

There are 2 answers

0
oli_obk On BEST ANSWER

You can use the fact that a binary literal knows its size at compile-time. Therefor you can dereference it and store it on the stack. Any let binding can also be a mutable let binding.

let mut input: [u8; 6] = *b"abcdef";

See PlayPen for a fully working example

Note that there's no reason to specify the type, I just showed it for clarity.

0
Veedrac On

I would use to_owned():

#[test]
fn test_swap_bytes() {
    let input: &[u8] = b"abcdef";
    let result: &mut[u8] = &mut input.to_owned();
    do_something(result);
    assert_eq!(b"fedcba", result);
}

Evidently this creates a copy (through an intermediate Vec), since the input is immutable.