This repository was archived by the owner on May 28, 2025. It is now read-only.
File tree Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Expand file tree Collapse file tree 3 files changed +31
-1
lines changed Original file line number Diff line number Diff line change @@ -19,6 +19,20 @@ mod iter;
1919#[ unstable( feature = "array_value_iter" , issue = "65798" ) ]
2020pub use iter:: IntoIter ;
2121
22+ /// Converts a reference to `T` into a reference to an array of length 1 (without copying).
23+ #[ unstable( feature = "array_from_ref" , issue = "none" ) ]
24+ pub fn from_ref < T > ( s : & T ) -> & [ T ; 1 ] {
25+ // SAFETY: Converting `&T` to `&[T; 1]` is sound.
26+ unsafe { & * ( s as * const T ) . cast :: < [ T ; 1 ] > ( ) }
27+ }
28+
29+ /// Converts a mutable reference to `T` into a mutable reference to an array of length 1 (without copying).
30+ #[ unstable( feature = "array_from_ref" , issue = "none" ) ]
31+ pub fn from_mut < T > ( s : & mut T ) -> & mut [ T ; 1 ] {
32+ // SAFETY: Converting `&mut T` to `&mut [T; 1]` is sound.
33+ unsafe { & mut * ( s as * mut T ) . cast :: < [ T ; 1 ] > ( ) }
34+ }
35+
2236/// Utility trait implemented only on arrays of fixed size
2337///
2438/// This trait can be used to implement other traits on fixed-size arrays
Original file line number Diff line number Diff line change 1- use core:: array:: { FixedSizeArray , IntoIter } ;
1+ use core:: array:: { self , FixedSizeArray , IntoIter } ;
22use core:: convert:: TryFrom ;
33
44#[ test]
@@ -19,6 +19,21 @@ fn fixed_size_array() {
1919 assert_eq ! ( FixedSizeArray :: as_mut_slice( & mut empty_zero_sized) . len( ) , 0 ) ;
2020}
2121
22+ #[ test]
23+ fn array_from_ref ( ) {
24+ let value: String = "Hello World!" . into ( ) ;
25+ let arr: & [ String ; 1 ] = array:: from_ref ( & value) ;
26+ assert_eq ! ( & [ value. clone( ) ] , arr) ;
27+ }
28+
29+ #[ test]
30+ fn array_from_mut ( ) {
31+ let mut value: String = "Hello World" . into ( ) ;
32+ let arr: & mut [ String ; 1 ] = array:: from_mut ( & mut value) ;
33+ arr[ 0 ] . push_str ( "!" ) ;
34+ assert_eq ! ( & value, "Hello World!" ) ;
35+ }
36+
2237#[ test]
2338fn array_try_from ( ) {
2439 macro_rules! test {
Original file line number Diff line number Diff line change 11#![ feature( alloc_layout_extra) ]
22#![ feature( array_chunks) ]
3+ #![ feature( array_from_ref) ]
34#![ feature( array_methods) ]
45#![ feature( array_map) ]
56#![ feature( array_windows) ]
You can’t perform that action at this time.
0 commit comments