0

I would like to know if this is possible to check in a simple way if a bytes32 value exists in an array of bytes32 value please?

contract Test {
    struct TestStruct {
        string name;
        bytes32 value;
    }

    struct ConfigStruct {
        bytes32[] valuesPossible;
    }

    TestStruct[] public structs;
    ConfigStruct[] configs;


    function constructor(bytes32[] _valuesToStore) public {
        configs.push(ConfigStruct(_valuesToStore));
    }

    function add(string _name, uint _idConfig, bytes32 _valueToStore) valueIsPossible(_idConfig, _valueToStore) public {
        structs.push(TestStruct("test", _valueToStore));
    }

    modifier valueIsPossible(uint _idConfig, bytes32 _valueToStore) {
        //require(configs[_idConfig].valuesPossible[_valueToStore]); // How to check that
        _;
    }
}

Thanks by advance

EDIT: Sorry my code was not very accurate, I updated it

1 Answer 1

1

Simplest way : iterate over the array.

But it may not be the cheapest solution, since you have to iterate potentially the entire array to find the value you are looking for.

Depending on what you want to do, you could use a mapping instead, and find if it's "present" in O(1).

An example would be :

mapping (bytes32 => bool) public ValueExists;

Now, if you really need your array, you can combine the mapping solution and your array.

5
  • Thank you for your answer, I updated the question because it was not accurate enough
    – oktapodia
    May 31, 2018 at 14:04
  • My answer is still the same. You could add a mapping in your ConfigStruct, and everytime you push a bytes32 value into the byte32 array of a struct, you update the mapping by setting the value corresponding to the bytes32 key to true, so when you do your require, you can do require(configs[_idConfig].ValueExists[_valueToStore]); May 31, 2018 at 14:15
  • Thank you, but I also want to get the ValueExists data which looks not possible with a mapping
    – oktapodia
    May 31, 2018 at 15:07
  • Then, your mapping could point to a struct instead, which has two variables isExisting and index, something like that. When you push a new struct, you set the index to be my_array.length-1. May 31, 2018 at 15:48
  • Can you do a quick example please?
    – oktapodia
    May 31, 2018 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.