Skip to content

Commit a2dd74a

Browse files
committed
changes as suggested by bluss (but not reordering arguments)
1 parent a09b541 commit a2dd74a

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/lib.rs

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,17 @@ extern crate quickcheck;
2323
/// or a Vec). The arguments are a bit clumsy
2424
#[macro_export]
2525
macro_rules! array_ref {
26-
($arr:expr, $offset:expr, $t:ty, $len:expr) => {{
26+
($arr:expr, $offset:expr, $elemty:ty, $len:expr) => {{
2727
{
28-
let sl = &$arr[$offset .. $offset + $len];
29-
let arrref: &[$t; $len] = unsafe {
30-
::std::mem::transmute(sl.as_ptr())
31-
};
32-
arrref
28+
#[inline]
29+
unsafe fn as_array(slice: &[$elemty]) -> &[$elemty; $len] {
30+
&*(slice.as_ptr() as *const [_; $len])
31+
}
32+
let a: usize = $offset;
33+
let l: usize = $len;
34+
unsafe {
35+
as_array(&$arr[a..a.saturating_add(l)])
36+
}
3337
}
3438
}}
3539
}
@@ -39,13 +43,17 @@ macro_rules! array_ref {
3943
/// or a slice, or a Vec).
4044
#[macro_export]
4145
macro_rules! array_mut_ref {
42-
($arr:expr, $offset:expr, $t:ty, $len:expr) => {{
46+
($arr:expr, $offset:expr, $elemty:ty, $len:expr) => {{
4347
{
44-
let sl = &mut $arr[$offset .. $offset + $len];
45-
let arrref: &mut [$t; $len] = unsafe {
46-
::std::mem::transmute(sl.as_ptr())
47-
};
48-
arrref
48+
#[inline]
49+
unsafe fn as_array(slice: &mut[$elemty]) -> &mut[$elemty; $len] {
50+
&mut *(slice.as_mut_ptr() as *mut [_; $len])
51+
}
52+
let a: usize = $offset;
53+
let l: usize = $len;
54+
unsafe {
55+
as_array(&mut $arr[a..a.saturating_add(l)])
56+
}
4957
}
5058
}}
5159
}
@@ -61,12 +69,14 @@ fn checks_bounds() {
6169
#[test]
6270
fn simple_case_works() {
6371
let mut foo: [u8; 11] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
64-
let bar = array_ref!(foo, 2, u8, 3);
65-
println!("{}", bar.len());
6672
fn pr3(x: &[u8; 3]) {
6773
println!("[{} {} {}]", x[0], x[1], x[2]);
6874
}
69-
pr3(bar);
75+
{
76+
let bar = array_ref!(foo, 2, u8, 3);
77+
println!("{}", bar.len());
78+
pr3(bar);
79+
}
7080
pr3(array_ref!(foo, 0, u8, 3));
7181
fn zero2(x: &mut [u8; 2]) {
7282
x[0] = 0;

0 commit comments

Comments
 (0)