@@ -10,6 +10,7 @@ use crate::convert::Infallible;
1010use crate :: error:: Error ;
1111use crate :: fmt;
1212use crate :: hash:: { self , Hash } ;
13+ use crate :: intrinsics:: transmute_unchecked;
1314use crate :: iter:: UncheckedIterator ;
1415use crate :: mem:: { self , MaybeUninit } ;
1516use crate :: ops:: {
@@ -27,6 +28,41 @@ pub(crate) use drain::drain_array_with;
2728#[ stable( feature = "array_value_iter" , since = "1.51.0" ) ]
2829pub use iter:: IntoIter ;
2930
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+
3066/// Creates an array of type [T; N], where each element `T` is the returned value from `cb`
3167/// using that element's index.
3268///
0 commit comments