@@ -10,6 +10,7 @@ use crate::convert::Infallible;
10
10
use crate :: error:: Error ;
11
11
use crate :: fmt;
12
12
use crate :: hash:: { self , Hash } ;
13
+ use crate :: intrinsics:: transmute_unchecked;
13
14
use crate :: iter:: UncheckedIterator ;
14
15
use crate :: mem:: { self , MaybeUninit } ;
15
16
use crate :: ops:: {
@@ -27,6 +28,41 @@ pub(crate) use drain::drain_array_with;
27
28
#[ stable( feature = "array_value_iter" , since = "1.51.0" ) ]
28
29
pub use iter:: IntoIter ;
29
30
31
+ /// Creates an array of type `[T; N]` by repeatedly cloning a value.
32
+ ///
33
+ /// The value will be used as the last element of the resulting array, so it
34
+ /// will be cloned N - 1 times. If N is zero, the value will be dropped.
35
+ ///
36
+ /// # Example
37
+ ///
38
+ /// Creating muliple copies of a string:
39
+ /// ```rust
40
+ /// #![feature(array_repeat)]
41
+ ///
42
+ /// use std::array;
43
+ ///
44
+ /// let string = "Hello there!".to_string();
45
+ /// let strings = array::repeat(string);
46
+ /// assert_eq!(strings, ["Hello there!", "Hello there!"]);
47
+ /// ```
48
+ #[ inline]
49
+ #[ unstable( feature = "array_repeat" , issue = "none" ) ]
50
+ pub fn repeat < T : Clone , const N : usize > ( val : T ) -> [ T ; N ] {
51
+ match N {
52
+ // SAFETY: we know N to be 0 at this point.
53
+ 0 => unsafe { transmute_unchecked :: < [ T ; 0 ] , [ T ; N ] > ( [ ] ) } ,
54
+ // SAFETY: we know N to be 1 at this point.
55
+ 1 => unsafe { transmute_unchecked :: < [ T ; 1 ] , [ T ; N ] > ( [ val] ) } ,
56
+ _ => {
57
+ let mut array = MaybeUninit :: uninit_array :: < N > ( ) ;
58
+ try_from_fn_erased ( & mut array[ ..N - 1 ] , NeverShortCircuit :: wrap_mut_1 ( |_| val. clone ( ) ) ) ;
59
+ array[ N - 1 ] . write ( val) ;
60
+ // SAFETY: all elements were initialized.
61
+ unsafe { MaybeUninit :: array_assume_init ( array) }
62
+ }
63
+ }
64
+ }
65
+
30
66
/// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
31
67
/// using that element's index.
32
68
///
0 commit comments