0

I would like to create an array with size bounded by a const expression that uses a generic parameter. In rust pseudo code:


struct ArrayWrapper<T, const U: Unsigned> 
{
    inner: [T; 2 * (U + 1)]
}

It seems U would also have to be bound with something like this: U <= Unsigned::Max / 2 - 1

I've managed to express this in stable rust (1.64.0) using typenum and generic_array.

use core::ops::Mul;
use core::ops::Add;
use typenum::*; // 1.15.0
use generic_array::*; // 0.14.6

struct ArrayWrapper<T> 
    where 
        T: Unsigned,
        T: Add<U1>,
        Sum<T,U1>: Mul<U2>,
        Prod<Sum<T, U1>, U2>: ArrayLength<u8>,
    
{
    inner: GenericArray<u8, Prod<Sum<T, U1>, U2>>,
}

Is there a way to simplify these bounds? Is there a way to express this in stable rust?

PrancingCrabulon
  • 403
  • 4
  • 15
  • 2
    For starters, you don't need the `T: Unsigned` since any value resulting in a negative length wont implement `ArrayLength`. Next, you could add a marker trait for it to make it easier on yourself. That way you could require the marker trait instead when using the type and not write out all of those conditions. – Locke Oct 23 '22 at 20:52

0 Answers0