openzeppelin-contracts icon indicating copy to clipboard operation
openzeppelin-contracts copied to clipboard

`_unsafeAccess` for the `EnumerableSet`

Open songhobby opened this issue 2 years ago • 0 comments

🧐 Motivation Saw the new release of oz smart contracts and unsafeAccess, I was wondering if this gas saving function can be applied else where as well

📝 Details

The following is the code from EnumerableSet library function _remove For example we can change

bytes32 lastValue = set._values[lastIndex];

to

bytes32 lastValue = _unsafeAccess(set._values, lastIndex)

The original code is here.

function _remove(Set storage set, bytes32 value) private returns (bool) {
    uint256 valueIndex = set._indices[value];
    if (valueIndex != 0) {
      uint256 toDeleteIndex = valueIndex - 1;
      uint256 lastIndex = set._values.length - 1;
      if (lastIndex != toDeleteIndex) {
        bytes32 lastValue = set._values[lastIndex];
        set._values[toDeleteIndex] = lastValue;
        set._indices[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
      }
      set._values.pop();
      delete set._indices[value];
      return true;
    } else {
      return false;
    }
  }

songhobby avatar Nov 17 '22 20:11 songhobby