Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 387fd1f

Browse files
committedJun 19, 2024
core: implement array::repeat
1 parent 2a5e5b8 commit 387fd1f

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎core/src/array/mod.rs

+36
Original file line numberDiff line numberDiff line change
@@ -10,6 +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;
1314
use crate::iter::UncheckedIterator;
1415
use crate::mem::{self, MaybeUninit};
1516
use crate::ops::{
@@ -27,6 +28,41 @@ pub(crate) use drain::drain_array_with;
2728
#[stable(feature = "array_value_iter", since = "1.51.0")]
2829
pub 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

Comments
 (0)
Failed to load comments.