Verified contractPartialMIT
EmberSnapshot
Address0x637efe76b47518d62f76bdd93dadeacac99aa6c4
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.38
- Same code
Only this contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,398,154
- Creation transaction
- 0xc6cda31de3…e89e5d0aca
contracts/EmberSnapshot.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {DynamicArrayLib} from "solady/utils/DynamicArrayLib.sol";
import {LibSort} from "solady/utils/LibSort.sol";
import {PagedReader} from "./base/PagedReader.sol";
contract EmberSnapshot is PagedReader {
using DynamicArrayLib for DynamicArrayLib.DynamicArray;
struct Row {
uint256 id;
uint256 shares;
uint256 gross;
uint256 permanentFee;
uint256 timeFee;
}
struct Facts {
address asset;
uint256 held;
uint256 heldAssets;
Row[] rows;
}
struct Cursor {
uint256 next;
uint256 matched;
address validator;
uint256 queueLength;
}
function snapshot(address vault, address owner, address denomination)
external
view
returns (Facts memory f, bytes memory)
{
// Redundant with _readUint, but it fixes the optimizer layout that keeps
// the sparse queue scan about 24 gas per row cheaper.
if (vault == address(0)) revert InvalidInput();
PageState memory s = _newPage(256, 160, 128);
Cursor memory cursor;
if (s.cursor.length == 0) {
if (_address(_readUint(vault, abi.encodeWithSignature("parkingLot()"))) != address(0)) {
revert("unsupported Ember parking-lot deposit scope");
}
f.held = _readUint(vault, abi.encodeWithSignature("balanceOf(address)", owner));
uint256 pending = _readUint(vault, abi.encodeWithSignature("accounts(address)", owner));
if (f.held == 0 && pending == 0) return (f, "");
f.asset = _address(_readUint(vault, abi.encodeWithSignature("asset()")));
if (f.asset == address(0)) revert("invalid Ember asset binding");
if (f.held > 0 && denomination != vault) {
f.heldAssets = _readUint(vault, abi.encodeWithSignature("convertToAssets(uint256)", f.held));
}
if (pending == 0) return (f, "");
} else {
cursor = abi.decode(s.cursor, (Cursor));
}
bytes memory input = abi.encodeWithSignature("getAccountState(address)", owner);
bytes memory data = _read(vault, input);
(, uint256[] memory ids, uint256[] memory cancelled) = abi.decode(data, (uint256, uint256[], uint256[]));
if (ids.length == 0) revert("empty Ember owner request IDs");
LibSort.sort(cancelled);
if (s.cursor.length == 0) {
cursor.validator = _address(_readUint(vault, abi.encodeWithSignature("vaultValidator()")));
cursor.queueLength = _readUint(vault, abi.encodeWithSignature("getPendingWithdrawalsLength()"));
}
DynamicArrayLib.DynamicArray memory buffer = DynamicArrayLib.p().reserve(16);
for (uint256 i = cursor.next; i < cursor.queueLength && cursor.matched < ids.length; ++i) {
uint256 scratch;
assembly ("memory-safe") { scratch := mload(0x40) }
cursor.next = i;
if (_pause(s, abi.encode(cursor), 160)) break;
data = _read(vault, abi.encodeWithSignature("getPendingWithdrawal(uint256)", i), 192);
(address rowOwner,,,,,) = abi.decode(data, (address, address, uint256, uint256, uint256, uint256));
if (rowOwner != owner) {
assembly ("memory-safe") { mstore(0x40, scratch) }
continue;
}
++cursor.matched;
Row memory r;
address receiver;
uint256 timestamp;
uint256 ignored;
(, receiver, r.shares, ignored, timestamp, r.id) =
abi.decode(data, (address, address, uint256, uint256, uint256, uint256));
if (r.shares == 0 || receiver != owner || timestamp == 0 || timestamp > block.timestamp * 1000) {
revert("invalid Ember request custody or quantity");
}
bool returned = LibSort.inSorted(cancelled, r.id);
if (!returned) {
r.gross = _readUint(vault, abi.encodeWithSignature("convertToAssets(uint256)", r.shares));
}
if (r.gross > 0 && cursor.validator != address(0)) {
input = abi.encodeWithSignature(
"calculateWithdrawalFees(address,address,uint256,uint256)",
vault,
owner,
r.gross,
block.timestamp * 1000
);
(r.permanentFee, r.timeFee) = abi.decode(_read(cursor.validator, input, 64), (uint256, uint256));
}
uint256 pointer;
assembly ("memory-safe") { pointer := r }
buffer.p(pointer);
s.encodedBytes += 160;
}
if (s.nextCursor.length == 0 && cursor.matched != ids.length) revert("incomplete Ember owner queue");
uint256[] memory rows = buffer.data;
Row[] memory typedRows;
assembly ("memory-safe") { typedRows := rows }
f.rows = typedRows;
return (f, s.nextCursor);
}
}
contracts/base/BoundedStaticReader.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {LowLevelCall} from "openzeppelin/utils/LowLevelCall.sol";
/// @dev Static source calls and canonical scalar decoding.
abstract contract BoundedStaticReader {
error InvalidInput();
error SourceReadFailed(address target, bytes4 selector);
function _readUint(address target, bytes memory input) internal view returns (uint256 value) {
if (target == address(0) || input.length < 4) revert InvalidInput();
(bool success, bytes32 first,) = LowLevelCall.staticcallReturn64Bytes(target, input);
uint256 size = LowLevelCall.returnDataSize();
if (!success || size != 32) revert SourceReadFailed(target, bytes4(input));
return uint256(first);
}
function _probe(address target, bytes memory input, uint256 maxBytes)
internal
view
returns (bool success, bytes memory data)
{
if (target == address(0) || input.length < 4) revert InvalidInput();
(success, data) = target.staticcall(input);
if (success && data.length > maxBytes) revert SourceReadFailed(target, bytes4(input));
}
/// @dev Required reply of exactly `size` bytes.
function _read(address target, bytes memory input, uint256 size) internal view returns (bytes memory data) {
bool ok;
(ok, data) = _probe(target, input, size);
if (!ok || data.length != size) revert SourceReadFailed(target, bytes4(input));
}
/// @dev Required variable-width reply; the caller's ABI decoding checks its shape.
function _read(address target, bytes memory input) internal view returns (bytes memory data) {
bool ok;
(ok, data) = target.staticcall(input);
if (!ok) revert SourceReadFailed(target, bytes4(input));
}
/// @dev Optional exact-width reply: a failed or short reply is unavailable; an oversized success still fails.
function _try(address target, bytes memory input, uint256 size) internal view returns (bool ok, bytes memory data) {
(ok, data) = _probe(target, input, size);
ok = ok && data.length == size;
}
function _tryUint(address target, bytes memory input) internal view returns (bool ok, uint256 value) {
bytes memory data;
(ok, data) = _try(target, input, 32);
if (ok) value = abi.decode(data, (uint256));
}
function _address(uint256 value) internal pure returns (address) {
if (value > type(uint160).max) revert InvalidInput();
return address(uint160(value));
}
function _bool(uint256 value) internal pure returns (bool) {
if (value > 1) revert InvalidInput();
return value == 1;
}
function _uint(uint256 value, uint256 bits) internal pure returns (uint256) {
if (bits < 256 && value >> bits != 0) revert InvalidInput();
return value;
}
}
contracts/base/PagedReader.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.38;
import {BoundedStaticReader} from "./BoundedStaticReader.sol";
/// @dev Paging is transport state; Go values the completed native facts.
abstract contract PagedReader is BoundedStaticReader {
// 100,000-byte CRE Await envelope minus 106 protobuf bytes, rounded to ABI words.
uint256 internal constant MAX_RESPONSE_BYTES = 99_872;
uint256 internal constant DEFAULT_PAGE_BYTES = MAX_RESPONSE_BYTES - 192;
error ResponseBudgetTooSmall(uint256 required);
error ResponseTooLarge(uint256 actual, uint256 budget);
struct PageState {
bytes cursor;
uint256 checkpointGas;
uint256 unitGas;
uint256 encodedBytes;
uint256 responseBudget;
bytes nextCursor;
}
function page(bytes calldata snapshotCall, bytes calldata continuation) external view {
if (msg.sender == address(this) || snapshotCall.length < 4) revert InvalidInput();
_page(snapshotCall, continuation, DEFAULT_PAGE_BYTES);
}
/// @dev The outer batch supplies its remaining response capacity before acquisition.
function read(bytes calldata snapshotCall, uint256 budget) external view {
if (msg.sender == address(this) || snapshotCall.length < 4) revert InvalidInput();
if (bytes4(snapshotCall[:4]) == this.page.selector) {
(bytes memory original, bytes memory continuation) = abi.decode(snapshotCall[4:], (bytes, bytes));
_page(original, continuation, budget);
} else {
_page(snapshotCall, bytes(""), budget);
}
}
function _page(bytes memory snapshotCall, bytes memory continuation, uint256 budget) private view {
(bool success, bytes memory result) =
address(this).staticcall(abi.encodePacked(snapshotCall, continuation, uint256(continuation.length), budget));
if (!success) {
assembly ("memory-safe") { revert(add(result, 32), mload(result)) }
}
if (result.length > budget) revert ResponseTooLarge(result.length, budget);
assembly ("memory-safe") { return(add(result, 32), mload(result)) }
}
function _newPage(uint256 terminalBytes, uint256 maxUnitBytes, uint256 maxCursorBytes)
internal
view
returns (PageState memory state)
{
state.encodedBytes = terminalBytes;
state.responseBudget = DEFAULT_PAGE_BYTES;
if (msg.sender == address(this)) {
uint256 length;
uint256 budget;
assembly ("memory-safe") {
length := calldataload(sub(calldatasize(), 64))
budget := calldataload(sub(calldatasize(), 32))
}
state.responseBudget = budget;
state.cursor = msg.data[msg.data.length - 64 - length:msg.data.length - 64];
}
uint256 required = terminalBytes + maxUnitBytes;
if (maxUnitBytes != 0 || maxCursorBytes != 0) required += (maxCursorBytes + 31) & ~uint256(31);
if (required > state.responseBudget && state.responseBudget < DEFAULT_PAGE_BYTES) {
revert ResponseBudgetTooSmall(required);
}
}
// Always attempt the first indivisible unit. Reserve encoding/return memory
// using actual output size and the greatest observed unit cost on this page.
function _pause(PageState memory state, bytes memory cursor, uint256 nextUnitBytes) internal view returns (bool) {
uint256 remaining = gasleft();
if (state.checkpointGas != 0) {
uint256 spent = state.checkpointGas > remaining ? state.checkpointGas - remaining : 0;
if (spent > state.unitGas) state.unitGas = spent;
uint256 free;
assembly ("memory-safe") { free := mload(0x40) }
uint256 encoded = state.encodedBytes + ((cursor.length + 31) & ~uint256(31));
uint256 words = (free + 2 * encoded + 31) / 32;
uint256 current = (free + 31) / 32;
uint256 memoryGas = 3 * (words - current) + (words * words - current * current) / 512;
uint256 reserve = 40_000 + memoryGas + (encoded / 32) * 24;
if (
encoded + nextUnitBytes > state.responseBudget
|| remaining <= reserve + (state.unitGas > 10_000 ? state.unitGas : 10_000)
) {
state.nextCursor = cursor;
return true;
}
}
state.checkpointGas = gasleft();
return false;
}
}
lib/openzeppelin/contracts/utils/LowLevelCall.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (utils/LowLevelCall.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of low level call functions that implement different calling strategies to deal with the return data.
*
* WARNING: Using this library requires an advanced understanding of Solidity and how the EVM works. It is recommended
* to use the {Address} library instead.
*/
library LowLevelCall {
/// @dev Performs a Solidity function call using a low level `call` and ignoring the return data.
function callNoReturn(address target, bytes memory data) internal returns (bool success) {
return callNoReturn(target, 0, data);
}
/// @dev Same as {callNoReturn-address-bytes}, but allows specifying the value to be sent in the call.
function callNoReturn(address target, uint256 value, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `call` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function callReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
return callReturn64Bytes(target, 0, data);
}
/// @dev Same as {callReturn64Bytes-address-bytes}, but allows specifying the value to be sent in the call.
function callReturn64Bytes(
address target,
uint256 value,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := call(gas(), target, value, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and ignoring the return data.
function staticcallNoReturn(address target, bytes memory data) internal view returns (bool success) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `staticcall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function staticcallReturn64Bytes(
address target,
bytes memory data
) internal view returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := staticcall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and ignoring the return data.
function delegatecallNoReturn(address target, bytes memory data) internal returns (bool success) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x00)
}
}
/// @dev Performs a Solidity function call using a low level `delegatecall` and returns the first 64 bytes of the result
/// in the scratch space of memory. Useful for functions that return a tuple with two single-word values.
///
/// WARNING: Do not assume that the results are zero if `success` is false. Memory can be already allocated
/// and this function doesn't zero it out.
function delegatecallReturn64Bytes(
address target,
bytes memory data
) internal returns (bool success, bytes32 result1, bytes32 result2) {
assembly ("memory-safe") {
success := delegatecall(gas(), target, add(data, 0x20), mload(data), 0x00, 0x40)
result1 := mload(0x00)
result2 := mload(0x20)
}
}
/// @dev Returns the size of the return data buffer.
function returnDataSize() internal pure returns (uint256 size) {
assembly ("memory-safe") {
size := returndatasize()
}
}
/// @dev Returns a buffer containing the return data from the last call.
function returnData() internal pure returns (bytes memory result) {
assembly ("memory-safe") {
result := mload(0x40)
mstore(result, returndatasize())
returndatacopy(add(result, 0x20), 0x00, returndatasize())
mstore(0x40, add(result, add(0x20, returndatasize())))
}
}
/// @dev Revert with the return data from the last call.
function bubbleRevert() internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
returndatacopy(fmp, 0x00, returndatasize())
revert(fmp, returndatasize())
}
}
function bubbleRevert(bytes memory returndata) internal pure {
assembly ("memory-safe") {
revert(add(returndata, 0x20), mload(returndata))
}
}
}
lib/solady/src/utils/DynamicArrayLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for memory arrays with automatic capacity resizing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/DynamicArrayLib.sol)
library DynamicArrayLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STRUCTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Type to represent a dynamic array in memory.
/// You can directly assign to `data`, and the `p` function will
/// take care of the memory allocation.
///
/// Note: The capacity is a prime-checksummed word before the array. If you assign
/// an array you did not allocate (e.g. from calldata), that word can
/// masquerade as a capacity, making `p` skip reallocation and write out of bounds.
/// Arrays brought in via `wrap` carry the same risk, as `wrap` assigns to `data` too.
/// If you are not assigning to `data` or using `wrap`, you don't have to worry about it.
struct DynamicArray {
uint256[] data;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the element is not found in the array.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UINT256 ARRAY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Low level minimalist uint256 array operations.
// If you don't need syntax sugar, it's recommended to use these.
// Some of these functions return the same array for function chaining.
// e.g. `array.set(0, 1).set(1, 2)`.
/// @dev Returns a uint256 array with `n` elements. The elements are not zeroized.
function malloc(uint256 n) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := or(sub(0, shr(32, n)), mload(0x40))
mstore(result, n)
mstore(0x40, add(add(result, 0x20), shl(5, n)))
}
}
/// @dev Zeroizes all the elements of `a`.
function zeroize(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
calldatacopy(add(result, 0x20), calldatasize(), shl(5, mload(result)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function get(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getUint256(uint256[] memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getAddress(uint256[] memory a, uint256 i) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getBool(uint256[] memory a, uint256 i) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a[i]`, without bounds checking.
function getBytes32(uint256[] memory a, uint256 i) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(a, 0x20), shl(5, i)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, uint256 data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), data)
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, address data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), shr(96, shl(96, data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, bool data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), iszero(iszero(data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(uint256[] memory a, uint256 i, bytes32 data)
internal
pure
returns (uint256[] memory result)
{
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(result, 0x20), shl(5, i)), data)
}
}
/// @dev Casts `a` to `address[]`.
function asAddressArray(uint256[] memory a) internal pure returns (address[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `bool[]`.
function asBoolArray(uint256[] memory a) internal pure returns (bool[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `bytes32[]`.
function asBytes32Array(uint256[] memory a) internal pure returns (bytes32[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(address[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(bool[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Casts `a` to `uint256[]`.
function toUint256Array(bytes32[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
}
}
/// @dev Reduces the size of `a` to `n`.
/// If `n` is greater than the size of `a`, this will be a no-op.
function truncate(uint256[] memory a, uint256 n)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := a
mstore(mul(lt(n, mload(result)), result), n)
}
}
/// @dev Clears the array and attempts to free the memory if possible.
function free(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := a
let n := mload(result)
mstore(shl(6, lt(iszero(n), eq(add(shl(5, add(1, n)), result), mload(0x40)))), result)
mstore(result, 0)
}
}
/// @dev Equivalent to `keccak256(abi.encodePacked(a))`.
function hash(uint256[] memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := keccak256(add(a, 0x20), shl(5, mload(a)))
}
}
/// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
function slice(uint256[] memory a, uint256 start, uint256 end)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let arrayLen := mload(a)
if iszero(gt(arrayLen, end)) { end := arrayLen }
if iszero(gt(arrayLen, start)) { start := arrayLen }
if lt(start, end) {
result := mload(0x40)
let resultLen := sub(end, start)
mstore(result, resultLen)
a := add(a, shl(5, start))
// Copy the `a` one word at a time, backwards.
let o := shl(5, resultLen)
mstore(0x40, add(add(result, o), 0x20)) // Allocate memory.
for {} 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := sub(o, 0x20)
if iszero(o) { break }
}
}
}
}
/// @dev Returns a copy of `a` sliced from `start` to the end of the array.
function slice(uint256[] memory a, uint256 start)
internal
pure
returns (uint256[] memory result)
{
result = slice(a, start, type(uint256).max);
}
/// @dev Returns a copy of the array.
function copy(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(add(result, 0x20), shl(5, mload(a)))
let o := result
for { let d := sub(a, result) } 1 {} {
mstore(o, mload(add(o, d)))
o := add(0x20, o)
if eq(o, end) { break }
}
mstore(0x40, o)
}
}
/// @dev Returns if `needle` is in `a`.
function contains(uint256[] memory a, uint256 needle) internal pure returns (bool) {
return ~indexOf(a, needle, 0) != 0;
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(uint256[] memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0)
if lt(from, mload(a)) {
let o := add(a, shl(5, from))
let end := add(shl(5, add(1, mload(a))), a)
let c := mload(end) // Cache the word after the array.
for { mstore(end, needle) } 1 {} {
o := add(o, 0x20)
if eq(mload(o), needle) { break }
}
mstore(end, c) // Restore the word after the array.
if iszero(eq(o, end)) { result := shr(5, sub(o, add(0x20, a))) }
}
}
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(uint256[] memory a, uint256 needle) internal pure returns (uint256 result) {
result = indexOf(a, needle, 0);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(uint256[] memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
result := not(0)
let n := mload(a)
if n {
if iszero(lt(from, n)) { from := sub(n, 1) }
let o := add(shl(5, add(2, from)), a)
for { mstore(a, needle) } 1 {} {
o := sub(o, 0x20)
if eq(mload(o), needle) { break }
}
mstore(a, n) // Restore the length.
if iszero(eq(o, a)) { result := shr(5, sub(o, add(0x20, a))) }
}
}
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(uint256[] memory a, uint256 needle)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(a, needle, NOT_FOUND);
}
/// @dev Directly returns `a` without copying.
function directReturn(uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let retStart := sub(a, 0x20)
mstore(retStart, 0x20)
return(retStart, add(0x40, shl(5, mload(a))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DYNAMIC ARRAY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// Some of these functions return the same array for function chaining.
// e.g. `a.p("1").p("2")`.
/// @dev Shorthand for `a.data.length`.
function length(DynamicArray memory a) internal pure returns (uint256) {
return a.data.length;
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(uint256[] memory a) internal pure returns (DynamicArray memory result) {
result.data = a;
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(address[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(bool[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Wraps `a` in a dynamic array struct.
function wrap(bytes32[] memory a) internal pure returns (DynamicArray memory result) {
/// @solidity memory-safe-assembly
assembly {
mstore(result, a)
}
}
/// @dev Clears the array without deallocating the memory.
function clear(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(mload(result), 0)
}
}
/// @dev Clears the array and attempts to free the memory if possible.
function free(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(result)
if iszero(eq(arrData, 0x60)) {
let prime := 8188386068317523
let cap := mload(sub(arrData, 0x20))
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// If `cap` is non-zero and the memory is contiguous, we can free it.
if lt(iszero(cap), eq(mload(0x40), add(arrData, add(0x20, cap)))) {
mstore(0x40, sub(arrData, 0x20))
}
mstore(result, 0x60)
}
}
}
/// @dev Resizes the array to contain `n` elements. New elements will be zeroized.
function resize(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
reserve(result, n);
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(result)
let arrLen := mload(arrData)
if iszero(lt(n, arrLen)) {
calldatacopy(
add(arrData, shl(5, add(1, arrLen))),
calldatasize(),
shl(5, sub(n, arrLen))
)
}
mstore(arrData, n)
}
}
/// @dev Increases the size of `a` to `n`.
/// If `n` is less than the size of `a`, this will be a no-op.
/// This method does not zeroize any newly created elements.
function expand(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
if (n >= a.data.length) {
reserve(result, n);
/// @solidity memory-safe-assembly
assembly {
mstore(mload(result), n)
}
}
}
/// @dev Reduces the size of `a` to `n`.
/// If `n` is greater than the size of `a`, this will be a no-op.
function truncate(DynamicArray memory a, uint256 n)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(mul(lt(n, mload(mload(result))), mload(result)), n)
}
}
/// @dev Reserves at least `minimum` amount of contiguous memory.
function reserve(DynamicArray memory a, uint256 minimum)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(minimum, 0xffffffff)) { invalid() } // For extra safety.
for { let arrData := mload(a) } 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.
let prime := 8188386068317523
// Special case for `arrData` pointing to zero pointer.
if eq(arrData, 0x60) {
let newCap := shl(5, add(1, minimum))
let capSlot := mload(0x40)
mstore(capSlot, mul(prime, newCap)) // Store the capacity.
let newArrData := add(0x20, capSlot)
mstore(newArrData, 0) // Store the length.
mstore(0x40, add(newArrData, add(0x20, newCap))) // Allocate memory.
mstore(a, newArrData)
break
}
let w := not(0x1f)
let cap := mload(add(arrData, w)) // `mload(sub(arrData, w))`.
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
let newCap := shl(5, minimum)
// If we don't need to grow the memory.
if iszero(and(gt(minimum, mload(arrData)), gt(newCap, cap))) { break }
// If the memory is contiguous, we can simply expand it.
if eq(mload(0x40), add(arrData, add(0x20, cap))) {
mstore(add(arrData, w), mul(prime, newCap)) // Store the capacity.
mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
break
}
let capSlot := mload(0x40)
let newArrData := add(capSlot, 0x20)
mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
mstore(a, newArrData) // Store the `newArrData`.
// Copy `arrData` one word at a time, backwards.
for { let o := add(0x20, shl(5, mload(arrData))) } 1 {} {
mstore(add(newArrData, o), mload(add(arrData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(capSlot, mul(prime, newCap)) // Store the capacity.
mstore(newArrData, mload(arrData)) // Store the length.
break
}
}
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, uint256 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(a)
let newArrLen := add(mload(arrData), 1)
let newArrBytesLen := shl(5, newArrLen)
// 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.
let prime := 8188386068317523
let cap := mload(sub(arrData, 0x20))
// Extract `cap`, initializing it to zero if it is not a multiple of `prime`.
cap := mul(div(cap, prime), iszero(mod(cap, prime)))
// Expand / Reallocate memory if required.
// Note that we need to allocate an extra word for the length.
for {} iszero(lt(newArrBytesLen, cap)) {} {
// Approximately more than double the capacity to ensure more than enough space.
let newCap := add(cap, or(cap, newArrBytesLen))
// If the memory is contiguous, we can simply expand it.
if iszero(or(xor(mload(0x40), add(arrData, add(0x20, cap))), iszero(cap))) {
mstore(sub(arrData, 0x20), mul(prime, newCap)) // Store the capacity.
mstore(0x40, add(arrData, add(0x20, newCap))) // Expand the memory allocation.
break
}
// Set the `newArrData` to point to the word after `cap`.
let newArrData := add(mload(0x40), 0x20)
mstore(0x40, add(newArrData, add(0x20, newCap))) // Reallocate the memory.
mstore(a, newArrData) // Store the `newArrData`.
let w := not(0x1f)
// Copy `arrData` one word at a time, backwards.
for { let o := newArrBytesLen } 1 {} {
mstore(add(newArrData, o), mload(add(arrData, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
mstore(add(newArrData, w), mul(prime, newCap)) // Store the memory.
arrData := newArrData // Assign `newArrData` to `arrData`.
break
}
mstore(add(arrData, newArrBytesLen), data) // Append `data`.
mstore(arrData, newArrLen) // Store the length.
}
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, address data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, uint256(uint160(data)));
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, bool data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, _toUint(data));
}
/// @dev Appends `data` to `a`.
function p(DynamicArray memory a, bytes32 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = p(a, uint256(data));
}
/// @dev Shorthand for returning an empty array.
function p() internal pure returns (DynamicArray memory result) {}
/// @dev Shorthand for `p(p(), data)`.
function p(uint256 data) internal pure returns (DynamicArray memory result) {
p(result, uint256(data));
}
/// @dev Shorthand for `p(p(), data)`.
function p(address data) internal pure returns (DynamicArray memory result) {
p(result, uint256(uint160(data)));
}
/// @dev Shorthand for `p(p(), data)`.
function p(bool data) internal pure returns (DynamicArray memory result) {
p(result, _toUint(data));
}
/// @dev Shorthand for `p(p(), data)`.
function p(bytes32 data) internal pure returns (DynamicArray memory result) {
p(result, uint256(data));
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function pop(DynamicArray memory a) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popUint256(DynamicArray memory a) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popAddress(DynamicArray memory a) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popBool(DynamicArray memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Removes and returns the last element of `a`.
/// Returns 0 and does not pop anything if the array is empty.
function popBytes32(DynamicArray memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let o := mload(a)
let n := mload(o)
result := mload(add(o, shl(5, n)))
mstore(o, sub(n, iszero(iszero(n))))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function get(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getUint256(DynamicArray memory a, uint256 i) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getAddress(DynamicArray memory a, uint256 i) internal pure returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getBool(DynamicArray memory a, uint256 i) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Returns the element at `a.data[i]`, without bounds checking.
function getBytes32(DynamicArray memory a, uint256 i) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(add(add(mload(a), 0x20), shl(5, i)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, uint256 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), data)
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, address data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), shr(96, shl(96, data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, bool data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), iszero(iszero(data)))
}
}
/// @dev Sets `a.data[i]` to `data`, without bounds checking.
function set(DynamicArray memory a, uint256 i, bytes32 data)
internal
pure
returns (DynamicArray memory result)
{
_deallocate(result);
result = a;
/// @solidity memory-safe-assembly
assembly {
mstore(add(add(mload(result), 0x20), shl(5, i)), data)
}
}
/// @dev Returns the underlying array as a `uint256[]`.
function asUint256Array(DynamicArray memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `address[]`.
function asAddressArray(DynamicArray memory a) internal pure returns (address[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `bool[]`.
function asBoolArray(DynamicArray memory a) internal pure returns (bool[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns the underlying array as a `bytes32[]`.
function asBytes32Array(DynamicArray memory a) internal pure returns (bytes32[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(a)
}
}
/// @dev Returns a copy of `a` sliced from `start` to `end` (exclusive).
function slice(DynamicArray memory a, uint256 start, uint256 end)
internal
pure
returns (DynamicArray memory result)
{
result.data = slice(a.data, start, end);
}
/// @dev Returns a copy of `a` sliced from `start` to the end of the array.
function slice(DynamicArray memory a, uint256 start)
internal
pure
returns (DynamicArray memory result)
{
result.data = slice(a.data, start, type(uint256).max);
}
/// @dev Returns a copy of `a`.
function copy(DynamicArray memory a) internal pure returns (DynamicArray memory result) {
result.data = copy(a.data);
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, uint256 needle) internal pure returns (bool) {
return ~indexOf(a.data, needle, 0) != 0;
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, address needle) internal pure returns (bool) {
return ~indexOf(a.data, uint160(needle), 0) != 0;
}
/// @dev Returns if `needle` is in `a`.
function contains(DynamicArray memory a, bytes32 needle) internal pure returns (bool) {
return ~indexOf(a.data, uint256(needle), 0) != 0;
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, needle, from);
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, address needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, uint160(needle), from);
}
/// @dev Returns the first index of `needle`, scanning forward from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, bytes32 needle, uint256 from)
internal
pure
returns (uint256)
{
return indexOf(a.data, uint256(needle), from);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
return indexOf(a.data, needle, 0);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
return indexOf(a.data, uint160(needle), 0);
}
/// @dev Returns the first index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function indexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
return indexOf(a.data, uint256(needle), 0);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, uint256 needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, needle, from);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, address needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, uint160(needle), from);
}
/// @dev Returns the last index of `needle`, scanning backwards from `from`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, bytes32 needle, uint256 from)
internal
pure
returns (uint256)
{
return lastIndexOf(a.data, uint256(needle), from);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, uint256 needle) internal pure returns (uint256) {
return lastIndexOf(a.data, needle, NOT_FOUND);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, address needle) internal pure returns (uint256) {
return lastIndexOf(a.data, uint160(needle), NOT_FOUND);
}
/// @dev Returns the last index of `needle`.
/// If `needle` is not in `a`, returns `NOT_FOUND`.
function lastIndexOf(DynamicArray memory a, bytes32 needle) internal pure returns (uint256) {
return lastIndexOf(a.data, uint256(needle), NOT_FOUND);
}
/// @dev Equivalent to `keccak256(abi.encodePacked(a.data))`.
function hash(DynamicArray memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
result := keccak256(add(mload(a), 0x20), shl(5, mload(mload(a))))
}
}
/// @dev Directly returns `a` without copying.
function directReturn(DynamicArray memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let arrData := mload(a)
let retStart := sub(arrData, 0x20)
mstore(retStart, 0x20)
return(retStart, add(0x40, shl(5, mload(arrData))))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper for deallocating an automatically allocated array pointer.
function _deallocate(DynamicArray memory result) private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x40, result) // Deallocate, as we have already allocated.
}
}
/// @dev Casts the bool into a uint256.
function _toUint(bool b) private pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
result := iszero(iszero(b))
}
}
}
lib/solady/src/utils/LibSort.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Optimized sorts and operations for sorted arrays.
/// @author Solady (https://github.com/Vectorized/solady/blob/main/src/utils/LibSort.sol)
library LibSort {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSERTION SORT */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// - Faster on small arrays (32 or lesser elements).
// - Faster on almost sorted arrays.
// - Smaller bytecode (about 300 bytes smaller than sort, which uses intro-quicksort).
// - May be suitable for view functions intended for off-chain querying.
/// @dev Sorts the array in-place with insertion sort.
function insertionSort(uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let n := mload(a) // Length of `a`.
mstore(a, 0) // For insertion sort's inner loop to terminate.
let h := add(a, shl(5, n)) // High slot.
let w := not(0x1f)
for { let i := add(a, 0x20) } 1 {} {
i := add(i, 0x20)
if gt(i, h) { break }
let k := mload(i) // Key.
let j := add(i, w) // The slot before the current slot.
let v := mload(j) // The value of `j`.
if iszero(gt(v, k)) { continue }
for {} 1 {} {
mstore(add(j, 0x20), v)
j := add(j, w) // `sub(j, 0x20)`.
v := mload(j)
if iszero(gt(v, k)) { break }
}
mstore(add(j, 0x20), k)
}
mstore(a, n) // Restore the length of `a`.
}
}
/// @dev Sorts the array in-place with insertion sort.
function insertionSort(int256[] memory a) internal pure {
_flipSign(a);
insertionSort(_toUints(a));
_flipSign(a);
}
/// @dev Sorts the array in-place with insertion sort.
function insertionSort(address[] memory a) internal pure {
insertionSort(_toUints(a));
}
/// @dev Sorts the array in-place with insertion sort.
function insertionSort(bytes32[] memory a) internal pure {
insertionSort(_toUints(a));
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTRO-QUICKSORT */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// - Faster on larger arrays (more than 32 elements).
// - Robust performance.
// - Larger bytecode.
/// @dev Sorts the array in-place with intro-quicksort.
function sort(uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
function swap(a_, b_) -> _a, _b {
_b := a_
_a := b_
}
function mswap(i_, j_) {
let t_ := mload(i_)
mstore(i_, mload(j_))
mstore(j_, t_)
}
function sortInner(w_, l_, h_) {
// Do insertion sort if `h_ - l_ <= 0x20 * 12`.
// Threshold is fine-tuned via trial and error.
if iszero(gt(sub(h_, l_), 0x180)) {
// Hardcode sort the first 2 elements.
let i_ := add(l_, 0x20)
if iszero(lt(mload(l_), mload(i_))) { mswap(i_, l_) }
for {} 1 {} {
i_ := add(i_, 0x20)
if gt(i_, h_) { break }
let k_ := mload(i_) // Key.
let j_ := add(i_, w_) // The slot before the current slot.
let v_ := mload(j_) // The value of `j_`.
if iszero(gt(v_, k_)) { continue }
for {} 1 {} {
mstore(add(j_, 0x20), v_)
j_ := add(j_, w_)
v_ := mload(j_)
if iszero(gt(v_, k_)) { break }
}
mstore(add(j_, 0x20), k_)
}
leave
}
// Pivot slot is the average of `l_` and `h_`.
let p_ := add(shl(5, shr(6, add(l_, h_))), and(31, l_))
// Median of 3 with sorting.
{
let e0_ := mload(l_)
let e1_ := mload(p_)
if iszero(lt(e0_, e1_)) { e0_, e1_ := swap(e0_, e1_) }
let e2_ := mload(h_)
if iszero(lt(e1_, e2_)) {
e1_, e2_ := swap(e1_, e2_)
if iszero(lt(e0_, e1_)) { e0_, e1_ := swap(e0_, e1_) }
}
mstore(h_, e2_)
mstore(p_, e1_)
mstore(l_, e0_)
}
// Hoare's partition.
{
// The value of the pivot slot.
let x_ := mload(p_)
p_ := h_
for { let i_ := l_ } 1 {} {
for {} 1 {} {
i_ := add(0x20, i_)
if iszero(gt(x_, mload(i_))) { break }
}
let j_ := p_
for {} 1 {} {
j_ := add(w_, j_)
if iszero(lt(x_, mload(j_))) { break }
}
p_ := j_
if iszero(lt(i_, p_)) { break }
mswap(i_, p_)
}
}
if iszero(eq(add(p_, 0x20), h_)) { sortInner(w_, add(p_, 0x20), h_) }
if iszero(eq(p_, l_)) { sortInner(w_, l_, p_) }
}
for { let n := mload(a) } iszero(lt(n, 2)) {} {
let w := not(0x1f) // `-0x20`.
let l := add(a, 0x20) // Low slot.
let h := add(a, shl(5, n)) // High slot.
let j := h
// While `mload(j - 0x20) <= mload(j): j -= 0x20`.
for {} iszero(gt(mload(add(w, j)), mload(j))) {} { j := add(w, j) }
// If the array is already sorted, break.
if iszero(gt(j, l)) { break }
// While `mload(j - 0x20) >= mload(j): j -= 0x20`.
for { j := h } iszero(lt(mload(add(w, j)), mload(j))) {} { j := add(w, j) }
// If the array is reversed sorted.
if iszero(gt(j, l)) {
for {} 1 {} {
let t := mload(l)
mstore(l, mload(h))
mstore(h, t)
h := add(w, h)
l := add(l, 0x20)
if iszero(lt(l, h)) { break }
}
break
}
mstore(a, 0) // For insertion sort's inner loop to terminate.
sortInner(w, l, h)
mstore(a, n) // Restore the length of `a`.
break
}
}
}
/// @dev Sorts the array in-place with intro-quicksort.
function sort(int256[] memory a) internal pure {
_flipSign(a);
sort(_toUints(a));
_flipSign(a);
}
/// @dev Sorts the array in-place with intro-quicksort.
function sort(address[] memory a) internal pure {
sort(_toUints(a));
}
/// @dev Sorts the array in-place with intro-quicksort.
function sort(bytes32[] memory a) internal pure {
sort(_toUints(a));
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OTHER USEFUL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance, the `uniquifySorted` methods will not revert if the
// array is not sorted -- it will simply remove consecutive duplicate elements.
/// @dev Removes duplicate elements from a ascendingly sorted memory array.
function uniquifySorted(uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
// If the length of `a` is greater than 1.
if iszero(lt(mload(a), 2)) {
let x := add(a, 0x20)
let y := add(a, 0x40)
let end := add(a, shl(5, add(mload(a), 1)))
for {} 1 {} {
if iszero(eq(mload(x), mload(y))) {
x := add(x, 0x20)
mstore(x, mload(y))
}
y := add(y, 0x20)
if eq(y, end) { break }
}
mstore(a, shr(5, sub(x, a)))
}
}
}
/// @dev Removes duplicate elements from a ascendingly sorted memory array.
function uniquifySorted(int256[] memory a) internal pure {
uniquifySorted(_toUints(a));
}
/// @dev Removes duplicate elements from a ascendingly sorted memory array.
function uniquifySorted(address[] memory a) internal pure {
uniquifySorted(_toUints(a));
}
/// @dev Removes duplicate elements from a ascendingly sorted memory array.
function uniquifySorted(bytes32[] memory a) internal pure {
uniquifySorted(_toUints(a));
}
/// @dev Returns whether `a` contains `needle`, and the index of `needle`.
/// `index` precedence: equal to > nearest before > nearest after.
function searchSorted(uint256[] memory a, uint256 needle)
internal
pure
returns (bool found, uint256 index)
{
(found, index) = _searchSorted(a, needle, 0);
}
/// @dev Returns whether `a` contains `needle`, and the index of `needle`.
/// `index` precedence: equal to > nearest before > nearest after.
function searchSorted(int256[] memory a, int256 needle)
internal
pure
returns (bool found, uint256 index)
{
(found, index) = _searchSorted(_toUints(a), uint256(needle), 1 << 255);
}
/// @dev Returns whether `a` contains `needle`, and the index of `needle`.
/// `index` precedence: equal to > nearest before > nearest after.
function searchSorted(address[] memory a, address needle)
internal
pure
returns (bool found, uint256 index)
{
(found, index) = _searchSorted(_toUints(a), uint160(needle), 0);
}
/// @dev Returns whether `a` contains `needle`, and the index of `needle`.
/// `index` precedence: equal to > nearest before > nearest after.
function searchSorted(bytes32[] memory a, bytes32 needle)
internal
pure
returns (bool found, uint256 index)
{
(found, index) = _searchSorted(_toUints(a), uint256(needle), 0);
}
/// @dev Returns whether `a` contains `needle`.
function inSorted(uint256[] memory a, uint256 needle) internal pure returns (bool found) {
(found,) = searchSorted(a, needle);
}
/// @dev Returns whether `a` contains `needle`.
function inSorted(int256[] memory a, int256 needle) internal pure returns (bool found) {
(found,) = searchSorted(a, needle);
}
/// @dev Returns whether `a` contains `needle`.
function inSorted(address[] memory a, address needle) internal pure returns (bool found) {
(found,) = searchSorted(a, needle);
}
/// @dev Returns whether `a` contains `needle`.
function inSorted(bytes32[] memory a, bytes32 needle) internal pure returns (bool found) {
(found,) = searchSorted(a, needle);
}
/// @dev Reverses the array in-place.
function reverse(uint256[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
if iszero(lt(mload(a), 2)) {
let s := 0x20
let w := not(0x1f)
let h := add(a, shl(5, mload(a)))
for { a := add(a, s) } 1 {} {
let t := mload(a)
mstore(a, mload(h))
mstore(h, t)
h := add(h, w)
a := add(a, s)
if iszero(lt(a, h)) { break }
}
}
}
}
/// @dev Reverses the array in-place.
function reverse(int256[] memory a) internal pure {
reverse(_toUints(a));
}
/// @dev Reverses the array in-place.
function reverse(address[] memory a) internal pure {
reverse(_toUints(a));
}
/// @dev Reverses the array in-place.
function reverse(bytes32[] memory a) internal pure {
reverse(_toUints(a));
}
/// @dev Returns a copy of the array.
function copy(uint256[] memory a) internal pure returns (uint256[] memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
let end := add(add(result, 0x20), shl(5, mload(a)))
let o := result
for { let d := sub(a, result) } 1 {} {
mstore(o, mload(add(o, d)))
o := add(0x20, o)
if eq(o, end) { break }
}
mstore(0x40, o)
}
}
/// @dev Returns a copy of the array.
function copy(int256[] memory a) internal pure returns (int256[] memory result) {
result = _toInts(copy(_toUints(a)));
}
/// @dev Returns a copy of the array.
function copy(address[] memory a) internal pure returns (address[] memory result) {
result = _toAddresses(copy(_toUints(a)));
}
/// @dev Returns a copy of the array.
function copy(bytes32[] memory a) internal pure returns (bytes32[] memory result) {
result = _toBytes32s(copy(_toUints(a)));
}
/// @dev Returns whether the array is sorted in ascending order.
function isSorted(uint256[] memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
for { a := add(a, 0x20) } 1 {} {
let p := mload(a)
a := add(a, 0x20)
result := iszero(gt(p, mload(a)))
if iszero(mul(result, xor(a, end))) { break }
}
}
}
}
/// @dev Returns whether the array is sorted in ascending order.
function isSorted(int256[] memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
for { a := add(a, 0x20) } 1 {} {
let p := mload(a)
a := add(a, 0x20)
result := iszero(sgt(p, mload(a)))
if iszero(mul(result, xor(a, end))) { break }
}
}
}
}
/// @dev Returns whether the array is sorted in ascending order.
function isSorted(address[] memory a) internal pure returns (bool result) {
result = isSorted(_toUints(a));
}
/// @dev Returns whether the array is sorted in ascending order.
function isSorted(bytes32[] memory a) internal pure returns (bool result) {
result = isSorted(_toUints(a));
}
/// @dev Returns whether the array is strictly ascending (sorted and uniquified).
function isSortedAndUniquified(uint256[] memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
for { a := add(a, 0x20) } 1 {} {
let p := mload(a)
a := add(a, 0x20)
result := lt(p, mload(a))
if iszero(mul(result, xor(a, end))) { break }
}
}
}
}
/// @dev Returns whether the array is strictly ascending (sorted and uniquified).
function isSortedAndUniquified(int256[] memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result := 1
if iszero(lt(mload(a), 2)) {
let end := add(a, shl(5, mload(a)))
for { a := add(a, 0x20) } 1 {} {
let p := mload(a)
a := add(a, 0x20)
result := slt(p, mload(a))
if iszero(mul(result, xor(a, end))) { break }
}
}
}
}
/// @dev Returns whether the array is strictly ascending (sorted and uniquified).
function isSortedAndUniquified(address[] memory a) internal pure returns (bool result) {
result = isSortedAndUniquified(_toUints(a));
}
/// @dev Returns whether the array is strictly ascending (sorted and uniquified).
function isSortedAndUniquified(bytes32[] memory a) internal pure returns (bool result) {
result = isSortedAndUniquified(_toUints(a));
}
/// @dev Returns the sorted set difference of `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function difference(uint256[] memory a, uint256[] memory b)
internal
pure
returns (uint256[] memory c)
{
c = _difference(a, b, 0);
}
/// @dev Returns the sorted set difference between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function difference(int256[] memory a, int256[] memory b)
internal
pure
returns (int256[] memory c)
{
c = _toInts(_difference(_toUints(a), _toUints(b), 1 << 255));
}
/// @dev Returns the sorted set difference between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function difference(address[] memory a, address[] memory b)
internal
pure
returns (address[] memory c)
{
c = _toAddresses(_difference(_toUints(a), _toUints(b), 0));
}
/// @dev Returns the sorted set difference between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function difference(bytes32[] memory a, bytes32[] memory b)
internal
pure
returns (bytes32[] memory c)
{
c = _toBytes32s(_difference(_toUints(a), _toUints(b), 0));
}
/// @dev Returns the sorted set intersection between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function intersection(uint256[] memory a, uint256[] memory b)
internal
pure
returns (uint256[] memory c)
{
c = _intersection(a, b, 0);
}
/// @dev Returns the sorted set intersection between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function intersection(int256[] memory a, int256[] memory b)
internal
pure
returns (int256[] memory c)
{
c = _toInts(_intersection(_toUints(a), _toUints(b), 1 << 255));
}
/// @dev Returns the sorted set intersection between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function intersection(address[] memory a, address[] memory b)
internal
pure
returns (address[] memory c)
{
c = _toAddresses(_intersection(_toUints(a), _toUints(b), 0));
}
/// @dev Returns the sorted set intersection between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function intersection(bytes32[] memory a, bytes32[] memory b)
internal
pure
returns (bytes32[] memory c)
{
c = _toBytes32s(_intersection(_toUints(a), _toUints(b), 0));
}
/// @dev Returns the sorted set union of `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function union(uint256[] memory a, uint256[] memory b)
internal
pure
returns (uint256[] memory c)
{
c = _union(a, b, 0);
}
/// @dev Returns the sorted set union of `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function union(int256[] memory a, int256[] memory b) internal pure returns (int256[] memory c) {
c = _toInts(_union(_toUints(a), _toUints(b), 1 << 255));
}
/// @dev Returns the sorted set union between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function union(address[] memory a, address[] memory b)
internal
pure
returns (address[] memory c)
{
c = _toAddresses(_union(_toUints(a), _toUints(b), 0));
}
/// @dev Returns the sorted set union between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function union(bytes32[] memory a, bytes32[] memory b)
internal
pure
returns (bytes32[] memory c)
{
c = _toBytes32s(_union(_toUints(a), _toUints(b), 0));
}
/// @dev Cleans the upper 96 bits of the addresses.
/// In case `a` is produced via assembly and might have dirty upper bits.
function clean(address[] memory a) internal pure {
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
for { let end := add(a, shl(5, mload(a))) } iszero(eq(a, end)) {} {
a := add(a, 0x20)
mstore(a, and(mload(a), addressMask))
}
}
}
/// @dev Sorts and uniquifies `keys`. Updates `values` with the grouped sums by key.
function groupSum(uint256[] memory keys, uint256[] memory values) internal pure {
/// @solidity memory-safe-assembly
assembly {
function mswap(i_, j_) {
let t_ := mload(i_)
mstore(i_, mload(j_))
mstore(j_, t_)
}
function sortInner(l_, h_, d_) {
let p_ := mload(l_)
let j_ := l_
for { let i_ := add(l_, 0x20) } 1 {} {
if lt(mload(i_), p_) {
j_ := add(j_, 0x20)
mswap(i_, j_)
mswap(add(i_, d_), add(j_, d_))
}
i_ := add(0x20, i_)
if iszero(lt(i_, h_)) { break }
}
mswap(l_, j_)
mswap(add(l_, d_), add(j_, d_))
if iszero(gt(add(0x40, l_), j_)) { sortInner(l_, j_, d_) }
if iszero(gt(add(0x60, j_), h_)) { sortInner(add(j_, 0x20), h_, d_) }
}
let n := mload(values)
if iszero(eq(mload(keys), n)) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x32) // Array out of bounds panic if the arrays lengths differ.
revert(0x1c, 0x24)
}
if iszero(lt(n, 2)) {
let d := sub(values, keys)
let x := add(keys, 0x20)
let end := add(x, shl(5, n))
sortInner(x, end, d)
let s := mload(add(x, d))
for { let y := add(keys, 0x40) } 1 {} {
if iszero(eq(mload(x), mload(y))) {
mstore(add(x, d), s) // Write sum.
s := 0
x := add(x, 0x20)
mstore(x, mload(y))
}
s := add(s, mload(add(y, d)))
if lt(s, mload(add(y, d))) {
mstore(0x00, 0x4e487b71)
mstore(0x20, 0x11) // Overflow panic if the addition overflows.
revert(0x1c, 0x24)
}
y := add(y, 0x20)
if eq(y, end) { break }
}
mstore(add(x, d), s) // Write sum.
mstore(keys, shr(5, sub(x, keys))) // Truncate.
mstore(values, mload(keys)) // Truncate.
}
}
}
/// @dev Sorts and uniquifies `keys`. Updates `values` with the grouped sums by key.
function groupSum(address[] memory keys, uint256[] memory values) internal pure {
groupSum(_toUints(keys), values);
}
/// @dev Sorts and uniquifies `keys`. Updates `values` with the grouped sums by key.
function groupSum(bytes32[] memory keys, uint256[] memory values) internal pure {
groupSum(_toUints(keys), values);
}
/// @dev Sorts and uniquifies `keys`. Updates `values` with the grouped sums by key.
function groupSum(int256[] memory keys, uint256[] memory values) internal pure {
_flipSign(keys);
groupSum(_toUints(keys), values);
_flipSign(keys);
}
/// @dev Returns if `a` has any duplicate. Does NOT mutate `a`. `O(n)`.
function hasDuplicate(uint256[] memory a) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
function p(i_, x_) -> _y {
_y := or(shr(i_, x_), x_)
}
let n := mload(a)
if iszero(lt(n, 2)) {
let m := mload(0x40) // Use free memory temporarily for hashmap.
let w := not(0x1f) // `-0x20`.
let c := and(w, p(16, p(8, p(4, p(2, p(1, mul(0x30, n)))))))
calldatacopy(m, calldatasize(), add(0x20, c)) // Zeroize hashmap.
for { let i := add(a, shl(5, n)) } 1 {} {
// See LibPRNG for explanation of this formula.
let r := mulmod(mload(i), 0x100000000000000000000000000000051, not(0xbc))
// Linear probing.
for {} 1 { r := add(0x20, r) } {
let o := add(m, and(r, c)) // Non-zero pointer into hashmap.
if iszero(mload(o)) {
mstore(o, i) // Store non-zero pointer into hashmap.
break
}
if eq(mload(mload(o)), mload(i)) {
result := 1
i := a // To break the outer loop.
break
}
}
i := add(i, w) // Iterate `a` backwards.
if iszero(lt(a, i)) { break }
}
if shr(31, n) { invalid() } // Just in case.
}
}
}
/// @dev Returns if `a` has any duplicate. Does NOT mutate `a`. `O(n)`.
function hasDuplicate(address[] memory a) internal pure returns (bool) {
return hasDuplicate(_toUints(a));
}
/// @dev Returns if `a` has any duplicate. Does NOT mutate `a`. `O(n)`.
function hasDuplicate(bytes32[] memory a) internal pure returns (bool) {
return hasDuplicate(_toUints(a));
}
/// @dev Returns if `a` has any duplicate. Does NOT mutate `a`. `O(n)`.
function hasDuplicate(int256[] memory a) internal pure returns (bool) {
return hasDuplicate(_toUints(a));
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Reinterpret cast to an uint256 array.
function _toUints(int256[] memory a) private pure returns (uint256[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
casted := a
}
}
/// @dev Reinterpret cast to an uint256 array.
function _toUints(address[] memory a) private pure returns (uint256[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
// As any address written to memory will have the upper 96 bits
// of the word zeroized (as per Solidity spec), we can directly
// compare these addresses as if they are whole uint256 words.
casted := a
}
}
/// @dev Reinterpret cast to an uint256 array.
function _toUints(bytes32[] memory a) private pure returns (uint256[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
casted := a
}
}
/// @dev Reinterpret cast to an int array.
function _toInts(uint256[] memory a) private pure returns (int256[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
casted := a
}
}
/// @dev Reinterpret cast to an address array.
function _toAddresses(uint256[] memory a) private pure returns (address[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
casted := a
}
}
/// @dev Reinterpret cast to an bytes32 array.
function _toBytes32s(uint256[] memory a) private pure returns (bytes32[] memory casted) {
/// @solidity memory-safe-assembly
assembly {
casted := a
}
}
/// @dev Converts an array of signed integers to unsigned
/// integers suitable for sorting or vice versa.
function _flipSign(int256[] memory a) private pure {
/// @solidity memory-safe-assembly
assembly {
let q := shl(255, 1)
for { let i := add(a, shl(5, mload(a))) } iszero(eq(a, i)) {} {
mstore(i, add(mload(i), q))
i := sub(i, 0x20)
}
}
}
/// @dev Returns whether `a` contains `needle`, and the index of `needle`.
/// `index` precedence: equal to > nearest before > nearest after.
function _searchSorted(uint256[] memory a, uint256 needle, uint256 signed)
private
pure
returns (bool found, uint256 index)
{
/// @solidity memory-safe-assembly
assembly {
let w := not(0)
let l := 1
let h := mload(a)
let t := 0
for { needle := add(signed, needle) } 1 {} {
index := shr(1, add(l, h))
t := add(signed, mload(add(a, shl(5, index))))
if or(gt(l, h), eq(t, needle)) { break }
// Decide whether to search the left or right half.
if iszero(gt(needle, t)) {
h := add(index, w)
continue
}
l := add(index, 1)
}
// `index` will be zero in the case of an empty array,
// or when the value is less than the smallest value in the array.
found := eq(t, needle)
t := iszero(iszero(index))
index := mul(add(index, w), t)
found := and(found, t)
}
}
/// @dev Returns the sorted set difference of `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function _difference(uint256[] memory a, uint256[] memory b, uint256 signed)
private
pure
returns (uint256[] memory c)
{
/// @solidity memory-safe-assembly
assembly {
let s := 0x20
let aEnd := add(a, shl(5, mload(a)))
let bEnd := add(b, shl(5, mload(b)))
c := mload(0x40) // Set `c` to the free memory pointer.
a := add(a, s)
b := add(b, s)
let k := c
for {} iszero(or(gt(a, aEnd), gt(b, bEnd))) {} {
let u := mload(a)
let v := mload(b)
if iszero(xor(u, v)) {
a := add(a, s)
b := add(b, s)
continue
}
if iszero(lt(add(u, signed), add(v, signed))) {
b := add(b, s)
continue
}
k := add(k, s)
mstore(k, u)
a := add(a, s)
}
for {} iszero(gt(a, aEnd)) {} {
k := add(k, s)
mstore(k, mload(a))
a := add(a, s)
}
mstore(c, shr(5, sub(k, c))) // Store the length of `c`.
mstore(0x40, add(k, s)) // Allocate the memory for `c`.
}
}
/// @dev Returns the sorted set intersection between `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function _intersection(uint256[] memory a, uint256[] memory b, uint256 signed)
private
pure
returns (uint256[] memory c)
{
/// @solidity memory-safe-assembly
assembly {
let s := 0x20
let aEnd := add(a, shl(5, mload(a)))
let bEnd := add(b, shl(5, mload(b)))
c := mload(0x40) // Set `c` to the free memory pointer.
a := add(a, s)
b := add(b, s)
let k := c
for {} iszero(or(gt(a, aEnd), gt(b, bEnd))) {} {
let u := mload(a)
let v := mload(b)
if iszero(xor(u, v)) {
k := add(k, s)
mstore(k, u)
a := add(a, s)
b := add(b, s)
continue
}
if iszero(lt(add(u, signed), add(v, signed))) {
b := add(b, s)
continue
}
a := add(a, s)
}
mstore(c, shr(5, sub(k, c))) // Store the length of `c`.
mstore(0x40, add(k, s)) // Allocate the memory for `c`.
}
}
/// @dev Returns the sorted set union of `a` and `b`.
/// Note: Behaviour is undefined if inputs are not sorted and uniquified.
function _union(uint256[] memory a, uint256[] memory b, uint256 signed)
private
pure
returns (uint256[] memory c)
{
/// @solidity memory-safe-assembly
assembly {
let s := 0x20
let aEnd := add(a, shl(5, mload(a)))
let bEnd := add(b, shl(5, mload(b)))
c := mload(0x40) // Set `c` to the free memory pointer.
a := add(a, s)
b := add(b, s)
let k := c
for {} iszero(or(gt(a, aEnd), gt(b, bEnd))) {} {
let u := mload(a)
let v := mload(b)
if iszero(xor(u, v)) {
k := add(k, s)
mstore(k, u)
a := add(a, s)
b := add(b, s)
continue
}
if iszero(lt(add(u, signed), add(v, signed))) {
k := add(k, s)
mstore(k, v)
b := add(b, s)
continue
}
k := add(k, s)
mstore(k, u)
a := add(a, s)
}
for {} iszero(gt(a, aEnd)) {} {
k := add(k, s)
mstore(k, mload(a))
a := add(a, s)
}
for {} iszero(gt(b, bEnd)) {} {
k := add(k, s)
mstore(k, mload(b))
b := add(b, s)
}
mstore(c, shr(5, sub(k, c))) // Store the length of `c`.
mstore(0x40, add(k, s)) // Allocate the memory for `c`.
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"solady/=lib/solady/src/",
"openzeppelin/=lib/openzeppelin/contracts/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.