Strings.sol 16 KB

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