-
Notifications
You must be signed in to change notification settings - Fork 50
/
Copy pathCarefulMath.sol
77 lines (64 loc) · 1.91 KB
/
CarefulMath.sol
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
pragma solidity ^0.4.24;
import "./ErrorReporter.sol";
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath is ErrorReporter {
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mul(uint a, uint b) internal pure returns (Error, uint) {
if (a == 0) {
return (Error.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (Error.INTEGER_OVERFLOW, 0);
} else {
return (Error.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint a, uint b) internal pure returns (Error, uint) {
if (b == 0) {
return (Error.DIVISION_BY_ZERO, 0);
}
return (Error.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint a, uint b) internal pure returns (Error, uint) {
if (b <= a) {
return (Error.NO_ERROR, a - b);
} else {
return (Error.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function add(uint a, uint b) internal pure returns (Error, uint) {
uint c = a + b;
if (c >= a) {
return (Error.NO_ERROR, c);
} else {
return (Error.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSub(uint a, uint b, uint c) internal pure returns (Error, uint) {
(Error err0, uint sum) = add(a, b);
if (err0 != Error.NO_ERROR) {
return (err0, 0);
}
return sub(sum, c);
}
}