Skip to content

Add Strings.toHexString(bytes) #5761

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
5 changes: 5 additions & 0 deletions .changeset/new-days-tease.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'openzeppelin-solidity': minor
---

`Strings`: Add `toHexString(bytes)`.
17 changes: 17 additions & 0 deletions contracts/utils/Strings.sol
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,23 @@ library Strings {
return string(buffer);
}

/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}

/**
* @dev Returns true if the two strings are equal.
*/
Expand Down
11 changes: 11 additions & 0 deletions test/utils/Strings.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,17 @@ describe('Strings', function () {
});
});

describe('bytes', function () {
describe('toHexString', function () {
for (const length of [0, 17, 20, 32, 42, 64, 512]) {
const input = ethers.hexlify(ethers.randomBytes(length));
it(`hexlify buffer of length ${length}`, async function () {
expect(await this.mock.getFunction('$toHexString(bytes)')(input)).to.equal(input);
});
}
});
});

describe('equal', function () {
it('compares two empty strings', async function () {
expect(await this.mock.$equal('', '')).to.be.true;
Expand Down