Skip to content

Commit

Permalink
✨ Add convenience equality check (#1160)
Browse files Browse the repository at this point in the history
  • Loading branch information
Vectorized authored Nov 9, 2024
1 parent 1c9927e commit a3d6a97
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/utils/EfficientHashLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,26 @@ library EfficientHashLib {
}
}

/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EQUALITY CHECKS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

/// @dev Returns `a == abi.decode(b, (bytes32))`.
function eq(bytes32 a, bytes memory b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := and(eq(0x20, mload(b)), eq(a, mload(add(b, 0x20))))
}
}

/// @dev Returns `abi.decode(a, (bytes32)) == a`.
function eq(bytes memory a, bytes32 b) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := and(eq(0x20, mload(a)), eq(b, mload(add(a, 0x20))))
}
}

/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE SLICE HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
Expand Down
21 changes: 21 additions & 0 deletions test/EfficientHashLib.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,25 @@ contract EfficientHashLibTest is SoladyTest {
function testEfficientHashBytesSlice() public {
this.testEfficientHashBytesSlice(bytes32(0), "0123456789");
}

function testEfficientHashEq(bytes32 a, uint256 n) public {
bytes memory b = abi.encode(a);
bytes memory s = abi.encode(a);
/// @solidity memory-safe-assembly
assembly {
mstore(s, mod(n, 0x20))
}
assertTrue(EfficientHashLib.eq(a, b));
assertTrue(EfficientHashLib.eq(b, a));
assertFalse(EfficientHashLib.eq(a, s));
assertFalse(EfficientHashLib.eq(s, a));
}

function testEfficientHashEq() public {
bytes32 a = 0x123456789a123456789a123456789a123456789a123456789a123456789a1234;
bytes memory b = hex"123456789a123456789a123456789a123456789a123456789a123456789a1234";
assertTrue(EfficientHashLib.eq(a, b));
// The following costs approximately 90 more gas:
// `assertTrue(a == abi.decode(b, (bytes32)))`;
}
}

0 comments on commit a3d6a97

Please sign in to comment.