macro_rules! mut_array_refs {
( $arr:expr, $( $pre:expr ),* ; .. ; $( $post:expr ),* ) => { ... };
( $arr:expr, $( $len:expr ),* ) => { ... };
}
Expand description
You can use mut_array_refs
to generate a series of mutable array
references to an input mutable array reference. The idea is if
you want to break an array into a series of contiguous and
non-overlapping mutable array references. Like array_refs!
,
mut_array_refs!
is a bit funny in that it insists on slicing up
the entire array. This is intentional, as I find it handy to
make me ensure that my sub-arrays add up to the entire array.
This macro will never panic, since the sizes are all checked at
compile time.
Note that unlike array_mut_ref!
, mut_array_refs
requires
that the first argument be a mutable array reference. The
following arguments are the lengths of each subarray you wish a
reference to. The total of these arguments must equal the size
of the array itself. Also note that this macro allows you to take
out multiple mutable references to a single object, which is both
weird and powerful.
#[macro_use]
extern crate arrayref;
fn write_u16(bytes: &mut [u8; 2], num: u16) {
bytes[0] = num as u8;
bytes[1] = (num >> 8) as u8;
}
fn write_u32(bytes: &mut [u8; 4], num: u32) {
bytes[0] = num as u8;
bytes[1] = (num >> 8) as u8; // this is buggy to save space...
}
// ...
let mut data = [0,1,2,3,4,0,6,7];
let (a,b,c) = mut_array_refs![&mut data,2,2,4];
// let's write out some nice prime numbers!
write_u16(a, 37);
write_u16(b, 73);
write_u32(c, 137); // approximate inverse of the fine structure constant!