charconv_bigint.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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. #ifndef ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
  15. #define ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
  16. #include <algorithm>
  17. #include <cstdint>
  18. #include <iostream>
  19. #include <string>
  20. #include "absl/base/config.h"
  21. #include "absl/strings/ascii.h"
  22. #include "absl/strings/internal/charconv_parse.h"
  23. #include "absl/strings/string_view.h"
  24. namespace absl {
  25. ABSL_NAMESPACE_BEGIN
  26. namespace strings_internal {
  27. // The largest power that 5 that can be raised to, and still fit in a uint32_t.
  28. constexpr int kMaxSmallPowerOfFive = 13;
  29. // The largest power that 10 that can be raised to, and still fit in a uint32_t.
  30. constexpr int kMaxSmallPowerOfTen = 9;
  31. ABSL_DLL extern const uint32_t
  32. kFiveToNth[kMaxSmallPowerOfFive + 1];
  33. ABSL_DLL extern const uint32_t kTenToNth[kMaxSmallPowerOfTen + 1];
  34. // Large, fixed-width unsigned integer.
  35. //
  36. // Exact rounding for decimal-to-binary floating point conversion requires very
  37. // large integer math, but a design goal of absl::from_chars is to avoid
  38. // allocating memory. The integer precision needed for decimal-to-binary
  39. // conversions is large but bounded, so a huge fixed-width integer class
  40. // suffices.
  41. //
  42. // This is an intentionally limited big integer class. Only needed operations
  43. // are implemented. All storage lives in an array data member, and all
  44. // arithmetic is done in-place, to avoid requiring separate storage for operand
  45. // and result.
  46. //
  47. // This is an internal class. Some methods live in the .cc file, and are
  48. // instantiated only for the values of max_words we need.
  49. template <int max_words>
  50. class BigUnsigned {
  51. public:
  52. static_assert(max_words == 4 || max_words == 84,
  53. "unsupported max_words value");
  54. BigUnsigned() : size_(0), words_{} {}
  55. explicit constexpr BigUnsigned(uint64_t v)
  56. : size_((v >> 32) ? 2 : v ? 1 : 0),
  57. words_{static_cast<uint32_t>(v & 0xffffffffu),
  58. static_cast<uint32_t>(v >> 32)} {}
  59. // Constructs a BigUnsigned from the given string_view containing a decimal
  60. // value. If the input string is not a decimal integer, constructs a 0
  61. // instead.
  62. explicit BigUnsigned(absl::string_view sv) : size_(0), words_{} {
  63. // Check for valid input, returning a 0 otherwise. This is reasonable
  64. // behavior only because this constructor is for unit tests.
  65. if (std::find_if_not(sv.begin(), sv.end(), ascii_isdigit) != sv.end() ||
  66. sv.empty()) {
  67. return;
  68. }
  69. int exponent_adjust =
  70. ReadDigits(sv.data(), sv.data() + sv.size(), Digits10() + 1);
  71. if (exponent_adjust > 0) {
  72. MultiplyByTenToTheNth(exponent_adjust);
  73. }
  74. }
  75. // Loads the mantissa value of a previously-parsed float.
  76. //
  77. // Returns the associated decimal exponent. The value of the parsed float is
  78. // exactly *this * 10**exponent.
  79. int ReadFloatMantissa(const ParsedFloat& fp, int significant_digits);
  80. // Returns the number of decimal digits of precision this type provides. All
  81. // numbers with this many decimal digits or fewer are representable by this
  82. // type.
  83. //
  84. // Analogous to std::numeric_limits<BigUnsigned>::digits10.
  85. static constexpr int Digits10() {
  86. // 9975007/1035508 is very slightly less than log10(2**32).
  87. return static_cast<uint64_t>(max_words) * 9975007 / 1035508;
  88. }
  89. // Shifts left by the given number of bits.
  90. void ShiftLeft(int count) {
  91. if (count > 0) {
  92. const int word_shift = count / 32;
  93. if (word_shift >= max_words) {
  94. SetToZero();
  95. return;
  96. }
  97. size_ = (std::min)(size_ + word_shift, max_words);
  98. count %= 32;
  99. if (count == 0) {
  100. // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=warray-bounds
  101. // shows a lot of bogus -Warray-bounds warnings under GCC.
  102. // This is not the only one in Abseil.
  103. #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0)
  104. #pragma GCC diagnostic push
  105. #pragma GCC diagnostic ignored "-Warray-bounds"
  106. #endif
  107. std::copy_backward(words_, words_ + size_ - word_shift, words_ + size_);
  108. #if ABSL_INTERNAL_HAVE_MIN_GNUC_VERSION(14, 0)
  109. #pragma GCC diagnostic pop
  110. #endif
  111. } else {
  112. for (int i = (std::min)(size_, max_words - 1); i > word_shift; --i) {
  113. words_[i] = (words_[i - word_shift] << count) |
  114. (words_[i - word_shift - 1] >> (32 - count));
  115. }
  116. words_[word_shift] = words_[0] << count;
  117. // Grow size_ if necessary.
  118. if (size_ < max_words && words_[size_]) {
  119. ++size_;
  120. }
  121. }
  122. std::fill_n(words_, word_shift, 0u);
  123. }
  124. }
  125. // Multiplies by v in-place.
  126. void MultiplyBy(uint32_t v) {
  127. if (size_ == 0 || v == 1) {
  128. return;
  129. }
  130. if (v == 0) {
  131. SetToZero();
  132. return;
  133. }
  134. const uint64_t factor = v;
  135. uint64_t window = 0;
  136. for (int i = 0; i < size_; ++i) {
  137. window += factor * words_[i];
  138. words_[i] = window & 0xffffffff;
  139. window >>= 32;
  140. }
  141. // If carry bits remain and there's space for them, grow size_.
  142. if (window && size_ < max_words) {
  143. words_[size_] = window & 0xffffffff;
  144. ++size_;
  145. }
  146. }
  147. void MultiplyBy(uint64_t v) {
  148. uint32_t words[2];
  149. words[0] = static_cast<uint32_t>(v);
  150. words[1] = static_cast<uint32_t>(v >> 32);
  151. if (words[1] == 0) {
  152. MultiplyBy(words[0]);
  153. } else {
  154. MultiplyBy(2, words);
  155. }
  156. }
  157. // Multiplies in place by 5 to the power of n. n must be non-negative.
  158. void MultiplyByFiveToTheNth(int n) {
  159. while (n >= kMaxSmallPowerOfFive) {
  160. MultiplyBy(kFiveToNth[kMaxSmallPowerOfFive]);
  161. n -= kMaxSmallPowerOfFive;
  162. }
  163. if (n > 0) {
  164. MultiplyBy(kFiveToNth[n]);
  165. }
  166. }
  167. // Multiplies in place by 10 to the power of n. n must be non-negative.
  168. void MultiplyByTenToTheNth(int n) {
  169. if (n > kMaxSmallPowerOfTen) {
  170. // For large n, raise to a power of 5, then shift left by the same amount.
  171. // (10**n == 5**n * 2**n.) This requires fewer multiplications overall.
  172. MultiplyByFiveToTheNth(n);
  173. ShiftLeft(n);
  174. } else if (n > 0) {
  175. // We can do this more quickly for very small N by using a single
  176. // multiplication.
  177. MultiplyBy(kTenToNth[n]);
  178. }
  179. }
  180. // Returns the value of 5**n, for non-negative n. This implementation uses
  181. // a lookup table, and is faster then seeding a BigUnsigned with 1 and calling
  182. // MultiplyByFiveToTheNth().
  183. static BigUnsigned FiveToTheNth(int n);
  184. // Multiplies by another BigUnsigned, in-place.
  185. template <int M>
  186. void MultiplyBy(const BigUnsigned<M>& other) {
  187. MultiplyBy(other.size(), other.words());
  188. }
  189. void SetToZero() {
  190. std::fill_n(words_, size_, 0u);
  191. size_ = 0;
  192. }
  193. // Returns the value of the nth word of this BigUnsigned. This is
  194. // range-checked, and returns 0 on out-of-bounds accesses.
  195. uint32_t GetWord(int index) const {
  196. if (index < 0 || index >= size_) {
  197. return 0;
  198. }
  199. return words_[index];
  200. }
  201. // Returns this integer as a decimal string. This is not used in the decimal-
  202. // to-binary conversion; it is intended to aid in testing.
  203. std::string ToString() const;
  204. int size() const { return size_; }
  205. const uint32_t* words() const { return words_; }
  206. private:
  207. // Reads the number between [begin, end), possibly containing a decimal point,
  208. // into this BigUnsigned.
  209. //
  210. // Callers are required to ensure [begin, end) contains a valid number, with
  211. // one or more decimal digits and at most one decimal point. This routine
  212. // will behave unpredictably if these preconditions are not met.
  213. //
  214. // Only the first `significant_digits` digits are read. Digits beyond this
  215. // limit are "sticky": If the final significant digit is 0 or 5, and if any
  216. // dropped digit is nonzero, then that final significant digit is adjusted up
  217. // to 1 or 6. This adjustment allows for precise rounding.
  218. //
  219. // Returns `exponent_adjustment`, a power-of-ten exponent adjustment to
  220. // account for the decimal point and for dropped significant digits. After
  221. // this function returns,
  222. // actual_value_of_parsed_string ~= *this * 10**exponent_adjustment.
  223. int ReadDigits(const char* begin, const char* end, int significant_digits);
  224. // Performs a step of big integer multiplication. This computes the full
  225. // (64-bit-wide) values that should be added at the given index (step), and
  226. // adds to that location in-place.
  227. //
  228. // Because our math all occurs in place, we must multiply starting from the
  229. // highest word working downward. (This is a bit more expensive due to the
  230. // extra carries involved.)
  231. //
  232. // This must be called in steps, for each word to be calculated, starting from
  233. // the high end and working down to 0. The first value of `step` should be
  234. // `std::min(original_size + other.size_ - 2, max_words - 1)`.
  235. // The reason for this expression is that multiplying the i'th word from one
  236. // multiplicand and the j'th word of another multiplicand creates a
  237. // two-word-wide value to be stored at the (i+j)'th element. The highest
  238. // word indices we will access are `original_size - 1` from this object, and
  239. // `other.size_ - 1` from our operand. Therefore,
  240. // `original_size + other.size_ - 2` is the first step we should calculate,
  241. // but limited on an upper bound by max_words.
  242. // Working from high-to-low ensures that we do not overwrite the portions of
  243. // the initial value of *this which are still needed for later steps.
  244. //
  245. // Once called with step == 0, *this contains the result of the
  246. // multiplication.
  247. //
  248. // `original_size` is the size_ of *this before the first call to
  249. // MultiplyStep(). `other_words` and `other_size` are the contents of our
  250. // operand. `step` is the step to perform, as described above.
  251. void MultiplyStep(int original_size, const uint32_t* other_words,
  252. int other_size, int step);
  253. void MultiplyBy(int other_size, const uint32_t* other_words) {
  254. const int original_size = size_;
  255. const int first_step =
  256. (std::min)(original_size + other_size - 2, max_words - 1);
  257. for (int step = first_step; step >= 0; --step) {
  258. MultiplyStep(original_size, other_words, other_size, step);
  259. }
  260. }
  261. // Adds a 32-bit value to the index'th word, with carry.
  262. void AddWithCarry(int index, uint32_t value) {
  263. if (value) {
  264. while (index < max_words && value > 0) {
  265. words_[index] += value;
  266. // carry if we overflowed in this word:
  267. if (value > words_[index]) {
  268. value = 1;
  269. ++index;
  270. } else {
  271. value = 0;
  272. }
  273. }
  274. size_ = (std::min)(max_words, (std::max)(index + 1, size_));
  275. }
  276. }
  277. void AddWithCarry(int index, uint64_t value) {
  278. if (value && index < max_words) {
  279. uint32_t high = value >> 32;
  280. uint32_t low = value & 0xffffffff;
  281. words_[index] += low;
  282. if (words_[index] < low) {
  283. ++high;
  284. if (high == 0) {
  285. // Carry from the low word caused our high word to overflow.
  286. // Short circuit here to do the right thing.
  287. AddWithCarry(index + 2, static_cast<uint32_t>(1));
  288. return;
  289. }
  290. }
  291. if (high > 0) {
  292. AddWithCarry(index + 1, high);
  293. } else {
  294. // Normally 32-bit AddWithCarry() sets size_, but since we don't call
  295. // it when `high` is 0, do it ourselves here.
  296. size_ = (std::min)(max_words, (std::max)(index + 1, size_));
  297. }
  298. }
  299. }
  300. // Divide this in place by a constant divisor. Returns the remainder of the
  301. // division.
  302. template <uint32_t divisor>
  303. uint32_t DivMod() {
  304. uint64_t accumulator = 0;
  305. for (int i = size_ - 1; i >= 0; --i) {
  306. accumulator <<= 32;
  307. accumulator += words_[i];
  308. // accumulator / divisor will never overflow an int32_t in this loop
  309. words_[i] = static_cast<uint32_t>(accumulator / divisor);
  310. accumulator = accumulator % divisor;
  311. }
  312. while (size_ > 0 && words_[size_ - 1] == 0) {
  313. --size_;
  314. }
  315. return static_cast<uint32_t>(accumulator);
  316. }
  317. // The number of elements in words_ that may carry significant values.
  318. // All elements beyond this point are 0.
  319. //
  320. // When size_ is 0, this BigUnsigned stores the value 0.
  321. // When size_ is nonzero, is *not* guaranteed that words_[size_ - 1] is
  322. // nonzero. This can occur due to overflow truncation.
  323. // In particular, x.size_ != y.size_ does *not* imply x != y.
  324. int size_;
  325. uint32_t words_[max_words];
  326. };
  327. // Compares two big integer instances.
  328. //
  329. // Returns -1 if lhs < rhs, 0 if lhs == rhs, and 1 if lhs > rhs.
  330. template <int N, int M>
  331. int Compare(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  332. int limit = (std::max)(lhs.size(), rhs.size());
  333. for (int i = limit - 1; i >= 0; --i) {
  334. const uint32_t lhs_word = lhs.GetWord(i);
  335. const uint32_t rhs_word = rhs.GetWord(i);
  336. if (lhs_word < rhs_word) {
  337. return -1;
  338. } else if (lhs_word > rhs_word) {
  339. return 1;
  340. }
  341. }
  342. return 0;
  343. }
  344. template <int N, int M>
  345. bool operator==(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  346. int limit = (std::max)(lhs.size(), rhs.size());
  347. for (int i = 0; i < limit; ++i) {
  348. if (lhs.GetWord(i) != rhs.GetWord(i)) {
  349. return false;
  350. }
  351. }
  352. return true;
  353. }
  354. template <int N, int M>
  355. bool operator!=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  356. return !(lhs == rhs);
  357. }
  358. template <int N, int M>
  359. bool operator<(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  360. return Compare(lhs, rhs) == -1;
  361. }
  362. template <int N, int M>
  363. bool operator>(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  364. return rhs < lhs;
  365. }
  366. template <int N, int M>
  367. bool operator<=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  368. return !(rhs < lhs);
  369. }
  370. template <int N, int M>
  371. bool operator>=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  372. return !(lhs < rhs);
  373. }
  374. // Output operator for BigUnsigned, for testing purposes only.
  375. template <int N>
  376. std::ostream& operator<<(std::ostream& os, const BigUnsigned<N>& num) {
  377. return os << num.ToString();
  378. }
  379. // Explicit instantiation declarations for the sizes of BigUnsigned that we
  380. // are using.
  381. //
  382. // For now, the choices of 4 and 84 are arbitrary; 4 is a small value that is
  383. // still bigger than an int128, and 84 is a large value we will want to use
  384. // in the from_chars implementation.
  385. //
  386. // Comments justifying the use of 84 belong in the from_chars implementation,
  387. // and will be added in a follow-up CL.
  388. extern template class BigUnsigned<4>;
  389. extern template class BigUnsigned<84>;
  390. } // namespace strings_internal
  391. ABSL_NAMESPACE_END
  392. } // namespace absl
  393. #endif // ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_