Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SignedMath with math utilities for signed integers #2686

Merged
merged 16 commits into from
Jan 12, 2022
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
* `ERC2771Context`: use immutable storage to store the forwarder address, no longer an issue since Solidity >=0.8.8 allows reading immutable variables in the constructor. ([#2917](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2917))
* `Base64`: add a library to parse bytes into base64 strings using `encode(bytes memory)` function, and provide examples to show how to use to build URL-safe `tokenURIs`. ([#2884](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#2884))
* `ERC20`: reduce allowance before triggering transfer. ([#3056](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/#3056))
* `SignedMath`: a new signed version of the Math library with `max`, `min`, `average`and `ceilDiv`. ([#2686](https://github.com/OpenZeppelin/openzeppelin-contracts/pull/2686))

## 4.4.1 (2021-12-14)

Expand Down
23 changes: 23 additions & 0 deletions contracts/mocks/SignedMathMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

import "../utils/math/SignedMath.sol";

contract SignedMathMock {
function max(int256 a, int256 b) public pure returns (int256) {
return SignedMath.max(a, b);
}

function min(int256 a, int256 b) public pure returns (int256) {
return SignedMath.min(a, b);
}

function average(int256 a, int256 b) public pure returns (int256) {
return SignedMath.average(a, b);
}

function ceilDiv(int256 a, int256 b) public pure returns (int256) {
return SignedMath.ceilDiv(a, b);
}
}
2 changes: 2 additions & 0 deletions contracts/utils/README.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ Finally, {Create2} contains all necessary utilities to safely use the https://bl

{{Math}}

{{SignedMath}}

{{SafeCast}}

{{SafeMath}}
Expand Down
44 changes: 44 additions & 0 deletions contracts/utils/math/SignedMath.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a >= b ? a : b;
}

/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}

/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}

/**
* @dev Returns the ceiling of the division of two signed numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
frangio marked this conversation as resolved.
Show resolved Hide resolved
*/
function ceilDiv(int256 a, int256 b) internal pure returns (int256) {
int256 z = a / b;
int256 r = a % b == 0 ? int256(0) : int256(1);
return z < 0 ? z - r : z + r;
}
}
126 changes: 126 additions & 0 deletions test/utils/math/SignedMath.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
const { BN, constants } = require('@openzeppelin/test-helpers');
const { expect } = require('chai');
const { MIN_INT256, MAX_INT256 } = constants;

const SignedMathMock = artifacts.require('SignedMathMock');

contract('SignedMath', function (accounts) {
const min = new BN('-1234');
const max = new BN('5678');

beforeEach(async function () {
this.math = await SignedMathMock.new();
});

describe('max', function () {
it('is correctly detected in first argument position', async function () {
expect(await this.math.max(max, min)).to.be.bignumber.equal(max);
});

it('is correctly detected in second argument position', async function () {
expect(await this.math.max(min, max)).to.be.bignumber.equal(max);
});
});

describe('min', function () {
it('is correctly detected in first argument position', async function () {
expect(await this.math.min(min, max)).to.be.bignumber.equal(min);
});

it('is correctly detected in second argument position', async function () {
expect(await this.math.min(max, min)).to.be.bignumber.equal(min);
});
});

describe('average', function () {
function bnAverage (a, b) {
return a.add(b).divn(2);
}

it('is correctly calculated with various input', async function () {
const valuesX = [
new BN('0'),
new BN('3'),
new BN('-3'),
new BN('4'),
new BN('-4'),
new BN('57417'),
new BN('-57417'),
new BN('42304'),
new BN('-42304'),
MIN_INT256,
MAX_INT256,
];

const valuesY = [
new BN('0'),
new BN('5'),
new BN('-5'),
new BN('2'),
new BN('-2'),
new BN('57417'),
new BN('-57417'),
new BN('42304'),
new BN('-42304'),
MIN_INT256,
MAX_INT256,
];

for (const x of valuesX) {
for (const y of valuesY) {
expect(await this.math.average(x, y))
.to.be.bignumber.equal(bnAverage(x, y), `Bad result for average(${x}, ${y})`);
}
}
});
});

describe('ceilDiv', function () {
it('does not round up on exact division, unsigned numbers', async function () {
const a = new BN('10');
const b = new BN('5');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('2');
});

it('does not round up on exact division, signed numbers', async function () {
const a = new BN('-10');
const b = new BN('-5');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('2');
});

it('does not round up on exact division', async function () {
const a = new BN('-10');
const b = new BN('5');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('-2');
});

it('rounds up on division with remainders, unsigned numbers', async function () {
const a = new BN('42');
const b = new BN('13');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('4');
});

it('rounds up on division with remainders signed numbers', async function () {
const a = new BN('-42');
const b = new BN('-13');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('4');
});

it('rounds up on division with remainders', async function () {
const a = new BN('-42');
const b = new BN('13');
expect(await this.math.ceilDiv(a, b)).to.be.bignumber.equal('-4');
});

it('does not overflow', async function () {
const b = new BN('2');
const result = new BN('1').shln(254);
expect(await this.math.ceilDiv(MAX_INT256, b)).to.be.bignumber.equal(result);
});

it('correctly computes max int256 divided by 1', async function () {
const b = new BN('1');
expect(await this.math.ceilDiv(MAX_INT256, b)).to.be.bignumber.equal(MAX_INT256);
});
});
});