Skip to content

Instantly share code, notes, and snippets.

@wchargin
Created September 22, 2022 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wchargin/9aa9785acd9e4b506f95834bd8880c48 to your computer and use it in GitHub Desktop.
Save wchargin/9aa9785acd9e4b506f95834bd8880c48 to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.8;
/// @dev
/// An `OptionalUint` is either absent (the default, uninitialized value) or a
/// `uint256` from `0` through `type(uint256).max - 1`, inclusive. Note that an
/// `OptionalUint` cannot represent the max value of a `uint256`.
type OptionalUint is uint256;
/// @dev
/// Operations on `OptionalUint` values.
///
/// This library uses the terms `encode` and decode rather than the more
/// standard `wrap` and `unwrap` to avoid confusion with the built-in methods
/// on the `OptionalUint` user-defined value type.
library OptionalUints {
OptionalUint internal constant NONE = OptionalUint.wrap(0);
/// @dev Tests whether the given `OptionalUint` is present. If it is, call
/// `decode` to get its value.
function isPresent(OptionalUint ox) internal pure returns (bool) {
return OptionalUint.unwrap(ox) != 0;
}
/// @dev Encodes a `uint256` as an `OptionalUint` that is present with the
/// given value, which must be at most `type(uint256).max - 1`. It always
/// holds that `OptionalUints.encode(x).decode() == x`.
function encode(uint256 x) internal pure returns (OptionalUint) {
return OptionalUint.wrap(x + 1);
}
/// @dev Decodes a `uint256` that is known to be present. If `ox` is not
/// actually present, execution reverts. See `isPresent`.
function decode(OptionalUint ox) internal pure returns (uint256 x) {
return OptionalUint.unwrap(ox) - 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment