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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With