Strings.sol 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
  3. pragma solidity ^0.8.20;
  4. import {Math} from "./math/Math.sol";
  5. import {SafeCast} from "./math/SafeCast.sol";
  6. import {SignedMath} from "./math/SignedMath.sol";
  7. /**
  8. * @dev String operations.
  9. */
  10. library Strings {
  11. using SafeCast for *;
  12. bytes16 private constant HEX_DIGITS = "0123456789abcdef";
  13. uint8 private constant ADDRESS_LENGTH = 20;
  14. /**
  15. * @dev The `value` string doesn't fit in the specified `length`.
  16. */
  17. error StringsInsufficientHexLength(uint256 value, uint256 length);
  18. /**
  19. * @dev The string being parsed contains characters that are not in scope of the given base.
  20. */
  21. error StringsInvalidChar();
  22. /**
  23. * @dev The string being parsed is not a properly formatted address.
  24. */
  25. error StringsInvalidAddressFormat();
  26. /**
  27. * @dev Converts a `uint256` to its ASCII `string` decimal representation.
  28. */
  29. function toString(uint256 value) internal pure returns (string memory) {
  30. unchecked {
  31. uint256 length = Math.log10(value) + 1;
  32. string memory buffer = new string(length);
  33. uint256 ptr;
  34. assembly ("memory-safe") {
  35. ptr := add(buffer, add(32, length))
  36. }
  37. while (true) {
  38. ptr--;
  39. assembly ("memory-safe") {
  40. mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
  41. }
  42. value /= 10;
  43. if (value == 0) break;
  44. }
  45. return buffer;
  46. }
  47. }
  48. /**
  49. * @dev Converts a `int256` to its ASCII `string` decimal representation.
  50. */
  51. function toStringSigned(int256 value) internal pure returns (string memory) {
  52. return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
  53. }
  54. /**
  55. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
  56. */
  57. function toHexString(uint256 value) internal pure returns (string memory) {
  58. unchecked {
  59. return toHexString(value, Math.log256(value) + 1);
  60. }
  61. }
  62. /**
  63. * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
  64. */
  65. function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
  66. uint256 localValue = value;
  67. bytes memory buffer = new bytes(2 * length + 2);
  68. buffer[0] = "0";
  69. buffer[1] = "x";
  70. for (uint256 i = 2 * length + 1; i > 1; --i) {
  71. buffer[i] = HEX_DIGITS[localValue & 0xf];
  72. localValue >>= 4;
  73. }
  74. if (localValue != 0) {
  75. revert StringsInsufficientHexLength(value, length);
  76. }
  77. return string(buffer);
  78. }
  79. /**
  80. * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
  81. * representation.
  82. */
  83. function toHexString(address addr) internal pure returns (string memory) {
  84. return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
  85. }
  86. /**
  87. * @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
  88. * representation, according to EIP-55.
  89. */
  90. function toChecksumHexString(address addr) internal pure returns (string memory) {
  91. bytes memory buffer = bytes(toHexString(addr));
  92. // hash the hex part of buffer (skip length + 2 bytes, length 40)
  93. uint256 hashValue;
  94. assembly ("memory-safe") {
  95. hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
  96. }
  97. for (uint256 i = 41; i > 1; --i) {
  98. // possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
  99. if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
  100. // case shift by xoring with 0x20
  101. buffer[i] ^= 0x20;
  102. }
  103. hashValue >>= 4;
  104. }
  105. return string(buffer);
  106. }
  107. /**
  108. * @dev Returns true if the two strings are equal.
  109. */
  110. function equal(string memory a, string memory b) internal pure returns (bool) {
  111. return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
  112. }
  113. /**
  114. * @dev Parse a decimal string and returns the value as a `uint256`.
  115. *
  116. * Requirements:
  117. * - The string must be formatted as `[0-9]*`
  118. * - The result must fit into an `uint256` type
  119. */
  120. function parseUint(string memory input) internal pure returns (uint256) {
  121. return parseUint(input, 0, bytes(input).length);
  122. }
  123. /**
  124. * @dev Variant of {parseUint} that parses a substring of `input` located between position `begin` (included) and
  125. * `end` (excluded).
  126. *
  127. * Requirements:
  128. * - The substring must be formatted as `[0-9]*`
  129. * - The result must fit into an `uint256` type
  130. */
  131. function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
  132. (bool success, uint256 value) = tryParseUint(input, begin, end);
  133. if (!success) revert StringsInvalidChar();
  134. return value;
  135. }
  136. /**
  137. * @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
  138. *
  139. * NOTE: This function will revert if the result does not fit in a `uint256`.
  140. */
  141. function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
  142. return tryParseUint(input, 0, bytes(input).length);
  143. }
  144. /**
  145. * @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
  146. * character.
  147. *
  148. * NOTE: This function will revert if the result does not fit in a `uint256`.
  149. */
  150. function tryParseUint(
  151. string memory input,
  152. uint256 begin,
  153. uint256 end
  154. ) internal pure returns (bool success, uint256 value) {
  155. bytes memory buffer = bytes(input);
  156. uint256 result = 0;
  157. if (begin >= end) return (false, 0);
  158. for (uint256 i = begin; i < end; ++i) {
  159. uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
  160. if (chr > 9) return (false, 0);
  161. result *= 10;
  162. result += chr;
  163. }
  164. return (true, result);
  165. }
  166. /**
  167. * @dev Parse a decimal string and returns the value as a `int256`.
  168. *
  169. * Requirements:
  170. * - The string must be formatted as `[-+]?[0-9]*`
  171. * - The result must fit in an `int256` type.
  172. */
  173. function parseInt(string memory input) internal pure returns (int256) {
  174. return parseInt(input, 0, bytes(input).length);
  175. }
  176. /**
  177. * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
  178. * `end` (excluded).
  179. *
  180. * Requirements:
  181. * - The substring must be formatted as `[-+]?[0-9]*`
  182. * - The result must fit in an `int256` type.
  183. */
  184. function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
  185. (bool success, int256 value) = tryParseInt(input, begin, end);
  186. if (!success) revert StringsInvalidChar();
  187. return value;
  188. }
  189. /**
  190. * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
  191. * the result does not fit in a `int256`.
  192. *
  193. * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
  194. */
  195. function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
  196. return tryParseInt(input, 0, bytes(input).length);
  197. }
  198. uint256 private constant ABS_MIN_INT256 = 2 ** 255;
  199. /**
  200. * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
  201. * character or if the result does not fit in a `int256`.
  202. *
  203. * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
  204. */
  205. function tryParseInt(
  206. string memory input,
  207. uint256 begin,
  208. uint256 end
  209. ) internal pure returns (bool success, int256 value) {
  210. bytes memory buffer = bytes(input);
  211. // Check presence of a negative sign.
  212. bytes1 sign = bytes1(_unsafeReadBytesOffset(buffer, begin));
  213. bool positiveSign = sign == bytes1("+");
  214. bool negativeSign = sign == bytes1("-");
  215. uint256 offset = (positiveSign || negativeSign).toUint();
  216. (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
  217. if (absSuccess && absValue < ABS_MIN_INT256) {
  218. return (true, negativeSign ? -int256(absValue) : int256(absValue));
  219. } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
  220. return (true, type(int256).min);
  221. } else return (false, 0);
  222. }
  223. /**
  224. * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
  225. *
  226. * Requirements:
  227. * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
  228. * - The result must fit in an `uint256` type.
  229. */
  230. function parseHexUint(string memory input) internal pure returns (uint256) {
  231. return parseHexUint(input, 0, bytes(input).length);
  232. }
  233. /**
  234. * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
  235. * `end` (excluded).
  236. *
  237. * Requirements:
  238. * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
  239. * - The result must fit in an `uint256` type.
  240. */
  241. function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
  242. (bool success, uint256 value) = tryParseHexUint(input, begin, end);
  243. if (!success) revert StringsInvalidChar();
  244. return value;
  245. }
  246. /**
  247. * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
  248. *
  249. * NOTE: This function will revert if the result does not fit in a `uint256`.
  250. */
  251. function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
  252. return tryParseHexUint(input, 0, bytes(input).length);
  253. }
  254. /**
  255. * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
  256. * invalid character.
  257. *
  258. * NOTE: This function will revert if the result does not fit in a `uint256`.
  259. */
  260. function tryParseHexUint(
  261. string memory input,
  262. uint256 begin,
  263. uint256 end
  264. ) internal pure returns (bool success, uint256 value) {
  265. bytes memory buffer = bytes(input);
  266. // skip 0x prefix if present
  267. bool hasPrefix = bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x");
  268. uint256 offset = hasPrefix.toUint() * 2;
  269. uint256 result = 0;
  270. for (uint256 i = begin + offset; i < end; ++i) {
  271. uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
  272. if (chr > 15) return (false, 0);
  273. result *= 16;
  274. unchecked {
  275. // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
  276. // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
  277. result += chr;
  278. }
  279. }
  280. return (true, result);
  281. }
  282. /**
  283. * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
  284. *
  285. * Requirements:
  286. * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
  287. */
  288. function parseAddress(string memory input) internal pure returns (address) {
  289. return parseAddress(input, 0, bytes(input).length);
  290. }
  291. /**
  292. * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
  293. * `end` (excluded).
  294. *
  295. * Requirements:
  296. * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
  297. */
  298. function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
  299. (bool success, address value) = tryParseAddress(input, begin, end);
  300. if (!success) revert StringsInvalidAddressFormat();
  301. return value;
  302. }
  303. /**
  304. * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
  305. * formatted address. See {parseAddress} requirements.
  306. */
  307. function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
  308. return tryParseAddress(input, 0, bytes(input).length);
  309. }
  310. /**
  311. * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
  312. * formatted address. See {parseAddress} requirements.
  313. */
  314. function tryParseAddress(
  315. string memory input,
  316. uint256 begin,
  317. uint256 end
  318. ) internal pure returns (bool success, address value) {
  319. // check that input is the correct length
  320. bool hasPrefix = bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x");
  321. uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
  322. if (end - begin == expectedLength && end < bytes(input).length) {
  323. // length guarantees that this does not overflow, and value is at most type(uint160).max
  324. (bool s, uint256 v) = tryParseHexUint(input, begin, end);
  325. return (s, address(uint160(v)));
  326. } else {
  327. return (false, address(0));
  328. }
  329. }
  330. function _tryParseChr(bytes1 chr) private pure returns (uint8) {
  331. uint8 value = uint8(chr);
  332. // Try to parse `chr`:
  333. // - Case 1: [0-9]
  334. // - Case 2: [a-f]
  335. // - Case 3: [A-F]
  336. // - otherwise not supported
  337. unchecked {
  338. if (value > 47 && value < 58) value -= 48;
  339. else if (value > 96 && value < 103) value -= 87;
  340. else if (value > 64 && value < 71) value -= 55;
  341. else return type(uint8).max;
  342. }
  343. return value;
  344. }
  345. /**
  346. * @dev Reads a bytes32 from a bytes array without bounds checking.
  347. *
  348. * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
  349. * assembly block as such would prevent some optimizations.
  350. */
  351. function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
  352. // This is not memory safe in the general case, but all calls to this private function are within bounds.
  353. assembly ("memory-safe") {
  354. value := mload(add(buffer, add(0x20, offset)))
  355. }
  356. }
  357. }