Search code examples
arraysrustconstants

How to construct large const arrays in Rust without manually writing values to construct it


TLDR: What is the best way to construct large const arrays without writing all the values manually one by one.

Subjective question below:

I want my program to have an const array that will hold range of ASCII bytes ([u8; 94]), but I don't want to use Range<u8>.

And the reason I am not using Vec is because I already know the exact range of values I can do it all statically, and I just can't seem to find the way to construct such an array without manually writing each value.

What I did before posting this question was use const Range because contains is O(1).

Anyways regarding original problem, I want this:

const VALID_BLOCK_BYTES: [u8; 94] = [32..126; 94];

How do I get constant variable array with values from 32 up to 126 without manually writing it myself?


Solution

  • I think the best way to achieve this right now is with a manual loop:

    const VALID_BLOCK_BYTES: [u8; 94] = {
        let mut output = [0; 94];
        
        let mut i = 0;
        while i < 94 {
            output[i as usize] = i + 32;
            i += 1;
        }
    
        output
    };
    

    Can't use iterators because traits in const contexts aren't stable.

    You can, of course, factor that out into a const fn if you need to do that a lot.