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;
19
19
#[ unstable( feature = "array_value_iter" , issue = "65798" ) ]
20
20
pub use iter:: IntoIter ;
21
21
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
+
22
36
/// Utility trait implemented only on arrays of fixed size
23
37
///
24
38
/// 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 } ;
2
2
use core:: convert:: TryFrom ;
3
3
4
4
#[ test]
@@ -19,6 +19,21 @@ fn fixed_size_array() {
19
19
assert_eq ! ( FixedSizeArray :: as_mut_slice( & mut empty_zero_sized) . len( ) , 0 ) ;
20
20
}
21
21
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
+
22
37
#[ test]
23
38
fn array_try_from ( ) {
24
39
macro_rules! test {
Original file line number Diff line number Diff line change 1
1
#![ feature( alloc_layout_extra) ]
2
2
#![ feature( array_chunks) ]
3
+ #![ feature( array_from_ref) ]
3
4
#![ feature( array_methods) ]
4
5
#![ feature( array_map) ]
5
6
#![ feature( array_windows) ]
You can’t perform that action at this time.
0 commit comments