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

Optimize toString #3573

Merged
merged 18 commits into from
Aug 31, 2022
15 changes: 8 additions & 7 deletions contracts/utils/Strings.sol
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ pragma solidity ^0.8.0;
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
bytes16 private constant _SYMBOLS = "0123456789abcdef";
frangio marked this conversation as resolved.
Show resolved Hide resolved
uint8 private constant _ADDRESS_LENGTH = 20;

/**
Expand Down Expand Up @@ -51,17 +51,18 @@ library Strings {
string memory buffer = new string(length);
/// @solidity memory-safe-assembly
assembly {
let pos := add(buffer, 32)
let ptr := add(pos, length)

let ptr := add(buffer, add(32, length))
for {

} gt(ptr, pos) {
} 1 {

} {
ptr := sub(ptr, 1)
mstore8(ptr, add(48, mod(value, 10)))
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
frangio marked this conversation as resolved.
Show resolved Hide resolved
value := div(value, 10)
if iszero(value) {
frangio marked this conversation as resolved.
Show resolved Hide resolved
break
}
}
}
return buffer;
Expand Down Expand Up @@ -111,7 +112,7 @@ library Strings {
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
Comment on lines 112 to 115
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This could be written in the same or similar way that the decimal toString.

require(value == 0, "Strings: hex length insufficient");
Expand Down