Skip to content

Instantly share code, notes, and snippets.

@ngmachado
Created March 7, 2022 13:38
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 ngmachado/0d185aea83f596e785c03842644cbfd8 to your computer and use it in GitHub Desktop.
Save ngmachado/0d185aea83f596e785c03842644cbfd8 to your computer and use it in GitHub Desktop.
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0 <0.9.0;
library SafeCast96 {
/**
* @dev Returns the downcasted int96 from uint256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
*/
function toInt96(uint256 value) internal pure returns (int96) {
require(value <= uint256(int256(type(int96).max)), "SafeCast96: value doesn't fit in 96 bits");
return int96(int256(value));
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
*/
function toInt96(int256 value) internal pure returns (int96) {
require(value >= type(int96).min && value <= type(int96).max, "SafeCast96: value doesn't fit in 96 bits");
return int96(value);
}
/**
* @dev Returns the downcasted int96 from uint128, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
*/
function toInt96(uint128 value) internal pure returns (int96) {
require(value <= uint128(int128(type(int96).max)), "SafeCast96: value doesn't fit in 96 bits");
return int96(int128(value));
}
/**
* @dev Returns the downcasted int96 from int128, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
*/
function toInt96(int128 value) internal pure returns (int96) {
require(value >= type(int96).min && value <= type(int96).max, "SafeCast96: value doesn't fit in 96 bits");
return int96(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment