arrayref icon indicating copy to clipboard operation
arrayref copied to clipboard

Implementation without `unsafe` is possible

Open Shnatsel opened this issue 6 years ago • 6 comments

It is now possible to implement this macro safely thanks to TryInto implementation from slices to array references:

let my_arr_reference: &[i32; 5] = my_slice.try_into().unwrap();

Bounds checks will also be elided if the size of the slice is known in advance.

Example of this conversion in action: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=9d6e1d61835060f832ce1724becb1214

The only limitation is that this only works for sizes of 32 and lower until const generics are stabilized.

Shnatsel avatar Nov 02 '19 14:11 Shnatsel

Nice. I don't think I'll make a change until it works for large as well as small arrays.

droundy avatar Nov 02 '19 16:11 droundy

Since rust-lang/rust#74060 now stabilizes trait implementations for all array lengths, this will be possible once 1.47 is released (which should happen 2020-10-08 if I didn't miscount).

aticu avatar Jul 27 '20 11:07 aticu

Okay, I'll accept a pull request changing the implementation to avoid unsafe.

droundy avatar Jul 27 '20 14:07 droundy

I suppose slices' size would be known in advance if you do the more subtle tricks?

burdges avatar Jul 27 '20 20:07 burdges

Looks like Rust 1.47 has been stable for a few weeks now! :tada: https://blog.rust-lang.org/2020/10/08/Rust-1.47.html

coderbot16 avatar Nov 19 '20 21:11 coderbot16

I raised this PR which will avoid unsafe in the array_ref! macro: https://github.com/droundy/arrayref/pull/24

nabilwadih avatar Jan 17 '23 23:01 nabilwadih