Skip to content

Commit f1580f3

Browse files
committed
Implement Random for array
Implement `Random` for `[T; N]`, where `Random` is implemented for `T`.
1 parent e060723 commit f1580f3

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

library/core/src/array/mod.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use crate::ops::{
1717
ChangeOutputType, ControlFlow, FromResidual, Index, IndexMut, NeverShortCircuit, Residual, Try,
1818
};
1919
use crate::ptr::{null, null_mut};
20+
use crate::random::{Random, RandomSource};
2021
use crate::slice::{Iter, IterMut};
2122

2223
mod ascii;
@@ -426,6 +427,18 @@ impl<T: Clone, const N: usize> Clone for [T; N] {
426427
}
427428
}
428429

430+
#[unstable(feature = "random", issue = "130703")]
431+
impl<T: Random, const N: usize> Random for [T; N] {
432+
fn random(source: &mut (impl RandomSource + ?Sized)) -> Self {
433+
let mut buf = [const { MaybeUninit::uninit() }; N];
434+
for elem in &mut buf {
435+
elem.write(T::random(source));
436+
}
437+
// SAFETY: all elements of the array were initialized.
438+
unsafe { mem::transmute_copy(&buf) }
439+
}
440+
}
441+
429442
trait SpecArrayClone: Clone {
430443
fn clone<const N: usize>(array: &[Self; N]) -> [Self; N];
431444
}

0 commit comments

Comments
 (0)