Skip to content

Commit

Permalink
Optimize DynamicArrayLib
Browse files Browse the repository at this point in the history
  • Loading branch information
Vectorized committed Sep 18, 2024
1 parent 0234e7d commit 6cd2a73
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
6 changes: 2 additions & 4 deletions src/utils/DynamicArrayLib.sol
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ library DynamicArrayLib {
assembly {
result := mload(0x40)
mstore(result, n)
mstore(0x40, add(add(result, 0x20), shl(5, n)))
if iszero(lt(n, 0xffffffff)) { invalid() }
mstore(or(sub(0, shr(32, n)), 0x40), add(add(result, 0x20), shl(5, n)))
}
}

Expand Down Expand Up @@ -205,8 +204,7 @@ library DynamicArrayLib {
result = array;
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(minimum, 0xffffffff)) { invalid() } // For extra safety.
for { let arrData := mload(array) } 1 {} {
for { let arrData := mload(or(sub(0, shr(32, minimum)), array)) } 1 {} {
// Some random prime number to multiply `cap`, so that
// we know that the `cap` is for a dynamic array.
// Selected to be larger than any memory pointer realistically.
Expand Down
30 changes: 30 additions & 0 deletions test/DynamicArrayLib.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,36 @@ contract DynamicArrayLibTest is SoladyTest {
}
}

function testUint256ArrayPopulate() public {
unchecked {
uint256 n = 100;
uint256[] memory a = DynamicArrayLib.malloc(n);
for (uint256 i; i != n; ++i) {
a.set(i, i);
}
uint256 sum;
for (uint256 i; i != n; ++i) {
sum += a.get(i);
}
assertEq(sum, 4950);
}
}

function testUint256ArrayPopulateOriginal() public {
unchecked {
uint256 n = 100;
uint256[] memory a = new uint256[](n);
for (uint256 i; i != n; ++i) {
a[i] = i;
}
uint256 sum;
for (uint256 i; i != n; ++i) {
sum += a[i];
}
assertEq(sum, 4950);
}
}

function testUint256ArrayOperations(uint256 n, uint256 r) public {
unchecked {
n = _bound(n, 0, 50);
Expand Down

0 comments on commit 6cd2a73

Please sign in to comment.