1. 程式人生 > >Openzeppelin庫 02.Math庫詳解

Openzeppelin庫 02.Math庫詳解

1. SafeMath.sol: 安全運算

pragma solidity ^0.4.24;
 
 
/**
 * @title SafeMath
 * @dev Math operations with safety checks that throw on error
 */
 // 安全的數學運算庫
library SafeMath {
 
  /**
  * @dev Multiplies two numbers, throws on overflow.
  */
  
  function mul(uint256 _a, uint256 _b) internal pure returns
(uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { //優化gas消耗,節省gas return 0; } c = _a * _b; assert(c / _a == _b)
; // 安全檢查 return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); // 判斷 a 不能小於 b return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } }

2. Math.sol: uint256與uint64的最值獲取


pragma solidity ^0.4.24;
 
 
/**
 * @title Math
 * @dev Assorted math operations
 */
library Math {
  // 取最大值
  function max64(uint64 _a, uint64 _b) internal pure returns (uint64) {
    return _a >= _b ? _a : _b;
  }
  // 取最小值
  function min64(uint64 _a, uint64 _b) internal pure returns (uint64) {
    return _a < _b ? _a : _b; // 三目運算子
  }
 
  function max256(uint256 _a, uint256 _b) internal pure returns (uint256) {
    return _a >= _b ? _a : _b;
  }
 
  function min256(uint256 _a, uint256 _b) internal pure returns (uint256) {
    return _a < _b ? _a : _b;
  }
}