Skip to content

Commit 0f3962f

Browse files
committed
core: simplify implementation of array::repeat, address other nits
1 parent a415a4c commit 0f3962f

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

library/core/src/array/mod.rs

+9-13
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::error::Error;
1111
use crate::fmt;
1212
use crate::hash::{self, Hash};
1313
use crate::intrinsics::transmute_unchecked;
14-
use crate::iter::UncheckedIterator;
14+
use crate::iter::{repeat_n, UncheckedIterator};
1515
use crate::mem::{self, MaybeUninit};
1616
use crate::ops::{
1717
ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
@@ -30,12 +30,16 @@ pub use iter::IntoIter;
3030

3131
/// Creates an array of type `[T; N]` by repeatedly cloning a value.
3232
///
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.
3539
///
3640
/// # Example
3741
///
38-
/// Creating muliple copies of a string:
42+
/// Creating muliple copies of a [`String`]:
3943
/// ```rust
4044
/// #![feature(array_repeat)]
4145
///
@@ -51,15 +55,7 @@ pub fn repeat<T: Clone, const N: usize>(val: T) -> [T; N] {
5155
match N {
5256
// SAFETY: we know N to be 0 at this point.
5357
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)),
6359
}
6460
}
6561

0 commit comments

Comments
 (0)