Strings.sol 2.7 KB

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