SafeMath

有安全检查的数学操作函数

pragma solidity ^0.4.11;


library SafeMath {
  function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
  }

  function div(uint256 a, uint256 b) internal constant 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 c;
  }

  function sub(uint256 a, uint256 b) internal constant returns (uint256) {
    assert(b <= a);
    return a - b;
  }

  function add(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a + b;
    assert(c >= a);
    return c;
  }
}

 

assert(bool assertion) internal

用来检查合约的要计算的数学表达式。如果传入的参数值为false,将抛出异常。这个方法现在是Solidity的标准语法了。

mul(uint256 a, uint256 b) internal returns (uint256)

两个无符号整数的乘法。默认检查了结果是否有溢出。

function mul(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a * b;
    assert(a == 0 || c / a == b);
    return c;
}

sub(uint256 a, uint256 b) internal returns (uint256)

检查了参数b不能大于参数a

function sub(uint256 a, uint256 b) internal constant returns (uint256) {
    assert(b <= a);
    return a - b;
}

add(uint256 a, uint256 b) internal returns (uint256)

检查添加后的结果要大于ab

function add(uint256 a, uint256 b) internal constant returns (uint256) {
    uint256 c = a + b;
    assert(c >= a);
    return c;
}

 

发表评论

后才能评论