Skip to content

Commit

Permalink
Merge 537c957 into a71c3bc
Browse files Browse the repository at this point in the history
  • Loading branch information
abcoathup committed May 27, 2019
2 parents a71c3bc + 537c957 commit 8ca7536
Show file tree
Hide file tree
Showing 3 changed files with 70 additions and 0 deletions.
38 changes: 38 additions & 0 deletions contracts/drafts/Strings.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
pragma solidity ^0.5.0;

/**
* @title Strings
* @dev String operations.
*/
library Strings {
/**
* Concatenates two strings.
* string(abi.encodePacked(a, b))
* https://solidity.readthedocs.io/en/latest/types.html?highlight=concatenate
*/

/**
* @dev Converts a uint256 to a string.
* via OraclizeAPI - MIT licence
* https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
*/
function fromUint256(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
9 changes: 9 additions & 0 deletions contracts/mocks/StringsMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pragma solidity ^0.5.0;

import "../drafts/Strings.sol";

contract StringsMock {
function fromUint256(uint256 value) public pure returns (string memory) {
return Strings.fromUint256(value);
}
}
23 changes: 23 additions & 0 deletions test/drafts/Strings.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { constants } = require('openzeppelin-test-helpers');

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

contract('Strings', function () {
beforeEach(async function () {
this.strings = await StringsMock.new();
});

describe('from uint256', function () {
it('converts 0', async function () {
(await this.strings.fromUint256(0)).should.equal('0');
});

it('converts a positive number', async function () {
(await this.strings.fromUint256(4132)).should.equal('4132');
});

it('converts MAX_UINT256', async function () {
(await this.strings.fromUint256(constants.MAX_UINT256)).should.equal(constants.MAX_UINT256.toString());
});
});
});

0 comments on commit 8ca7536

Please sign in to comment.