Strings.sol 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v4.8.0-rc.0) (utils/Strings.sol)
  3. pragma solidity ^0.8.0;
  4. import "./math/Math.sol";
  5. /**
  6. * @dev String operations.
  7. */
  8. library Strings {
  9. bytes16 private constant _SYMBOLS = "0123456789abcdef";
  10. uint8 private constant _ADDRESS_LENGTH = 20;
  11. /**
  12. * @dev Converts a `uint256` to its ASCII `string` decimal representation.
  13. */
  14. function toString(uint256 value) internal pure returns (string memory) {
  15. unchecked {
  16. uint256 length = Math.log10(value) + 1;
  17. string memory buffer = new string(length);
  18. uint256 ptr;
  19. /// @solidity memory-safe-assembly
  20. assembly {
  21. ptr := add(buffer, add(32, length))
  22. }
  23. while (true) {
  24. ptr--;
  25. /// @solidity memory-safe-assembly
  26. assembly {
  27. mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
  28. }
  29. value /= 10;
  30. if (value == 0) break;
  31. }
  32. return buffer;
  33. }
  34. }
  35. /**
  36. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
  37. */
  38. function toHexString(uint256 value) internal pure returns (string memory) {
  39. unchecked {
  40. return toHexString(value, Math.log256(value) + 1);
  41. }
  42. }
  43. /**
  44. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
  45. */
  46. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
  47. bytes memory buffer = new bytes(2 * length + 2);
  48. buffer[0] = "0";
  49. buffer[1] = "x";
  50. for (uint256 i = 2 * length + 1; i > 1; --i) {
  51. buffer[i] = _SYMBOLS[value & 0xf];
  52. value >>= 4;
  53. }
  54. require(value == 0, "Strings: hex length insufficient");
  55. return string(buffer);
  56. }
  57. /**
  58. * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
  59. */
  60. function toHexString(address addr) internal pure returns (string memory) {
  61. return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
  62. }
  63. }