Skip to content

Commit 5ddeaca

Browse files
committed
core: simplify implementation of array::repeat, address other nits
1 parent 62f7a4e commit 5ddeaca

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

core/src/array/mod.rs

+9-18
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,7 @@ use crate::convert::Infallible;
1010
use crate::error::Error;
1111
use crate::fmt;
1212
use crate::hash::{self, Hash};
13-
use crate::intrinsics::transmute_unchecked;
14-
use crate::iter::UncheckedIterator;
13+
use crate::iter::{repeat_n, UncheckedIterator};
1514
use crate::mem::{self, MaybeUninit};
1615
use crate::ops::{
1716
ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
@@ -30,12 +29,16 @@ pub use iter::IntoIter;
3029

3130
/// Creates an array of type `[T; N]` by repeatedly cloning a value.
3231
///
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.
32+
/// This is the same as `[val; N]`, but it also works for types that do not
33+
/// implement [`Copy`].
34+
///
35+
/// The provided value will be used as an element of the resulting array and
36+
/// will be cloned N - 1 times to fill up the rest. If N is zero, the value
37+
/// will be dropped.
3538
///
3639
/// # Example
3740
///
38-
/// Creating muliple copies of a string:
41+
/// Creating muliple copies of a `String`:
3942
/// ```rust
4043
/// #![feature(array_repeat)]
4144
///
@@ -48,19 +51,7 @@ pub use iter::IntoIter;
4851
#[inline]
4952
#[unstable(feature = "array_repeat", issue = "none")]
5053
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-
}
54+
from_trusted_iterator(repeat_n(val, N))
6455
}
6556

6657
/// Creates an array of type [T; N], where each element `T` is the returned value from `cb`

0 commit comments

Comments
 (0)