Skip to content

Commit

Permalink
Merge branch 'master' into optimize_log2
Browse files Browse the repository at this point in the history
  • Loading branch information
Amxx authored Feb 7, 2024
2 parents a371515 + 0a757ec commit b0ad358
Show file tree
Hide file tree
Showing 20 changed files with 261 additions and 113 deletions.
5 changes: 5 additions & 0 deletions .changeset/dirty-cobras-smile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Arrays`: add a `sort` function.
5 changes: 5 additions & 0 deletions .changeset/gentle-bulldogs-turn.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`DoubleEndedQueue`: Custom errors replaced with native panic codes.
2 changes: 1 addition & 1 deletion .changeset/smart-bugs-switch.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
'openzeppelin-solidity': minor
---

`Math`: MathOverflowedMulDiv error was replaced with native panic codes.
`Math`: Custom errors replaced with native panic codes.
40 changes: 0 additions & 40 deletions contracts/mocks/_import.sol

This file was deleted.

2 changes: 1 addition & 1 deletion contracts/token/ERC1155/IERC1155.sol
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ interface IERC1155 is IERC165 {
*
* Requirements:
*
* - `operator` cannot be the caller.
* - `operator` cannot be the zero address.
*/
function setApprovalForAll(address operator, bool approved) external;

Expand Down
78 changes: 76 additions & 2 deletions contracts/utils/Arrays.sol
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,69 @@ import {Math} from "./math/Math.sol";
library Arrays {
using StorageSlot for bytes32;

/**
* @dev Sort an array (in memory) in increasing order.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
_quickSort(array, 0, array.length);
return array;
}

/**
* @dev Performs a quick sort on an array in memory. The array is sorted in increasing order.
*
* Invariant: `i <= j <= array.length`. This is the case when initially called by {sort} and is preserved in
* subcalls.
*/
function _quickSort(uint256[] memory array, uint256 i, uint256 j) private pure {
unchecked {
// Can't overflow given `i <= j`
if (j - i < 2) return;

// Use first element as pivot
uint256 pivot = unsafeMemoryAccess(array, i);
// Position where the pivot should be at the end of the loop
uint256 index = i;

for (uint256 k = i + 1; k < j; ++k) {
// Unsafe access is safe given `k < j <= array.length`.
if (unsafeMemoryAccess(array, k) < pivot) {
// If array[k] is smaller than the pivot, we increment the index and move array[k] there.
_swap(array, ++index, k);
}
}

// Swap pivot into place
_swap(array, i, index);

_quickSort(array, i, index); // Sort the left side of the pivot
_quickSort(array, index + 1, j); // Sort the right side of the pivot
}
}

/**
* @dev Swaps the elements at positions `i` and `j` in the `arr` array.
*/
function _swap(uint256[] memory arr, uint256 i, uint256 j) private pure {
assembly {
let start := add(arr, 0x20) // Pointer to the first element of the array
let pos_i := add(start, mul(i, 0x20))
let pos_j := add(start, mul(j, 0x20))
let val_i := mload(pos_i)
let val_j := mload(pos_j)
mstore(pos_i, val_j)
mstore(pos_j, val_i)
}
}

/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
Expand Down Expand Up @@ -238,7 +301,7 @@ library Arrays {
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
Expand All @@ -249,7 +312,18 @@ library Arrays {
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}

/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
Expand Down
2 changes: 1 addition & 1 deletion contracts/utils/Panic.sol
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ pragma solidity ^0.8.20;
* }
* ```
*
* Follows the list from libsolutil: https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*/
// slither-disable-next-line unused-state
library Panic {
Expand Down
3 changes: 3 additions & 0 deletions contracts/utils/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ Miscellaneous contracts and libraries containing utility functions you can use t
* {StorageSlot}: Methods for accessing specific storage slots formatted as common primitive types.
* {Multicall}: Abstract contract with an utility to allow batching together multiple calls in a single transaction. Useful for allowing EOAs to perform multiple operations at once.
* {Context}: An utility for abstracting the sender and calldata in the current execution context.
* {Panic}: A library to revert with https://docs.soliditylang.org/en/v0.8.20/control-structures.html#panic-via-assert-and-error-via-require[Solidity panic codes].

[NOTE]
====
Expand Down Expand Up @@ -106,3 +107,5 @@ Ethereum contracts have no native concept of an interface, so applications must
{{Multicall}}

{{Context}}

{{Panic}}
45 changes: 16 additions & 29 deletions contracts/utils/structs/DoubleEndedQueue.sol
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/DoubleEndedQueue.sol)
pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";

/**
* @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of
* the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and
Expand All @@ -15,21 +17,6 @@ pragma solidity ^0.8.20;
* ```
*/
library DoubleEndedQueue {
/**
* @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty.
*/
error QueueEmpty();

/**
* @dev A push operation couldn't be completed due to the queue being full.
*/
error QueueFull();

/**
* @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds.
*/
error QueueOutOfBounds();

/**
* @dev Indices are 128 bits so begin and end are packed in a single storage slot for efficient access.
*
Expand All @@ -48,12 +35,12 @@ library DoubleEndedQueue {
/**
* @dev Inserts an item at the end of the queue.
*
* Reverts with {QueueFull} if the queue is full.
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/
function pushBack(Bytes32Deque storage deque, bytes32 value) internal {
unchecked {
uint128 backIndex = deque._end;
if (backIndex + 1 == deque._begin) revert QueueFull();
if (backIndex + 1 == deque._begin) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[backIndex] = value;
deque._end = backIndex + 1;
}
Expand All @@ -62,12 +49,12 @@ library DoubleEndedQueue {
/**
* @dev Removes the item at the end of the queue and returns it.
*
* Reverts with {QueueEmpty} if the queue is empty.
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/
function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) {
unchecked {
uint128 backIndex = deque._end;
if (backIndex == deque._begin) revert QueueEmpty();
if (backIndex == deque._begin) Panic.panic(Panic.EMPTY_ARRAY_POP);
--backIndex;
value = deque._data[backIndex];
delete deque._data[backIndex];
Expand All @@ -78,12 +65,12 @@ library DoubleEndedQueue {
/**
* @dev Inserts an item at the beginning of the queue.
*
* Reverts with {QueueFull} if the queue is full.
* Reverts with {Panic-RESOURCE_ERROR} if the queue is full.
*/
function pushFront(Bytes32Deque storage deque, bytes32 value) internal {
unchecked {
uint128 frontIndex = deque._begin - 1;
if (frontIndex == deque._end) revert QueueFull();
if (frontIndex == deque._end) Panic.panic(Panic.RESOURCE_ERROR);
deque._data[frontIndex] = value;
deque._begin = frontIndex;
}
Expand All @@ -92,12 +79,12 @@ library DoubleEndedQueue {
/**
* @dev Removes the item at the beginning of the queue and returns it.
*
* Reverts with `QueueEmpty` if the queue is empty.
* Reverts with {Panic-EMPTY_ARRAY_POP} if the queue is empty.
*/
function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) {
unchecked {
uint128 frontIndex = deque._begin;
if (frontIndex == deque._end) revert QueueEmpty();
if (frontIndex == deque._end) Panic.panic(Panic.EMPTY_ARRAY_POP);
value = deque._data[frontIndex];
delete deque._data[frontIndex];
deque._begin = frontIndex + 1;
Expand All @@ -107,20 +94,20 @@ library DoubleEndedQueue {
/**
* @dev Returns the item at the beginning of the queue.
*
* Reverts with `QueueEmpty` if the queue is empty.
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/
function front(Bytes32Deque storage deque) internal view returns (bytes32 value) {
if (empty(deque)) revert QueueEmpty();
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
return deque._data[deque._begin];
}

/**
* @dev Returns the item at the end of the queue.
*
* Reverts with `QueueEmpty` if the queue is empty.
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the queue is empty.
*/
function back(Bytes32Deque storage deque) internal view returns (bytes32 value) {
if (empty(deque)) revert QueueEmpty();
if (empty(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
unchecked {
return deque._data[deque._end - 1];
}
Expand All @@ -130,10 +117,10 @@ library DoubleEndedQueue {
* @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at
* `length(deque) - 1`.
*
* Reverts with `QueueOutOfBounds` if the index is out of bounds.
* Reverts with {Panic-ARRAY_OUT_OF_BOUNDS} if the index is out of bounds.
*/
function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) {
if (index >= length(deque)) revert QueueOutOfBounds();
if (index >= length(deque)) Panic.panic(Panic.ARRAY_OUT_OF_BOUNDS);
// By construction, length is a uint128, so the check above ensures that index can be safely downcast to uint128
unchecked {
return deque._data[deque._begin + uint128(index)];
Expand Down
26 changes: 26 additions & 0 deletions docs/templates/contract.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,23 @@ import "@openzeppelin/{{__item_context.file.absolutePath}}";
--
{{/if}}

{{#if has-internal-variables}}
[.contract-index]
.Internal Variables
--
{{#each inheritance}}
{{#unless @first}}
[.contract-subindex-inherited]
.{{name}}
{{/unless}}
{{#each internal-variables}}
* {xref-{{anchor~}} }[`++{{typeDescriptions.typeString}} {{#if constant}}constant{{/if}} {{name}}++`]
{{/each}}

{{/each}}
--
{{/if}}

{{#each modifiers}}
[.contract-item]
[[{{anchor}}]]
Expand Down Expand Up @@ -109,3 +126,12 @@ import "@openzeppelin/{{__item_context.file.absolutePath}}";
{{{natspec.dev}}}

{{/each}}

{{#each internal-variables}}
[.contract-item]
[[{{anchor}}]]
==== `{{typeDescriptions.typeString}} [.contract-item-name]#++{{name}}++#` [.item-kind]#internal{{#if constant}} constant{{/if}}#

{{{natspec.dev}}}

{{/each}}
8 changes: 8 additions & 0 deletions docs/templates/properties.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,14 @@ module.exports['has-errors'] = function ({ item }) {
return item.inheritance.some(c => c.errors.length > 0);
};

module.exports['internal-variables'] = function ({ item }) {
return item.variables.filter(({ visibility }) => visibility === 'internal');
};

module.exports['has-internal-variables'] = function ({ item }) {
return module.exports['internal-variables']({ item }).length > 0;
};

module.exports.functions = function ({ item }) {
return [
...[...findAll('FunctionDefinition', item)].filter(f => f.visibility !== 'private'),
Expand Down
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit b0ad358

Please sign in to comment.