Skip to content

Commit a5350ec

Browse files
authored
Add Strings.toHexString(bytes) (#5761)
1 parent fd9bbae commit a5350ec

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

.changeset/new-days-tease.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': minor
3+
---
4+
5+
`Strings`: Add `toHexString(bytes)`.

contracts/utils/Strings.sol

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,23 @@ library Strings {
128128
return string(buffer);
129129
}
130130

131+
/**
132+
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
133+
*/
134+
function toHexString(bytes memory input) internal pure returns (string memory) {
135+
unchecked {
136+
bytes memory buffer = new bytes(2 * input.length + 2);
137+
buffer[0] = "0";
138+
buffer[1] = "x";
139+
for (uint256 i = 0; i < input.length; ++i) {
140+
uint8 v = uint8(input[i]);
141+
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
142+
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
143+
}
144+
return string(buffer);
145+
}
146+
}
147+
131148
/**
132149
* @dev Returns true if the two strings are equal.
133150
*/

test/utils/Strings.test.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,17 @@ describe('Strings', function () {
186186
});
187187
});
188188

189+
describe('bytes', function () {
190+
describe('toHexString', function () {
191+
for (const length of [0, 17, 20, 32, 42, 64, 512]) {
192+
const input = ethers.hexlify(ethers.randomBytes(length));
193+
it(`hexlify buffer of length ${length}`, async function () {
194+
expect(await this.mock.getFunction('$toHexString(bytes)')(input)).to.equal(input);
195+
});
196+
}
197+
});
198+
});
199+
189200
describe('equal', function () {
190201
it('compares two empty strings', async function () {
191202
expect(await this.mock.$equal('', '')).to.be.true;

0 commit comments

Comments
 (0)