Repository navigation
Description
We already support generating [T; N] for Standard where T supports Standard and N ≤ 32 via a macro. It would be nice to replace this with a more generic implementation using const_generics.
There is a catch: our macro generates arrays via this syntax: [_rng.gen::<$t>(), $(_rng.gen::<$ts>()),*], but there is no equivalent const-generics literal. This leaves only a couple of options:
-
Use
std::mem::MaybeUninit. This should work with code like this; currently it doesn't (I believe because ofconst_genericsbugs):#[cfg(feature = "const_generics")] impl<T, const N: usize> Distribution<[T; N]> for Standard where Standard: Distribution<T> { #[inline] fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> [T; N] { // We cannot have a safe implementation without some extra bound // allowing construction, e.g. `T: Default`, thus we use MaybeUninit. use core::mem::{MaybeUninit, transmute}; // Use MaybeUninit as in element-by-element array example: // https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#initializing-an-array-element-by-element let mut r: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() }; for elem in &mut r[..] { *elem = MaybeUninit::new(rng.gen::<T>()); } unsafe { transmute::<[MaybeUninit<T>; N], [T; N]>(r) } } }
-
Use an extra bound like
T: Defaultto allow construction of a temporary, then generate elt-by-elt. -
If somehow Rust were to support
FromIteratorfor array types, we could useiter::repeat(...).take(N).collect()— but I don't expect to see this happen any time soon (if ever).
Probably eventually we'll go for option (1), though it's a shame we'll need the unsafe code. For now, we do nothing.
Activity
Use const_generics to impl Fill for array types (feature flag)
burdges commentedon Feb 29, 2020
Isn't
FromIteratorrather easy so why not that route? You can even partially consume iterators with node likemy_iter.by_ref().collect::<T; N]>().Afaik, there is no reason for a
.take(N)here since the iterator need not be consumed. There is no reason forTrustedLenetc since we want exactlyN.There is a slim risk someone uses the less efficent
iter::repeat(foo).collect::<[T; 1000]>()in anIntoIteratorcontext, where they should useiter::repeat(foo).take(1000), but whatever.dhardy commentedon Feb 29, 2020
@burdges I think there's a misunderstanding; iterators are not supposed to appear in this API anywhere. It's purely about implementing
Distribution<[T; N]> for Standard.burdges commentedon Feb 29, 2020
I missread the repo ;) but I do think rust libcore would accept a pull for the above code once const generics land. Anyways 1 works fine :)
dhardy commentedon Mar 1, 2020
True, the
unsafe-ty could be bumped up to libcore.vks commentedon Aug 24, 2021
I believe this was fixed with the introduction of the
min_const_genfeature.