67 lines
2.1 KiB
Solidity
67 lines
2.1 KiB
Solidity
|
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
|
||
|
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
|
||
|
|
||
|
pragma solidity ^0.5.8;
|
||
|
|
||
|
|
||
|
/**
|
||
|
* @title SafeMath64
|
||
|
* @dev Math operations for uint64 with safety checks that revert on error
|
||
|
*/
|
||
|
library SafeMath64 {
|
||
|
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
|
||
|
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
|
||
|
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
|
||
|
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
|
||
|
|
||
|
/**
|
||
|
* @dev Multiplies two numbers, reverts on overflow.
|
||
|
*/
|
||
|
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
|
||
|
uint256 c = uint256(_a) * uint256(_b);
|
||
|
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
|
||
|
|
||
|
return uint64(c);
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
|
||
|
*/
|
||
|
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
|
||
|
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
|
||
|
uint64 c = _a / _b;
|
||
|
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
|
||
|
|
||
|
return c;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
|
||
|
*/
|
||
|
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
|
||
|
require(_b <= _a, ERROR_SUB_UNDERFLOW);
|
||
|
uint64 c = _a - _b;
|
||
|
|
||
|
return c;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @dev Adds two numbers, reverts on overflow.
|
||
|
*/
|
||
|
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
|
||
|
uint64 c = _a + _b;
|
||
|
require(c >= _a, ERROR_ADD_OVERFLOW);
|
||
|
|
||
|
return c;
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
|
||
|
* reverts when dividing by zero.
|
||
|
*/
|
||
|
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
|
||
|
require(b != 0, ERROR_DIV_ZERO);
|
||
|
return a % b;
|
||
|
}
|
||
|
}
|