Skip to content

Const generics: array support #939

Closed

Description

@dhardy

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:

  1. Use std::mem::MaybeUninit. This should work with code like this; currently it doesn't (I believe because of const_generics bugs):

    #[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) }
        }
    }
  2. Use an extra bound like T: Default to allow construction of a temporary, then generate elt-by-elt.

  3. If somehow Rust were to support FromIterator for array types, we could use iter::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

  1. burdges commented on Feb 29, 2020

    @burdges
    Contributor

    Isn't FromIterator rather easy so why not that route? You can even partially consume iterators with node like my_iter.by_ref().collect::<T; N]>().

    impl<T, const N:  usize> FromIterator<T> for [T; N] {
        #[inline]
        fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> [T; N] {
            use core::mem::{MaybeUninit, transmute};
            let mut r: [MaybeUninit<T>; N] = unsafe { MaybeUninit::uninit().assume_init() };
            let mut iter = iter.into_iter();
            for elem in (&mut r[..]).iter_mut() {
                *elem = MaybeUninit::new(i.next().expect("Iterator terminated early"));
            }
            unsafe { transmute::<[MaybeUninit<T>; N], [T; N]>(r) }
        }
    }
    

    Afaik, there is no reason for a .take(N) here since the iterator need not be consumed. There is no reason for TrustedLen etc since we want exactly N.

    There is a slim risk someone uses the less efficent iter::repeat(foo).collect::<[T; 1000]>() in an IntoIterator context, where they should use iter::repeat(foo).take(1000), but whatever.

  2. dhardy commented on Feb 29, 2020

    @dhardy
    MemberAuthor

    @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.

  3. burdges commented on Feb 29, 2020

    @burdges
    Contributor

    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 :)

  4. dhardy commented on Mar 1, 2020

    @dhardy
    MemberAuthor

    True, the unsafe-ty could be bumped up to libcore.

  5. added
    P-postpone
    on Mar 9, 2020
  6. vks commented on Aug 24, 2021

    @vks
    Contributor

    I believe this was fixed with the introduction of the min_const_gen feature.

  7. removed
    P-postpone
    on Aug 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions