@@ -11,7 +11,7 @@ use crate::error::Error;
11
11
use crate :: fmt;
12
12
use crate :: hash:: { self , Hash } ;
13
13
use crate :: intrinsics:: transmute_unchecked;
14
- use crate :: iter:: UncheckedIterator ;
14
+ use crate :: iter:: { repeat_n , UncheckedIterator } ;
15
15
use crate :: mem:: { self , MaybeUninit } ;
16
16
use crate :: ops:: {
17
17
ChangeOutputType , ControlFlow , FromResidual , Index , IndexMut , NeverShortCircuit , Residual , Try ,
@@ -30,12 +30,16 @@ pub use iter::IntoIter;
30
30
31
31
/// Creates an array of type `[T; N]` by repeatedly cloning a value.
32
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.
33
+ /// This is the same as `[val; N]`, but it also works for types that do not
34
+ /// implement [`Copy`].
35
+ ///
36
+ /// The provided value will be used as an element of the resulting array and
37
+ /// will be cloned N - 1 times to fill up the rest. If N is zero, the value
38
+ /// will be dropped.
35
39
///
36
40
/// # Example
37
41
///
38
- /// Creating muliple copies of a string :
42
+ /// Creating muliple copies of a [`String`] :
39
43
/// ```rust
40
44
/// #![feature(array_repeat)]
41
45
///
@@ -51,15 +55,7 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
51
55
match N {
52
56
// SAFETY: we know N to be 0 at this point.
53
57
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
- }
58
+ _ => from_trusted_iterator ( repeat_n ( val, N ) ) ,
63
59
}
64
60
}
65
61
0 commit comments