charconv_bigint.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 Y_ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
  15. #define Y_ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_
  16. #include <algorithm>
  17. #include <cstdint>
  18. #include <iostream>
  19. #include <util/generic/string.h>
  20. #include "y_absl/base/config.h"
  21. #include "y_absl/strings/ascii.h"
  22. #include "y_absl/strings/internal/charconv_parse.h"
  23. #include "y_absl/strings/string_view.h"
  24. namespace y_absl {
  25. Y_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. Y_ABSL_DLL extern const uint32_t
  32. kFiveToNth[kMaxSmallPowerOfFive + 1];
  33. Y_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 y_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(y_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. std::copy_backward(words_, words_ + size_ - word_shift, words_ + size_);
  101. } else {
  102. for (int i = (std::min)(size_, max_words - 1); i > word_shift; --i) {
  103. words_[i] = (words_[i - word_shift] << count) |
  104. (words_[i - word_shift - 1] >> (32 - count));
  105. }
  106. words_[word_shift] = words_[0] << count;
  107. // Grow size_ if necessary.
  108. if (size_ < max_words && words_[size_]) {
  109. ++size_;
  110. }
  111. }
  112. std::fill_n(words_, word_shift, 0u);
  113. }
  114. }
  115. // Multiplies by v in-place.
  116. void MultiplyBy(uint32_t v) {
  117. if (size_ == 0 || v == 1) {
  118. return;
  119. }
  120. if (v == 0) {
  121. SetToZero();
  122. return;
  123. }
  124. const uint64_t factor = v;
  125. uint64_t window = 0;
  126. for (int i = 0; i < size_; ++i) {
  127. window += factor * words_[i];
  128. words_[i] = window & 0xffffffff;
  129. window >>= 32;
  130. }
  131. // If carry bits remain and there's space for them, grow size_.
  132. if (window && size_ < max_words) {
  133. words_[size_] = window & 0xffffffff;
  134. ++size_;
  135. }
  136. }
  137. void MultiplyBy(uint64_t v) {
  138. uint32_t words[2];
  139. words[0] = static_cast<uint32_t>(v);
  140. words[1] = static_cast<uint32_t>(v >> 32);
  141. if (words[1] == 0) {
  142. MultiplyBy(words[0]);
  143. } else {
  144. MultiplyBy(2, words);
  145. }
  146. }
  147. // Multiplies in place by 5 to the power of n. n must be non-negative.
  148. void MultiplyByFiveToTheNth(int n) {
  149. while (n >= kMaxSmallPowerOfFive) {
  150. MultiplyBy(kFiveToNth[kMaxSmallPowerOfFive]);
  151. n -= kMaxSmallPowerOfFive;
  152. }
  153. if (n > 0) {
  154. MultiplyBy(kFiveToNth[n]);
  155. }
  156. }
  157. // Multiplies in place by 10 to the power of n. n must be non-negative.
  158. void MultiplyByTenToTheNth(int n) {
  159. if (n > kMaxSmallPowerOfTen) {
  160. // For large n, raise to a power of 5, then shift left by the same amount.
  161. // (10**n == 5**n * 2**n.) This requires fewer multiplications overall.
  162. MultiplyByFiveToTheNth(n);
  163. ShiftLeft(n);
  164. } else if (n > 0) {
  165. // We can do this more quickly for very small N by using a single
  166. // multiplication.
  167. MultiplyBy(kTenToNth[n]);
  168. }
  169. }
  170. // Returns the value of 5**n, for non-negative n. This implementation uses
  171. // a lookup table, and is faster then seeding a BigUnsigned with 1 and calling
  172. // MultiplyByFiveToTheNth().
  173. static BigUnsigned FiveToTheNth(int n);
  174. // Multiplies by another BigUnsigned, in-place.
  175. template <int M>
  176. void MultiplyBy(const BigUnsigned<M>& other) {
  177. MultiplyBy(other.size(), other.words());
  178. }
  179. void SetToZero() {
  180. std::fill_n(words_, size_, 0u);
  181. size_ = 0;
  182. }
  183. // Returns the value of the nth word of this BigUnsigned. This is
  184. // range-checked, and returns 0 on out-of-bounds accesses.
  185. uint32_t GetWord(int index) const {
  186. if (index < 0 || index >= size_) {
  187. return 0;
  188. }
  189. return words_[index];
  190. }
  191. // Returns this integer as a decimal string. This is not used in the decimal-
  192. // to-binary conversion; it is intended to aid in testing.
  193. TString ToString() const;
  194. int size() const { return size_; }
  195. const uint32_t* words() const { return words_; }
  196. private:
  197. // Reads the number between [begin, end), possibly containing a decimal point,
  198. // into this BigUnsigned.
  199. //
  200. // Callers are required to ensure [begin, end) contains a valid number, with
  201. // one or more decimal digits and at most one decimal point. This routine
  202. // will behave unpredictably if these preconditions are not met.
  203. //
  204. // Only the first `significant_digits` digits are read. Digits beyond this
  205. // limit are "sticky": If the final significant digit is 0 or 5, and if any
  206. // dropped digit is nonzero, then that final significant digit is adjusted up
  207. // to 1 or 6. This adjustment allows for precise rounding.
  208. //
  209. // Returns `exponent_adjustment`, a power-of-ten exponent adjustment to
  210. // account for the decimal point and for dropped significant digits. After
  211. // this function returns,
  212. // actual_value_of_parsed_string ~= *this * 10**exponent_adjustment.
  213. int ReadDigits(const char* begin, const char* end, int significant_digits);
  214. // Performs a step of big integer multiplication. This computes the full
  215. // (64-bit-wide) values that should be added at the given index (step), and
  216. // adds to that location in-place.
  217. //
  218. // Because our math all occurs in place, we must multiply starting from the
  219. // highest word working downward. (This is a bit more expensive due to the
  220. // extra carries involved.)
  221. //
  222. // This must be called in steps, for each word to be calculated, starting from
  223. // the high end and working down to 0. The first value of `step` should be
  224. // `std::min(original_size + other.size_ - 2, max_words - 1)`.
  225. // The reason for this expression is that multiplying the i'th word from one
  226. // multiplicand and the j'th word of another multiplicand creates a
  227. // two-word-wide value to be stored at the (i+j)'th element. The highest
  228. // word indices we will access are `original_size - 1` from this object, and
  229. // `other.size_ - 1` from our operand. Therefore,
  230. // `original_size + other.size_ - 2` is the first step we should calculate,
  231. // but limited on an upper bound by max_words.
  232. // Working from high-to-low ensures that we do not overwrite the portions of
  233. // the initial value of *this which are still needed for later steps.
  234. //
  235. // Once called with step == 0, *this contains the result of the
  236. // multiplication.
  237. //
  238. // `original_size` is the size_ of *this before the first call to
  239. // MultiplyStep(). `other_words` and `other_size` are the contents of our
  240. // operand. `step` is the step to perform, as described above.
  241. void MultiplyStep(int original_size, const uint32_t* other_words,
  242. int other_size, int step);
  243. void MultiplyBy(int other_size, const uint32_t* other_words) {
  244. const int original_size = size_;
  245. const int first_step =
  246. (std::min)(original_size + other_size - 2, max_words - 1);
  247. for (int step = first_step; step >= 0; --step) {
  248. MultiplyStep(original_size, other_words, other_size, step);
  249. }
  250. }
  251. // Adds a 32-bit value to the index'th word, with carry.
  252. void AddWithCarry(int index, uint32_t value) {
  253. if (value) {
  254. while (index < max_words && value > 0) {
  255. words_[index] += value;
  256. // carry if we overflowed in this word:
  257. if (value > words_[index]) {
  258. value = 1;
  259. ++index;
  260. } else {
  261. value = 0;
  262. }
  263. }
  264. size_ = (std::min)(max_words, (std::max)(index + 1, size_));
  265. }
  266. }
  267. void AddWithCarry(int index, uint64_t value) {
  268. if (value && index < max_words) {
  269. uint32_t high = value >> 32;
  270. uint32_t low = value & 0xffffffff;
  271. words_[index] += low;
  272. if (words_[index] < low) {
  273. ++high;
  274. if (high == 0) {
  275. // Carry from the low word caused our high word to overflow.
  276. // Short circuit here to do the right thing.
  277. AddWithCarry(index + 2, static_cast<uint32_t>(1));
  278. return;
  279. }
  280. }
  281. if (high > 0) {
  282. AddWithCarry(index + 1, high);
  283. } else {
  284. // Normally 32-bit AddWithCarry() sets size_, but since we don't call
  285. // it when `high` is 0, do it ourselves here.
  286. size_ = (std::min)(max_words, (std::max)(index + 1, size_));
  287. }
  288. }
  289. }
  290. // Divide this in place by a constant divisor. Returns the remainder of the
  291. // division.
  292. template <uint32_t divisor>
  293. uint32_t DivMod() {
  294. uint64_t accumulator = 0;
  295. for (int i = size_ - 1; i >= 0; --i) {
  296. accumulator <<= 32;
  297. accumulator += words_[i];
  298. // accumulator / divisor will never overflow an int32_t in this loop
  299. words_[i] = static_cast<uint32_t>(accumulator / divisor);
  300. accumulator = accumulator % divisor;
  301. }
  302. while (size_ > 0 && words_[size_ - 1] == 0) {
  303. --size_;
  304. }
  305. return static_cast<uint32_t>(accumulator);
  306. }
  307. // The number of elements in words_ that may carry significant values.
  308. // All elements beyond this point are 0.
  309. //
  310. // When size_ is 0, this BigUnsigned stores the value 0.
  311. // When size_ is nonzero, is *not* guaranteed that words_[size_ - 1] is
  312. // nonzero. This can occur due to overflow truncation.
  313. // In particular, x.size_ != y.size_ does *not* imply x != y.
  314. int size_;
  315. uint32_t words_[max_words];
  316. };
  317. // Compares two big integer instances.
  318. //
  319. // Returns -1 if lhs < rhs, 0 if lhs == rhs, and 1 if lhs > rhs.
  320. template <int N, int M>
  321. int Compare(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  322. int limit = (std::max)(lhs.size(), rhs.size());
  323. for (int i = limit - 1; i >= 0; --i) {
  324. const uint32_t lhs_word = lhs.GetWord(i);
  325. const uint32_t rhs_word = rhs.GetWord(i);
  326. if (lhs_word < rhs_word) {
  327. return -1;
  328. } else if (lhs_word > rhs_word) {
  329. return 1;
  330. }
  331. }
  332. return 0;
  333. }
  334. template <int N, int M>
  335. bool operator==(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  336. int limit = (std::max)(lhs.size(), rhs.size());
  337. for (int i = 0; i < limit; ++i) {
  338. if (lhs.GetWord(i) != rhs.GetWord(i)) {
  339. return false;
  340. }
  341. }
  342. return true;
  343. }
  344. template <int N, int M>
  345. bool operator!=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  346. return !(lhs == rhs);
  347. }
  348. template <int N, int M>
  349. bool operator<(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  350. return Compare(lhs, rhs) == -1;
  351. }
  352. template <int N, int M>
  353. bool operator>(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  354. return rhs < lhs;
  355. }
  356. template <int N, int M>
  357. bool operator<=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  358. return !(rhs < lhs);
  359. }
  360. template <int N, int M>
  361. bool operator>=(const BigUnsigned<N>& lhs, const BigUnsigned<M>& rhs) {
  362. return !(lhs < rhs);
  363. }
  364. // Output operator for BigUnsigned, for testing purposes only.
  365. template <int N>
  366. std::ostream& operator<<(std::ostream& os, const BigUnsigned<N>& num) {
  367. return os << num.ToString();
  368. }
  369. // Explicit instantiation declarations for the sizes of BigUnsigned that we
  370. // are using.
  371. //
  372. // For now, the choices of 4 and 84 are arbitrary; 4 is a small value that is
  373. // still bigger than an int128, and 84 is a large value we will want to use
  374. // in the from_chars implementation.
  375. //
  376. // Comments justifying the use of 84 belong in the from_chars implementation,
  377. // and will be added in a follow-up CL.
  378. extern template class BigUnsigned<4>;
  379. extern template class BigUnsigned<84>;
  380. } // namespace strings_internal
  381. Y_ABSL_NAMESPACE_END
  382. } // namespace y_absl
  383. #endif // Y_ABSL_STRINGS_INTERNAL_CHARCONV_BIGINT_H_