1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- // SPDX-License-Identifier: MIT
- pragma solidity >=0.6.0 <0.8.0;
- /**
- * @title SignedSafeMath
- * @dev Signed math operations with safety checks that revert on error.
- */
- library SignedSafeMath {
- int256 constant private _INT256_MIN = -2**255;
- /**
- * @dev Returns the multiplication of two signed integers, reverting on
- * overflow.
- *
- * Counterpart to Solidity's `*` operator.
- *
- * Requirements:
- *
- * - Multiplication cannot overflow.
- */
- function mul(int256 a, int256 b) internal pure returns (int256) {
- // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
- // benefit is lost if 'b' is also tested.
- // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
- if (a == 0) {
- return 0;
- }
- require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
- int256 c = a * b;
- require(c / a == b, "SignedSafeMath: multiplication overflow");
- return c;
- }
- /**
- * @dev Returns the integer division of two signed integers. Reverts on
- * division by zero. The result is rounded towards zero.
- *
- * Counterpart to Solidity's `/` operator. Note: this function uses a
- * `revert` opcode (which leaves remaining gas untouched) while Solidity
- * uses an invalid opcode to revert (consuming all remaining gas).
- *
- * Requirements:
- *
- * - The divisor cannot be zero.
- */
- function div(int256 a, int256 b) internal pure returns (int256) {
- require(b != 0, "SignedSafeMath: division by zero");
- require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
- int256 c = a / b;
- return c;
- }
- /**
- * @dev Returns the subtraction of two signed integers, reverting on
- * overflow.
- *
- * Counterpart to Solidity's `-` operator.
- *
- * Requirements:
- *
- * - Subtraction cannot overflow.
- */
- function sub(int256 a, int256 b) internal pure returns (int256) {
- int256 c = a - b;
- require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
- return c;
- }
- /**
- * @dev Returns the addition of two signed integers, reverting on
- * overflow.
- *
- * Counterpart to Solidity's `+` operator.
- *
- * Requirements:
- *
- * - Addition cannot overflow.
- */
- function add(int256 a, int256 b) internal pure returns (int256) {
- int256 c = a + b;
- require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
- return c;
- }
- }
|