1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#![deny(warnings)]
#[cfg(test)]
extern crate quickcheck;
#[macro_export]
macro_rules! array_ref {
($arr:expr, $offset:expr, $t:ty, $len:expr) => {{
{
let sl = &$arr[$offset .. $offset + $len];
let arrref: &[$t; $len] = unsafe {
::std::mem::transmute(sl.as_ptr())
};
arrref
}
}}
}
#[macro_export]
macro_rules! array_mut_ref {
($arr:expr, $offset:expr, $t:ty, $len:expr) => {{
{
let sl = &mut $arr[$offset .. $offset + $len];
let arrref: &mut [$t; $len] = unsafe {
::std::mem::transmute(sl.as_ptr())
};
arrref
}
}}
}
#[test]
#[should_panic]
fn checks_bounds() {
let foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let bar = array_ref!(foo, 1, u8, 11);
println!("{}", bar[0]);
}
#[test]
fn simple_case_works() {
let mut foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let bar = array_ref!(foo, 2, u8, 3);
println!("{}", bar.len());
fn pr3(x: &[u8; 3]) {
println!("[{} {} {}]", x[0], x[1], x[2]);
}
pr3(bar);
pr3(array_ref!(foo, 0, u8, 3));
fn zero2(x: &mut [u8; 2]) {
x[0] = 0;
x[1] = 0;
}
zero2(array_mut_ref!(foo, 8, u8, 2));
pr3(array_ref!(foo, 8, u8, 3));
}
#[test]
fn check_array_ref_5() {
fn f(data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
if data.len() < offset + 5 {
return quickcheck::TestResult::discard();
}
let out = array_ref!(data, offset, u8, 5);
quickcheck::TestResult::from_bool(out.len() == 5)
}
quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
}
#[test]
fn check_array_ref_out_of_bounds_5() {
fn f(data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
if data.len() >= offset + 5 {
return quickcheck::TestResult::discard();
}
quickcheck::TestResult::must_fail(move || {
array_ref!(data, offset, u8, 5);
})
}
quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
}
#[test]
fn check_array_mut_ref_7() {
fn f(mut data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
if data.len() < offset + 7 {
return quickcheck::TestResult::discard();
}
let out = array_mut_ref!(data, offset, u8, 7);
out[6] = 3;
quickcheck::TestResult::from_bool(out.len() == 7)
}
quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
}
#[test]
fn check_array_mut_ref_out_of_bounds_32() {
fn f(mut data: Vec<u8>, offset: usize) -> quickcheck::TestResult {
if data.len() >= offset + 32 {
return quickcheck::TestResult::discard();
}
quickcheck::TestResult::must_fail(move || {
array_mut_ref!(data, offset, u8, 32);
})
}
quickcheck::quickcheck(f as fn(Vec<u8>, usize) -> quickcheck::TestResult);
}