Peter Smit
Peter Smit

Reputation: 28736

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

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?

Upvotes: 4

Views: 823

Answers (2)

oli_obk
oli_obk

Reputation: 31263

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.

Upvotes: 9

Veedrac
Veedrac

Reputation: 60177

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.

Upvotes: 6

Related Questions