charconv_parse.cc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "y_absl/strings/internal/charconv_parse.h"
  15. #include "y_absl/strings/charconv.h"
  16. #include <cassert>
  17. #include <cstdint>
  18. #include <limits>
  19. #include "y_absl/strings/internal/memutil.h"
  20. namespace y_absl {
  21. Y_ABSL_NAMESPACE_BEGIN
  22. namespace {
  23. // ParseFloat<10> will read the first 19 significant digits of the mantissa.
  24. // This number was chosen for multiple reasons.
  25. //
  26. // (a) First, for whatever integer type we choose to represent the mantissa, we
  27. // want to choose the largest possible number of decimal digits for that integer
  28. // type. We are using uint64_t, which can express any 19-digit unsigned
  29. // integer.
  30. //
  31. // (b) Second, we need to parse enough digits that the binary value of any
  32. // mantissa we capture has more bits of resolution than the mantissa
  33. // representation in the target float. Our algorithm requires at least 3 bits
  34. // of headway, but 19 decimal digits give a little more than that.
  35. //
  36. // The following static assertions verify the above comments:
  37. constexpr int kDecimalMantissaDigitsMax = 19;
  38. static_assert(std::numeric_limits<uint64_t>::digits10 ==
  39. kDecimalMantissaDigitsMax,
  40. "(a) above");
  41. // IEEE doubles, which we assume in Abseil, have 53 binary bits of mantissa.
  42. static_assert(std::numeric_limits<double>::is_iec559, "IEEE double assumed");
  43. static_assert(std::numeric_limits<double>::radix == 2, "IEEE double fact");
  44. static_assert(std::numeric_limits<double>::digits == 53, "IEEE double fact");
  45. // The lowest valued 19-digit decimal mantissa we can read still contains
  46. // sufficient information to reconstruct a binary mantissa.
  47. static_assert(1000000000000000000u > (uint64_t{1} << (53 + 3)), "(b) above");
  48. // ParseFloat<16> will read the first 15 significant digits of the mantissa.
  49. //
  50. // Because a base-16-to-base-2 conversion can be done exactly, we do not need
  51. // to maximize the number of scanned hex digits to improve our conversion. What
  52. // is required is to scan two more bits than the mantissa can represent, so that
  53. // we always round correctly.
  54. //
  55. // (One extra bit does not suffice to perform correct rounding, since a number
  56. // exactly halfway between two representable floats has unique rounding rules,
  57. // so we need to differentiate between a "halfway between" number and a "closer
  58. // to the larger value" number.)
  59. constexpr int kHexadecimalMantissaDigitsMax = 15;
  60. // The minimum number of significant bits that will be read from
  61. // kHexadecimalMantissaDigitsMax hex digits. We must subtract by three, since
  62. // the most significant digit can be a "1", which only contributes a single
  63. // significant bit.
  64. constexpr int kGuaranteedHexadecimalMantissaBitPrecision =
  65. 4 * kHexadecimalMantissaDigitsMax - 3;
  66. static_assert(kGuaranteedHexadecimalMantissaBitPrecision >
  67. std::numeric_limits<double>::digits + 2,
  68. "kHexadecimalMantissaDigitsMax too small");
  69. // We also impose a limit on the number of significant digits we will read from
  70. // an exponent, to avoid having to deal with integer overflow. We use 9 for
  71. // this purpose.
  72. //
  73. // If we read a 9 digit exponent, the end result of the conversion will
  74. // necessarily be infinity or zero, depending on the sign of the exponent.
  75. // Therefore we can just drop extra digits on the floor without any extra
  76. // logic.
  77. constexpr int kDecimalExponentDigitsMax = 9;
  78. static_assert(std::numeric_limits<int>::digits10 >= kDecimalExponentDigitsMax,
  79. "int type too small");
  80. // To avoid incredibly large inputs causing integer overflow for our exponent,
  81. // we impose an arbitrary but very large limit on the number of significant
  82. // digits we will accept. The implementation refuses to match a string with
  83. // more consecutive significant mantissa digits than this.
  84. constexpr int kDecimalDigitLimit = 50000000;
  85. // Corresponding limit for hexadecimal digit inputs. This is one fourth the
  86. // amount of kDecimalDigitLimit, since each dropped hexadecimal digit requires
  87. // a binary exponent adjustment of 4.
  88. constexpr int kHexadecimalDigitLimit = kDecimalDigitLimit / 4;
  89. // The largest exponent we can read is 999999999 (per
  90. // kDecimalExponentDigitsMax), and the largest exponent adjustment we can get
  91. // from dropped mantissa digits is 2 * kDecimalDigitLimit, and the sum of these
  92. // comfortably fits in an integer.
  93. //
  94. // We count kDecimalDigitLimit twice because there are independent limits for
  95. // numbers before and after the decimal point. (In the case where there are no
  96. // significant digits before the decimal point, there are independent limits for
  97. // post-decimal-point leading zeroes and for significant digits.)
  98. static_assert(999999999 + 2 * kDecimalDigitLimit <
  99. std::numeric_limits<int>::max(),
  100. "int type too small");
  101. static_assert(999999999 + 2 * (4 * kHexadecimalDigitLimit) <
  102. std::numeric_limits<int>::max(),
  103. "int type too small");
  104. // Returns true if the provided bitfield allows parsing an exponent value
  105. // (e.g., "1.5e100").
  106. bool AllowExponent(chars_format flags) {
  107. bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
  108. bool scientific =
  109. (flags & chars_format::scientific) == chars_format::scientific;
  110. return scientific || !fixed;
  111. }
  112. // Returns true if the provided bitfield requires an exponent value be present.
  113. bool RequireExponent(chars_format flags) {
  114. bool fixed = (flags & chars_format::fixed) == chars_format::fixed;
  115. bool scientific =
  116. (flags & chars_format::scientific) == chars_format::scientific;
  117. return scientific && !fixed;
  118. }
  119. const int8_t kAsciiToInt[256] = {
  120. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  121. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  122. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8,
  123. 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1,
  124. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  125. -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  126. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  127. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  128. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  129. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  130. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  131. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  132. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  133. -1, -1, -1, -1, -1, -1, -1, -1, -1};
  134. // Returns true if `ch` is a digit in the given base
  135. template <int base>
  136. bool IsDigit(char ch);
  137. // Converts a valid `ch` to its digit value in the given base.
  138. template <int base>
  139. unsigned ToDigit(char ch);
  140. // Returns true if `ch` is the exponent delimiter for the given base.
  141. template <int base>
  142. bool IsExponentCharacter(char ch);
  143. // Returns the maximum number of significant digits we will read for a float
  144. // in the given base.
  145. template <int base>
  146. constexpr int MantissaDigitsMax();
  147. // Returns the largest consecutive run of digits we will accept when parsing a
  148. // number in the given base.
  149. template <int base>
  150. constexpr int DigitLimit();
  151. // Returns the amount the exponent must be adjusted by for each dropped digit.
  152. // (For decimal this is 1, since the digits are in base 10 and the exponent base
  153. // is also 10, but for hexadecimal this is 4, since the digits are base 16 but
  154. // the exponent base is 2.)
  155. template <int base>
  156. constexpr int DigitMagnitude();
  157. template <>
  158. bool IsDigit<10>(char ch) {
  159. return ch >= '0' && ch <= '9';
  160. }
  161. template <>
  162. bool IsDigit<16>(char ch) {
  163. return kAsciiToInt[static_cast<unsigned char>(ch)] >= 0;
  164. }
  165. template <>
  166. unsigned ToDigit<10>(char ch) {
  167. return static_cast<unsigned>(ch - '0');
  168. }
  169. template <>
  170. unsigned ToDigit<16>(char ch) {
  171. return static_cast<unsigned>(kAsciiToInt[static_cast<unsigned char>(ch)]);
  172. }
  173. template <>
  174. bool IsExponentCharacter<10>(char ch) {
  175. return ch == 'e' || ch == 'E';
  176. }
  177. template <>
  178. bool IsExponentCharacter<16>(char ch) {
  179. return ch == 'p' || ch == 'P';
  180. }
  181. template <>
  182. constexpr int MantissaDigitsMax<10>() {
  183. return kDecimalMantissaDigitsMax;
  184. }
  185. template <>
  186. constexpr int MantissaDigitsMax<16>() {
  187. return kHexadecimalMantissaDigitsMax;
  188. }
  189. template <>
  190. constexpr int DigitLimit<10>() {
  191. return kDecimalDigitLimit;
  192. }
  193. template <>
  194. constexpr int DigitLimit<16>() {
  195. return kHexadecimalDigitLimit;
  196. }
  197. template <>
  198. constexpr int DigitMagnitude<10>() {
  199. return 1;
  200. }
  201. template <>
  202. constexpr int DigitMagnitude<16>() {
  203. return 4;
  204. }
  205. // Reads decimal digits from [begin, end) into *out. Returns the number of
  206. // digits consumed.
  207. //
  208. // After max_digits has been read, keeps consuming characters, but no longer
  209. // adjusts *out. If a nonzero digit is dropped this way, *dropped_nonzero_digit
  210. // is set; otherwise, it is left unmodified.
  211. //
  212. // If no digits are matched, returns 0 and leaves *out unchanged.
  213. //
  214. // ConsumeDigits does not protect against overflow on *out; max_digits must
  215. // be chosen with respect to type T to avoid the possibility of overflow.
  216. template <int base, typename T>
  217. int ConsumeDigits(const char* begin, const char* end, int max_digits, T* out,
  218. bool* dropped_nonzero_digit) {
  219. if (base == 10) {
  220. assert(max_digits <= std::numeric_limits<T>::digits10);
  221. } else if (base == 16) {
  222. assert(max_digits * 4 <= std::numeric_limits<T>::digits);
  223. }
  224. const char* const original_begin = begin;
  225. // Skip leading zeros, but only if *out is zero.
  226. // They don't cause an overflow so we don't have to count them for
  227. // `max_digits`.
  228. while (!*out && end != begin && *begin == '0') ++begin;
  229. T accumulator = *out;
  230. const char* significant_digits_end =
  231. (end - begin > max_digits) ? begin + max_digits : end;
  232. while (begin < significant_digits_end && IsDigit<base>(*begin)) {
  233. // Do not guard against *out overflow; max_digits was chosen to avoid this.
  234. // Do assert against it, to detect problems in debug builds.
  235. auto digit = static_cast<T>(ToDigit<base>(*begin));
  236. assert(accumulator * base >= accumulator);
  237. accumulator *= base;
  238. assert(accumulator + digit >= accumulator);
  239. accumulator += digit;
  240. ++begin;
  241. }
  242. bool dropped_nonzero = false;
  243. while (begin < end && IsDigit<base>(*begin)) {
  244. dropped_nonzero = dropped_nonzero || (*begin != '0');
  245. ++begin;
  246. }
  247. if (dropped_nonzero && dropped_nonzero_digit != nullptr) {
  248. *dropped_nonzero_digit = true;
  249. }
  250. *out = accumulator;
  251. return static_cast<int>(begin - original_begin);
  252. }
  253. // Returns true if `v` is one of the chars allowed inside parentheses following
  254. // a NaN.
  255. bool IsNanChar(char v) {
  256. return (v == '_') || (v >= '0' && v <= '9') || (v >= 'a' && v <= 'z') ||
  257. (v >= 'A' && v <= 'Z');
  258. }
  259. // Checks the range [begin, end) for a strtod()-formatted infinity or NaN. If
  260. // one is found, sets `out` appropriately and returns true.
  261. bool ParseInfinityOrNan(const char* begin, const char* end,
  262. strings_internal::ParsedFloat* out) {
  263. if (end - begin < 3) {
  264. return false;
  265. }
  266. switch (*begin) {
  267. case 'i':
  268. case 'I': {
  269. // An infinity string consists of the characters "inf" or "infinity",
  270. // case insensitive.
  271. if (strings_internal::memcasecmp(begin + 1, "nf", 2) != 0) {
  272. return false;
  273. }
  274. out->type = strings_internal::FloatType::kInfinity;
  275. if (end - begin >= 8 &&
  276. strings_internal::memcasecmp(begin + 3, "inity", 5) == 0) {
  277. out->end = begin + 8;
  278. } else {
  279. out->end = begin + 3;
  280. }
  281. return true;
  282. }
  283. case 'n':
  284. case 'N': {
  285. // A NaN consists of the characters "nan", case insensitive, optionally
  286. // followed by a parenthesized sequence of zero or more alphanumeric
  287. // characters and/or underscores.
  288. if (strings_internal::memcasecmp(begin + 1, "an", 2) != 0) {
  289. return false;
  290. }
  291. out->type = strings_internal::FloatType::kNan;
  292. out->end = begin + 3;
  293. // NaN is allowed to be followed by a parenthesized string, consisting of
  294. // only the characters [a-zA-Z0-9_]. Match that if it's present.
  295. begin += 3;
  296. if (begin < end && *begin == '(') {
  297. const char* nan_begin = begin + 1;
  298. while (nan_begin < end && IsNanChar(*nan_begin)) {
  299. ++nan_begin;
  300. }
  301. if (nan_begin < end && *nan_begin == ')') {
  302. // We found an extra NaN specifier range
  303. out->subrange_begin = begin + 1;
  304. out->subrange_end = nan_begin;
  305. out->end = nan_begin + 1;
  306. }
  307. }
  308. return true;
  309. }
  310. default:
  311. return false;
  312. }
  313. }
  314. } // namespace
  315. namespace strings_internal {
  316. template <int base>
  317. strings_internal::ParsedFloat ParseFloat(const char* begin, const char* end,
  318. chars_format format_flags) {
  319. strings_internal::ParsedFloat result;
  320. // Exit early if we're given an empty range.
  321. if (begin == end) return result;
  322. // Handle the infinity and NaN cases.
  323. if (ParseInfinityOrNan(begin, end, &result)) {
  324. return result;
  325. }
  326. const char* const mantissa_begin = begin;
  327. while (begin < end && *begin == '0') {
  328. ++begin; // skip leading zeros
  329. }
  330. uint64_t mantissa = 0;
  331. int exponent_adjustment = 0;
  332. bool mantissa_is_inexact = false;
  333. int pre_decimal_digits = ConsumeDigits<base>(
  334. begin, end, MantissaDigitsMax<base>(), &mantissa, &mantissa_is_inexact);
  335. begin += pre_decimal_digits;
  336. int digits_left;
  337. if (pre_decimal_digits >= DigitLimit<base>()) {
  338. // refuse to parse pathological inputs
  339. return result;
  340. } else if (pre_decimal_digits > MantissaDigitsMax<base>()) {
  341. // We dropped some non-fraction digits on the floor. Adjust our exponent
  342. // to compensate.
  343. exponent_adjustment =
  344. static_cast<int>(pre_decimal_digits - MantissaDigitsMax<base>());
  345. digits_left = 0;
  346. } else {
  347. digits_left =
  348. static_cast<int>(MantissaDigitsMax<base>() - pre_decimal_digits);
  349. }
  350. if (begin < end && *begin == '.') {
  351. ++begin;
  352. if (mantissa == 0) {
  353. // If we haven't seen any nonzero digits yet, keep skipping zeros. We
  354. // have to adjust the exponent to reflect the changed place value.
  355. const char* begin_zeros = begin;
  356. while (begin < end && *begin == '0') {
  357. ++begin;
  358. }
  359. int zeros_skipped = static_cast<int>(begin - begin_zeros);
  360. if (zeros_skipped >= DigitLimit<base>()) {
  361. // refuse to parse pathological inputs
  362. return result;
  363. }
  364. exponent_adjustment -= static_cast<int>(zeros_skipped);
  365. }
  366. int post_decimal_digits = ConsumeDigits<base>(
  367. begin, end, digits_left, &mantissa, &mantissa_is_inexact);
  368. begin += post_decimal_digits;
  369. // Since `mantissa` is an integer, each significant digit we read after
  370. // the decimal point requires an adjustment to the exponent. "1.23e0" will
  371. // be stored as `mantissa` == 123 and `exponent` == -2 (that is,
  372. // "123e-2").
  373. if (post_decimal_digits >= DigitLimit<base>()) {
  374. // refuse to parse pathological inputs
  375. return result;
  376. } else if (post_decimal_digits > digits_left) {
  377. exponent_adjustment -= digits_left;
  378. } else {
  379. exponent_adjustment -= post_decimal_digits;
  380. }
  381. }
  382. // If we've found no mantissa whatsoever, this isn't a number.
  383. if (mantissa_begin == begin) {
  384. return result;
  385. }
  386. // A bare "." doesn't count as a mantissa either.
  387. if (begin - mantissa_begin == 1 && *mantissa_begin == '.') {
  388. return result;
  389. }
  390. if (mantissa_is_inexact) {
  391. // We dropped significant digits on the floor. Handle this appropriately.
  392. if (base == 10) {
  393. // If we truncated significant decimal digits, store the full range of the
  394. // mantissa for future big integer math for exact rounding.
  395. result.subrange_begin = mantissa_begin;
  396. result.subrange_end = begin;
  397. } else if (base == 16) {
  398. // If we truncated hex digits, reflect this fact by setting the low
  399. // ("sticky") bit. This allows for correct rounding in all cases.
  400. mantissa |= 1;
  401. }
  402. }
  403. result.mantissa = mantissa;
  404. const char* const exponent_begin = begin;
  405. result.literal_exponent = 0;
  406. bool found_exponent = false;
  407. if (AllowExponent(format_flags) && begin < end &&
  408. IsExponentCharacter<base>(*begin)) {
  409. bool negative_exponent = false;
  410. ++begin;
  411. if (begin < end && *begin == '-') {
  412. negative_exponent = true;
  413. ++begin;
  414. } else if (begin < end && *begin == '+') {
  415. ++begin;
  416. }
  417. const char* const exponent_digits_begin = begin;
  418. // Exponent is always expressed in decimal, even for hexadecimal floats.
  419. begin += ConsumeDigits<10>(begin, end, kDecimalExponentDigitsMax,
  420. &result.literal_exponent, nullptr);
  421. if (begin == exponent_digits_begin) {
  422. // there were no digits where we expected an exponent. We failed to read
  423. // an exponent and should not consume the 'e' after all. Rewind 'begin'.
  424. found_exponent = false;
  425. begin = exponent_begin;
  426. } else {
  427. found_exponent = true;
  428. if (negative_exponent) {
  429. result.literal_exponent = -result.literal_exponent;
  430. }
  431. }
  432. }
  433. if (!found_exponent && RequireExponent(format_flags)) {
  434. // Provided flags required an exponent, but none was found. This results
  435. // in a failure to scan.
  436. return result;
  437. }
  438. // Success!
  439. result.type = strings_internal::FloatType::kNumber;
  440. if (result.mantissa > 0) {
  441. result.exponent = result.literal_exponent +
  442. (DigitMagnitude<base>() * exponent_adjustment);
  443. } else {
  444. result.exponent = 0;
  445. }
  446. result.end = begin;
  447. return result;
  448. }
  449. template ParsedFloat ParseFloat<10>(const char* begin, const char* end,
  450. chars_format format_flags);
  451. template ParsedFloat ParseFloat<16>(const char* begin, const char* end,
  452. chars_format format_flags);
  453. } // namespace strings_internal
  454. Y_ABSL_NAMESPACE_END
  455. } // namespace y_absl