Strings.sol 14 KB

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