arrayref/
lib.rs

1//! This package contains just four macros, which enable the creation
2//! of array references to portions of arrays or slices (or things
3//! that can be sliced).
4//!
5//! # Examples
6//!
7//! Here is a simple example of slicing and dicing a slice into array
8//! references with these macros.  Here we implement a simple
9//! little-endian conversion from bytes to `u16`, and demonstrate code
10//! that uses `array_ref!` to extract an array reference from a larger
11//! array.  Note that the documentation for each macro also has an
12//! example of its use.
13//!
14//! ```
15//! #[macro_use]
16//! extern crate arrayref;
17//!
18//! fn read_u16(bytes: &[u8; 2]) -> u16 {
19//!      bytes[0] as u16 + ((bytes[1] as u16) << 8)
20//! }
21//! // ...
22//! # fn main() {
23//! let data = [0,1,2,3,4,0,6,7,8,9];
24//! assert_eq!(256, read_u16(array_ref![data,0,2]));
25//! assert_eq!(4, read_u16(array_ref![data,4,2]));
26//! # }
27//! ```
28#![deny(warnings)]
29#![no_std]
30
31#[cfg(test)]
32#[macro_use]
33extern crate std;
34
35/// You can use `array_ref` to generate an array reference to a subset
36/// of a sliceable bit of data (which could be an array, or a slice,
37/// or a Vec).
38///
39/// **Panics** if the slice is out of bounds.
40///
41/// ```
42/// #[macro_use]
43/// extern crate arrayref;
44///
45/// fn read_u16(bytes: &[u8; 2]) -> u16 {
46///      bytes[0] as u16 + ((bytes[1] as u16) << 8)
47/// }
48/// // ...
49/// # fn main() {
50/// let data = [0,1,2,3,4,0,6,7,8,9];
51/// assert_eq!(256, read_u16(array_ref![data,0,2]));
52/// assert_eq!(4, read_u16(array_ref![data,4,2]));
53/// # }
54/// ```
55
56#[macro_export]
57macro_rules! array_ref {
58    ($arr:expr, $offset:expr, $len:expr) => {{
59        {
60            #[inline]
61            unsafe fn as_array<T>(slice: &[T]) -> &[T; $len] {
62                &*(slice.as_ptr() as *const [_; $len])
63            }
64            let offset = $offset;
65            let slice = & $arr[offset..offset + $len];
66            #[allow(unused_unsafe)]
67            unsafe {
68                as_array(slice)
69            }
70        }
71    }}
72}
73
74/// You can use `array_refs` to generate a series of array references
75/// to an input array reference.  The idea is if you want to break an
76/// array into a series of contiguous and non-overlapping arrays.
77/// `array_refs` is a bit funny in that it insists on slicing up the
78/// *entire* array.  This is intentional, as I find it handy to make
79/// me ensure that my sub-arrays add up to the entire array.  This
80/// macro will *never* panic, since the sizes are all checked at
81/// compile time.
82///
83/// Note that unlike `array_ref!`, `array_refs` *requires* that the
84/// first argument be an array reference.  The following arguments are
85/// the lengths of each subarray you wish a reference to.  The total
86/// of these arguments *must* equal the size of the array itself.
87///
88/// ```
89/// #[macro_use]
90/// extern crate arrayref;
91///
92/// fn read_u16(bytes: &[u8; 2]) -> u16 {
93///      bytes[0] as u16 + ((bytes[1] as u16) << 8)
94/// }
95/// // ...
96/// # fn main() {
97/// let data = [0,1,2,3,4,0,6,7];
98/// let (a,b,c) = array_refs![&data,2,2,4];
99/// assert_eq!(read_u16(a), 256);
100/// assert_eq!(read_u16(b), 3*256+2);
101/// assert_eq!(*c, [4,0,6,7]);
102/// # }
103/// ```
104#[macro_export]
105macro_rules! array_refs {
106    ( $arr:expr, $( $pre:expr ),* ; .. ;  $( $post:expr ),* ) => {{
107        {
108            use std::slice;
109            #[inline]
110            #[allow(unused_assignments)]
111            unsafe fn as_arrays<T>(a: &[T]) -> ( $( &[T; $pre], )* &[T],  $( &[T; $post], )*) {
112                let min_len = $( $pre + )* $( $post + )* 0;
113                let var_len = a.len() - min_len;
114                assert!(a.len() >= min_len);
115                let mut p = a.as_ptr();
116                ( $( {
117                    let aref = & *(p as *const [T; $pre]);
118                    p = p.offset($pre as isize);
119                    aref
120                } ),* , {
121                    let sl = slice::from_raw_parts(p as *const T, var_len);
122                    p = p.offset(var_len as isize);
123                    sl
124                }, $( {
125                    let aref = & *(p as *const [T; $post]);
126                    p = p.offset($post as isize);
127                    aref
128                } ),*)
129            }
130            let input = $arr;
131            #[allow(unused_unsafe)]
132            unsafe {
133                as_arrays(input)
134            }
135        }
136    }};
137    ( $arr:expr, $( $len:expr ),* ) => {{
138        {
139            #[inline]
140            #[allow(unused_assignments)]
141            unsafe fn as_arrays<T>(a: &[T; $( $len + )* 0 ]) -> ( $( &[T; $len], )* ) {
142                let mut p = a.as_ptr();
143                ( $( {
144                    let aref = &*(p as *const [T; $len]);
145                    p = p.offset($len as isize);
146                    aref
147                } ),* )
148            }
149            let input = $arr;
150            #[allow(unused_unsafe)]
151            unsafe {
152                as_arrays(input)
153            }
154        }
155    }}
156}
157
158
159/// You can use `mut_array_refs` to generate a series of mutable array
160/// references to an input mutable array reference.  The idea is if
161/// you want to break an array into a series of contiguous and
162/// non-overlapping mutable array references.  Like `array_refs!`,
163/// `mut_array_refs!` is a bit funny in that it insists on slicing up
164/// the *entire* array.  This is intentional, as I find it handy to
165/// make me ensure that my sub-arrays add up to the entire array.
166/// This macro will *never* panic, since the sizes are all checked at
167/// compile time.
168///
169/// Note that unlike `array_mut_ref!`, `mut_array_refs` *requires*
170/// that the first argument be a mutable array reference.  The
171/// following arguments are the lengths of each subarray you wish a
172/// reference to.  The total of these arguments *must* equal the size
173/// of the array itself.  Also note that this macro allows you to take
174/// out multiple mutable references to a single object, which is both
175/// weird and powerful.
176///
177/// ```
178/// #[macro_use]
179/// extern crate arrayref;
180///
181/// fn write_u16(bytes: &mut [u8; 2], num: u16) {
182///      bytes[0] = num as u8;
183///      bytes[1] = (num >> 8) as u8;
184/// }
185/// fn write_u32(bytes: &mut [u8; 4], num: u32) {
186///      bytes[0] = num as u8;
187///      bytes[1] = (num >> 8) as u8; // this is buggy to save space...
188/// }
189/// // ...
190/// # fn main() {
191/// let mut data = [0,1,2,3,4,0,6,7];
192/// let (a,b,c) = mut_array_refs![&mut data,2,2,4];
193/// // let's write out some nice prime numbers!
194/// write_u16(a, 37);
195/// write_u16(b, 73);
196/// write_u32(c, 137); // approximate inverse of the fine structure constant!
197/// # }
198/// ```
199#[macro_export]
200macro_rules! mut_array_refs {
201    ( $arr:expr, $( $pre:expr ),* ; .. ;  $( $post:expr ),* ) => {{
202        {
203            use std::slice;
204            #[inline]
205            #[allow(unused_assignments)]
206            unsafe fn as_arrays<T>(a: &mut [T]) -> ( $( &mut [T; $pre], )* &mut [T],  $( &mut [T; $post], )*) {
207                let min_len = $( $pre + )* $( $post + )* 0;
208                let var_len = a.len() - min_len;
209                assert!(a.len() >= min_len);
210                let mut p = a.as_mut_ptr();
211                ( $( {
212                    let aref = &mut *(p as *mut [T; $pre]);
213                    p = p.offset($pre as isize);
214                    aref
215                } ),* , {
216                    let sl = slice::from_raw_parts_mut(p as *mut T, var_len);
217                    p = p.offset(var_len as isize);
218                    sl
219                }, $( {
220                    let aref = &mut *(p as *mut [T; $post]);
221                    p = p.offset($post as isize);
222                    aref
223                } ),*)
224            }
225            let input = $arr;
226            #[allow(unused_unsafe)]
227            unsafe {
228                as_arrays(input)
229            }
230        }
231    }};
232    ( $arr:expr, $( $len:expr ),* ) => {{
233        {
234            #[inline]
235            #[allow(unused_assignments)]
236            unsafe fn as_arrays<T>(a: &mut [T; $( $len + )* 0 ]) -> ( $( &mut [T; $len], )* ) {
237                let mut p = a.as_mut_ptr();
238                ( $( {
239                    let aref = &mut *(p as *mut [T; $len]);
240                    p = p.offset($len as isize);
241                    aref
242                } ),* )
243            }
244            let input = $arr;
245            #[allow(unused_unsafe)]
246            unsafe {
247                as_arrays(input)
248            }
249        }
250    }};
251}
252
253/// You can use `array_mut_ref` to generate a mutable array reference
254/// to a subset of a sliceable bit of data (which could be an array,
255/// or a slice, or a Vec).
256///
257/// **Panics** if the slice is out of bounds.
258///
259/// ```
260/// #[macro_use]
261/// extern crate arrayref;
262///
263/// fn write_u16(bytes: &mut [u8; 2], num: u16) {
264///      bytes[0] = num as u8;
265///      bytes[1] = (num >> 8) as u8;
266/// }
267/// // ...
268/// # fn main() {
269/// let mut data = [0,1,2,3,4,0,6,7,8,9];
270/// write_u16(array_mut_ref![data,0,2], 1);
271/// write_u16(array_mut_ref![data,2,2], 5);
272/// assert_eq!(*array_ref![data,0,4], [1,0,5,0]);
273/// *array_mut_ref![data,4,5] = [4,3,2,1,0];
274/// assert_eq!(data, [1,0,5,0,4,3,2,1,0,9]);
275/// # }
276/// ```
277#[macro_export]
278macro_rules! array_mut_ref {
279    ($arr:expr, $offset:expr, $len:expr) => {{
280        {
281            #[inline]
282            unsafe fn as_array<T>(slice: &mut [T]) -> &mut [T; $len] {
283                &mut *(slice.as_mut_ptr() as *mut [_; $len])
284            }
285            let offset = $offset;
286            let slice = &mut $arr[offset..offset + $len];
287            #[allow(unused_unsafe)]
288            unsafe {
289                as_array(slice)
290            }
291        }
292    }}
293}
294
295
296#[cfg(test)]
297mod test {
298
299extern crate quickcheck;
300
301use std::vec::Vec;
302
303// use super::*;
304
305#[test]
306#[should_panic]
307fn checks_bounds() {
308    let foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
309    let bar = array_ref!(foo, 1, 11);
310    println!("I am checking that I can dereference bar[0] = {}", bar[0]);
311}
312
313#[test]
314fn simple_case_works() {
315    fn check(expected: [u8; 3], actual: &[u8; 3]) {
316        for (e, a) in (&expected).iter().zip(actual.iter()) {
317            assert_eq!(e, a)
318        }
319    }
320    let mut foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
321    {
322        let bar = array_ref!(foo, 2, 3);
323        check([2, 3, 4], bar);
324    }
325    check([0, 1, 2], array_ref!(foo, 0, 3));
326    fn zero2(x: &mut [u8; 2]) {
327        x[0] = 0;
328        x[1] = 0;
329    }
330    zero2(array_mut_ref!(foo, 8, 2));
331    check([0, 0, 10], array_ref!(foo, 8, 3));
332}
333
334
335#[test]
336fn check_array_ref_5() {
337    fn f(data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
338        if data.len() < offset + 5 {
339            return quickcheck::TestResult::discard();
340        }
341        let out = array_ref!(data, offset, 5);
342        quickcheck::TestResult::from_bool(out.len() == 5)
343    }
344    quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
345}
346
347#[test]
348fn check_array_ref_out_of_bounds_5() {
349    fn f(data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
350        if data.len() >= offset + 5 {
351            return quickcheck::TestResult::discard();
352        }
353        quickcheck::TestResult::must_fail(move || {
354            array_ref!(data, offset, 5);
355        })
356    }
357    quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
358}
359
360#[test]
361fn check_array_mut_ref_7() {
362    fn f(mut data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
363        if data.len() < offset + 7 {
364            return quickcheck::TestResult::discard();
365        }
366        let out = array_mut_ref!(data, offset, 7);
367        out[6] = 3;
368        quickcheck::TestResult::from_bool(out.len() == 7)
369    }
370    quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
371}
372
373
374#[test]
375fn check_array_mut_ref_out_of_bounds_32() {
376    fn f(mut data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
377        if data.len() >= offset + 32 {
378            return quickcheck::TestResult::discard();
379        }
380        quickcheck::TestResult::must_fail(move || {
381            array_mut_ref!(data, offset, 32);
382        })
383    }
384    quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
385}
386
387
388#[test]
389fn test_5_array_refs() {
390    let mut data: [usize; 128] = [0; 128];
391    for i in 0..128 {
392        data[i] = i;
393    }
394    let data = data;
395    let (a,b,c,d,e) = array_refs!(&data, 1, 14, 3, 100, 10);
396    assert_eq!(a.len(), 1 as usize);
397    assert_eq!(b.len(), 14 as usize);
398    assert_eq!(c.len(), 3 as usize);
399    assert_eq!(d.len(), 100 as usize);
400    assert_eq!(e.len(), 10 as usize);
401    assert_eq!(a, array_ref![data, 0, 1]);
402    assert_eq!(b, array_ref![data, 1, 14]);
403    assert_eq!(c, array_ref![data, 15, 3]);
404    assert_eq!(e, array_ref![data, 118, 10]);
405}
406
407#[test]
408fn test_5_array_refs_dotdot() {
409    let mut data: [usize; 128] = [0; 128];
410    for i in 0..128 {
411        data[i] = i;
412    }
413    let data = data;
414    let (a,b,c,d,e) = array_refs!(&data, 1, 14, 3; ..; 10);
415    assert_eq!(a.len(), 1 as usize);
416    assert_eq!(b.len(), 14 as usize);
417    assert_eq!(c.len(), 3 as usize);
418    assert_eq!(d.len(), 100 as usize);
419    assert_eq!(e.len(), 10 as usize);
420    assert_eq!(a, array_ref![data, 0, 1]);
421    assert_eq!(b, array_ref![data, 1, 14]);
422    assert_eq!(c, array_ref![data, 15, 3]);
423    assert_eq!(e, array_ref![data, 118, 10]);
424}
425
426
427#[test]
428fn test_5_mut_xarray_refs() {
429    let mut data: [usize; 128] = [0; 128];
430    {
431        // temporarily borrow the data to modify it.
432        let (a,b,c,d,e) = mut_array_refs!(&mut data, 1, 14, 3, 100, 10);
433        assert_eq!(a.len(), 1 as usize);
434        assert_eq!(b.len(), 14 as usize);
435        assert_eq!(c.len(), 3 as usize);
436        assert_eq!(d.len(), 100 as usize);
437        assert_eq!(e.len(), 10 as usize);
438        *a = [1; 1];
439        *b = [14; 14];
440        *c = [3; 3];
441        *d = [100; 100];
442        *e = [10; 10];
443    }
444    assert_eq!(&[1;1], array_ref![data, 0, 1]);
445    assert_eq!(&[14;14], array_ref![data, 1, 14]);
446    assert_eq!(&[3;3], array_ref![data, 15, 3]);
447    assert_eq!(&[10;10], array_ref![data, 118, 10]);
448}
449
450#[test]
451fn test_5_mut_xarray_refs_with_dotdot() {
452    let mut data: [usize; 128] = [0; 128];
453    {
454        // temporarily borrow the data to modify it.
455        let (a,b,c,d,e) = mut_array_refs!(&mut data, 1, 14, 3; ..; 10);
456        assert_eq!(a.len(), 1 as usize);
457        assert_eq!(b.len(), 14 as usize);
458        assert_eq!(c.len(), 3 as usize);
459        assert_eq!(d.len(), 100 as usize);
460        assert_eq!(e.len(), 10 as usize);
461        *a = [1; 1];
462        *b = [14; 14];
463        *c = [3; 3];
464        *e = [10; 10];
465    }
466    assert_eq!(&[1;1], array_ref![data, 0, 1]);
467    assert_eq!(&[14;14], array_ref![data, 1, 14]);
468    assert_eq!(&[3;3], array_ref![data, 15, 3]);
469    assert_eq!(&[10;10], array_ref![data, 118, 10]);
470}
471
472} // mod test