Strings.sol 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.2.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 _tryParseUintUncheckedBounds(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. if (end > bytes(input).length || begin > end) return (false, 0);
  156. return _tryParseUintUncheckedBounds(input, begin, end);
  157. }
  158. /**
  159. * @dev Implementation of {tryParseUint} that does not check bounds. Caller should make sure that
  160. * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
  161. */
  162. function _tryParseUintUncheckedBounds(
  163. string memory input,
  164. uint256 begin,
  165. uint256 end
  166. ) private pure returns (bool success, uint256 value) {
  167. bytes memory buffer = bytes(input);
  168. uint256 result = 0;
  169. for (uint256 i = begin; i < end; ++i) {
  170. uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
  171. if (chr > 9) return (false, 0);
  172. result *= 10;
  173. result += chr;
  174. }
  175. return (true, result);
  176. }
  177. /**
  178. * @dev Parse a decimal string and returns the value as a `int256`.
  179. *
  180. * Requirements:
  181. * - The string must be formatted as `[-+]?[0-9]*`
  182. * - The result must fit in an `int256` type.
  183. */
  184. function parseInt(string memory input) internal pure returns (int256) {
  185. return parseInt(input, 0, bytes(input).length);
  186. }
  187. /**
  188. * @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
  189. * `end` (excluded).
  190. *
  191. * Requirements:
  192. * - The substring must be formatted as `[-+]?[0-9]*`
  193. * - The result must fit in an `int256` type.
  194. */
  195. function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
  196. (bool success, int256 value) = tryParseInt(input, begin, end);
  197. if (!success) revert StringsInvalidChar();
  198. return value;
  199. }
  200. /**
  201. * @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
  202. * the result does not fit in a `int256`.
  203. *
  204. * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
  205. */
  206. function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
  207. return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
  208. }
  209. uint256 private constant ABS_MIN_INT256 = 2 ** 255;
  210. /**
  211. * @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
  212. * character or if the result does not fit in a `int256`.
  213. *
  214. * NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
  215. */
  216. function tryParseInt(
  217. string memory input,
  218. uint256 begin,
  219. uint256 end
  220. ) internal pure returns (bool success, int256 value) {
  221. if (end > bytes(input).length || begin > end) return (false, 0);
  222. return _tryParseIntUncheckedBounds(input, begin, end);
  223. }
  224. /**
  225. * @dev Implementation of {tryParseInt} that does not check bounds. Caller should make sure that
  226. * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
  227. */
  228. function _tryParseIntUncheckedBounds(
  229. string memory input,
  230. uint256 begin,
  231. uint256 end
  232. ) private pure returns (bool success, int256 value) {
  233. bytes memory buffer = bytes(input);
  234. // Check presence of a negative sign.
  235. bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
  236. bool positiveSign = sign == bytes1("+");
  237. bool negativeSign = sign == bytes1("-");
  238. uint256 offset = (positiveSign || negativeSign).toUint();
  239. (bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
  240. if (absSuccess && absValue < ABS_MIN_INT256) {
  241. return (true, negativeSign ? -int256(absValue) : int256(absValue));
  242. } else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
  243. return (true, type(int256).min);
  244. } else return (false, 0);
  245. }
  246. /**
  247. * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
  248. *
  249. * Requirements:
  250. * - The string must be formatted as `(0x)?[0-9a-fA-F]*`
  251. * - The result must fit in an `uint256` type.
  252. */
  253. function parseHexUint(string memory input) internal pure returns (uint256) {
  254. return parseHexUint(input, 0, bytes(input).length);
  255. }
  256. /**
  257. * @dev Variant of {parseHexUint} that parses a substring of `input` located between position `begin` (included) and
  258. * `end` (excluded).
  259. *
  260. * Requirements:
  261. * - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
  262. * - The result must fit in an `uint256` type.
  263. */
  264. function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
  265. (bool success, uint256 value) = tryParseHexUint(input, begin, end);
  266. if (!success) revert StringsInvalidChar();
  267. return value;
  268. }
  269. /**
  270. * @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
  271. *
  272. * NOTE: This function will revert if the result does not fit in a `uint256`.
  273. */
  274. function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
  275. return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
  276. }
  277. /**
  278. * @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
  279. * invalid character.
  280. *
  281. * NOTE: This function will revert if the result does not fit in a `uint256`.
  282. */
  283. function tryParseHexUint(
  284. string memory input,
  285. uint256 begin,
  286. uint256 end
  287. ) internal pure returns (bool success, uint256 value) {
  288. if (end > bytes(input).length || begin > end) return (false, 0);
  289. return _tryParseHexUintUncheckedBounds(input, begin, end);
  290. }
  291. /**
  292. * @dev Implementation of {tryParseHexUint} that does not check bounds. Caller should make sure that
  293. * `begin <= end <= input.length`. Other inputs would result in undefined behavior.
  294. */
  295. function _tryParseHexUintUncheckedBounds(
  296. string memory input,
  297. uint256 begin,
  298. uint256 end
  299. ) private pure returns (bool success, uint256 value) {
  300. bytes memory buffer = bytes(input);
  301. // skip 0x prefix if present
  302. bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
  303. uint256 offset = hasPrefix.toUint() * 2;
  304. uint256 result = 0;
  305. for (uint256 i = begin + offset; i < end; ++i) {
  306. uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
  307. if (chr > 15) return (false, 0);
  308. result *= 16;
  309. unchecked {
  310. // Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
  311. // This guaratees that adding a value < 16 will not cause an overflow, hence the unchecked.
  312. result += chr;
  313. }
  314. }
  315. return (true, result);
  316. }
  317. /**
  318. * @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
  319. *
  320. * Requirements:
  321. * - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
  322. */
  323. function parseAddress(string memory input) internal pure returns (address) {
  324. return parseAddress(input, 0, bytes(input).length);
  325. }
  326. /**
  327. * @dev Variant of {parseAddress} that parses a substring of `input` located between position `begin` (included) and
  328. * `end` (excluded).
  329. *
  330. * Requirements:
  331. * - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
  332. */
  333. function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
  334. (bool success, address value) = tryParseAddress(input, begin, end);
  335. if (!success) revert StringsInvalidAddressFormat();
  336. return value;
  337. }
  338. /**
  339. * @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
  340. * formatted address. See {parseAddress} requirements.
  341. */
  342. function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
  343. return tryParseAddress(input, 0, bytes(input).length);
  344. }
  345. /**
  346. * @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
  347. * formatted address. See {parseAddress} requirements.
  348. */
  349. function tryParseAddress(
  350. string memory input,
  351. uint256 begin,
  352. uint256 end
  353. ) internal pure returns (bool success, address value) {
  354. if (end > bytes(input).length || begin > end) return (false, address(0));
  355. bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
  356. uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
  357. // check that input is the correct length
  358. if (end - begin == expectedLength) {
  359. // length guarantees that this does not overflow, and value is at most type(uint160).max
  360. (bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
  361. return (s, address(uint160(v)));
  362. } else {
  363. return (false, address(0));
  364. }
  365. }
  366. function _tryParseChr(bytes1 chr) private pure returns (uint8) {
  367. uint8 value = uint8(chr);
  368. // Try to parse `chr`:
  369. // - Case 1: [0-9]
  370. // - Case 2: [a-f]
  371. // - Case 3: [A-F]
  372. // - otherwise not supported
  373. unchecked {
  374. if (value > 47 && value < 58) value -= 48;
  375. else if (value > 96 && value < 103) value -= 87;
  376. else if (value > 64 && value < 71) value -= 55;
  377. else return type(uint8).max;
  378. }
  379. return value;
  380. }
  381. /**
  382. * @dev Reads a bytes32 from a bytes array without bounds checking.
  383. *
  384. * NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
  385. * assembly block as such would prevent some optimizations.
  386. */
  387. function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
  388. // This is not memory safe in the general case, but all calls to this private function are within bounds.
  389. assembly ("memory-safe") {
  390. value := mload(add(buffer, add(0x20, offset)))
  391. }
  392. }
  393. }