[Ethereum] Standard work-around for using a Solidity constant array (which is not supported) in pure function

arraysconstantpuresolidityview

I have an array in my contract like this and a pure method which uses it like this (simplified exmaple because my real exmaple is many more lines):

uint[16] constant x = [10, 2, 6, 42, 19, 5, 4, 36, 6, 6, 5, 5, 5, 46, 4, 4];

function foo(uint i, uint j) external pure returns (uint) {
    return x[i] + x[j] * 12;
}

But solidity doesn't seem to support this, so I can only figure out to change it to non constant, but then I'm foreced to switch to view even though my function is pure.

uint[16] x = [10, 2, 6, 42, 19, 5, 4, 36, 6, 6, 5, 5, 5, 46, 4, 4];

function foo(uint i, uint j) external view returns (uint) {
    return x[i] + x[j] * 12;
}

it seems I can only keep the funciton pure if I changd it in to a bunch of seperate uint insted of uint[16] but that's messy.

Is there a workaorund which keeps my function pure? Is just making it view the standard work-around to this?

Best Answer

It seems that is an pending feature https://github.com/ethereum/solidity/issues/1772

However, if the desired range is from 0-255, there is a trick for you.

bytes public constant TEST_MAP = hex"000804";
   
function test(uint8 key) external pure returns (byte) {
   return TEST_MAP[uint256(key)];
}
Related Topic