Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Peter Smit Avatar asked Dec 06 '22 21:12

Peter Smit


2 Answers

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.

like image 139
oli_obk Avatar answered Dec 22 '22 00:12

oli_obk


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.

like image 33
Veedrac Avatar answered Dec 21 '22 23:12

Veedrac