double-conversion-bignum.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. // © 2018 and later: Unicode, Inc. and others.
  2. // License & terms of use: http://www.unicode.org/copyright.html
  3. //
  4. // From the double-conversion library. Original license:
  5. //
  6. // Copyright 2010 the V8 project authors. All rights reserved.
  7. // Redistribution and use in source and binary forms, with or without
  8. // modification, are permitted provided that the following conditions are
  9. // met:
  10. //
  11. // * Redistributions of source code must retain the above copyright
  12. // notice, this list of conditions and the following disclaimer.
  13. // * Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. // * Neither the name of Google Inc. nor the names of its
  18. // contributors may be used to endorse or promote products derived
  19. // from this software without specific prior written permission.
  20. //
  21. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. // ICU PATCH: ifdef around UCONFIG_NO_FORMATTING
  33. #include "unicode/utypes.h"
  34. #if !UCONFIG_NO_FORMATTING
  35. #include <algorithm>
  36. #include <cstring>
  37. // ICU PATCH: Customize header file paths for ICU.
  38. #include "double-conversion-bignum.h"
  39. #include "double-conversion-utils.h"
  40. // ICU PATCH: Wrap in ICU namespace
  41. U_NAMESPACE_BEGIN
  42. namespace double_conversion {
  43. Bignum::Chunk& Bignum::RawBigit(const int index) {
  44. DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
  45. return bigits_buffer_[index];
  46. }
  47. const Bignum::Chunk& Bignum::RawBigit(const int index) const {
  48. DOUBLE_CONVERSION_ASSERT(static_cast<unsigned>(index) < kBigitCapacity);
  49. return bigits_buffer_[index];
  50. }
  51. template<typename S>
  52. static int BitSize(const S value) {
  53. (void) value; // Mark variable as used.
  54. return 8 * sizeof(value);
  55. }
  56. // Guaranteed to lie in one Bigit.
  57. void Bignum::AssignUInt16(const uint16_t value) {
  58. DOUBLE_CONVERSION_ASSERT(kBigitSize >= BitSize(value));
  59. Zero();
  60. if (value > 0) {
  61. RawBigit(0) = value;
  62. used_bigits_ = 1;
  63. }
  64. }
  65. void Bignum::AssignUInt64(uint64_t value) {
  66. Zero();
  67. for(int i = 0; value > 0; ++i) {
  68. RawBigit(i) = value & kBigitMask;
  69. value >>= kBigitSize;
  70. ++used_bigits_;
  71. }
  72. }
  73. void Bignum::AssignBignum(const Bignum& other) {
  74. exponent_ = other.exponent_;
  75. for (int i = 0; i < other.used_bigits_; ++i) {
  76. RawBigit(i) = other.RawBigit(i);
  77. }
  78. used_bigits_ = other.used_bigits_;
  79. }
  80. static uint64_t ReadUInt64(const Vector<const char> buffer,
  81. const int from,
  82. const int digits_to_read) {
  83. uint64_t result = 0;
  84. for (int i = from; i < from + digits_to_read; ++i) {
  85. const int digit = buffer[i] - '0';
  86. DOUBLE_CONVERSION_ASSERT(0 <= digit && digit <= 9);
  87. result = result * 10 + digit;
  88. }
  89. return result;
  90. }
  91. void Bignum::AssignDecimalString(const Vector<const char> value) {
  92. // 2^64 = 18446744073709551616 > 10^19
  93. static const int kMaxUint64DecimalDigits = 19;
  94. Zero();
  95. int length = value.length();
  96. unsigned pos = 0;
  97. // Let's just say that each digit needs 4 bits.
  98. while (length >= kMaxUint64DecimalDigits) {
  99. const uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
  100. pos += kMaxUint64DecimalDigits;
  101. length -= kMaxUint64DecimalDigits;
  102. MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
  103. AddUInt64(digits);
  104. }
  105. const uint64_t digits = ReadUInt64(value, pos, length);
  106. MultiplyByPowerOfTen(length);
  107. AddUInt64(digits);
  108. Clamp();
  109. }
  110. static uint64_t HexCharValue(const int c) {
  111. if ('0' <= c && c <= '9') {
  112. return c - '0';
  113. }
  114. if ('a' <= c && c <= 'f') {
  115. return 10 + c - 'a';
  116. }
  117. DOUBLE_CONVERSION_ASSERT('A' <= c && c <= 'F');
  118. return 10 + c - 'A';
  119. }
  120. // Unlike AssignDecimalString(), this function is "only" used
  121. // for unit-tests and therefore not performance critical.
  122. void Bignum::AssignHexString(Vector<const char> value) {
  123. Zero();
  124. // Required capacity could be reduced by ignoring leading zeros.
  125. EnsureCapacity(((value.length() * 4) + kBigitSize - 1) / kBigitSize);
  126. DOUBLE_CONVERSION_ASSERT(sizeof(uint64_t) * 8 >= kBigitSize + 4); // TODO: static_assert
  127. // Accumulates converted hex digits until at least kBigitSize bits.
  128. // Works with non-factor-of-four kBigitSizes.
  129. uint64_t tmp = 0;
  130. for (int cnt = 0; !value.is_empty(); value.pop_back()) {
  131. tmp |= (HexCharValue(value.last()) << cnt);
  132. if ((cnt += 4) >= kBigitSize) {
  133. RawBigit(used_bigits_++) = (tmp & kBigitMask);
  134. cnt -= kBigitSize;
  135. tmp >>= kBigitSize;
  136. }
  137. }
  138. if (tmp > 0) {
  139. DOUBLE_CONVERSION_ASSERT(tmp <= kBigitMask);
  140. RawBigit(used_bigits_++) = static_cast<Bignum::Chunk>(tmp & kBigitMask);
  141. }
  142. Clamp();
  143. }
  144. void Bignum::AddUInt64(const uint64_t operand) {
  145. if (operand == 0) {
  146. return;
  147. }
  148. Bignum other;
  149. other.AssignUInt64(operand);
  150. AddBignum(other);
  151. }
  152. void Bignum::AddBignum(const Bignum& other) {
  153. DOUBLE_CONVERSION_ASSERT(IsClamped());
  154. DOUBLE_CONVERSION_ASSERT(other.IsClamped());
  155. // If this has a greater exponent than other append zero-bigits to this.
  156. // After this call exponent_ <= other.exponent_.
  157. Align(other);
  158. // There are two possibilities:
  159. // aaaaaaaaaaa 0000 (where the 0s represent a's exponent)
  160. // bbbbb 00000000
  161. // ----------------
  162. // ccccccccccc 0000
  163. // or
  164. // aaaaaaaaaa 0000
  165. // bbbbbbbbb 0000000
  166. // -----------------
  167. // cccccccccccc 0000
  168. // In both cases we might need a carry bigit.
  169. EnsureCapacity(1 + (std::max)(BigitLength(), other.BigitLength()) - exponent_);
  170. Chunk carry = 0;
  171. int bigit_pos = other.exponent_ - exponent_;
  172. DOUBLE_CONVERSION_ASSERT(bigit_pos >= 0);
  173. for (int i = used_bigits_; i < bigit_pos; ++i) {
  174. RawBigit(i) = 0;
  175. }
  176. for (int i = 0; i < other.used_bigits_; ++i) {
  177. const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
  178. const Chunk sum = my + other.RawBigit(i) + carry;
  179. RawBigit(bigit_pos) = sum & kBigitMask;
  180. carry = sum >> kBigitSize;
  181. ++bigit_pos;
  182. }
  183. while (carry != 0) {
  184. const Chunk my = (bigit_pos < used_bigits_) ? RawBigit(bigit_pos) : 0;
  185. const Chunk sum = my + carry;
  186. RawBigit(bigit_pos) = sum & kBigitMask;
  187. carry = sum >> kBigitSize;
  188. ++bigit_pos;
  189. }
  190. used_bigits_ = static_cast<int16_t>(std::max(bigit_pos, static_cast<int>(used_bigits_)));
  191. DOUBLE_CONVERSION_ASSERT(IsClamped());
  192. }
  193. void Bignum::SubtractBignum(const Bignum& other) {
  194. DOUBLE_CONVERSION_ASSERT(IsClamped());
  195. DOUBLE_CONVERSION_ASSERT(other.IsClamped());
  196. // We require this to be bigger than other.
  197. DOUBLE_CONVERSION_ASSERT(LessEqual(other, *this));
  198. Align(other);
  199. const int offset = other.exponent_ - exponent_;
  200. Chunk borrow = 0;
  201. int i;
  202. for (i = 0; i < other.used_bigits_; ++i) {
  203. DOUBLE_CONVERSION_ASSERT((borrow == 0) || (borrow == 1));
  204. const Chunk difference = RawBigit(i + offset) - other.RawBigit(i) - borrow;
  205. RawBigit(i + offset) = difference & kBigitMask;
  206. borrow = difference >> (kChunkSize - 1);
  207. }
  208. while (borrow != 0) {
  209. const Chunk difference = RawBigit(i + offset) - borrow;
  210. RawBigit(i + offset) = difference & kBigitMask;
  211. borrow = difference >> (kChunkSize - 1);
  212. ++i;
  213. }
  214. Clamp();
  215. }
  216. void Bignum::ShiftLeft(const int shift_amount) {
  217. if (used_bigits_ == 0) {
  218. return;
  219. }
  220. exponent_ += static_cast<int16_t>(shift_amount / kBigitSize);
  221. const int local_shift = shift_amount % kBigitSize;
  222. EnsureCapacity(used_bigits_ + 1);
  223. BigitsShiftLeft(local_shift);
  224. }
  225. void Bignum::MultiplyByUInt32(const uint32_t factor) {
  226. if (factor == 1) {
  227. return;
  228. }
  229. if (factor == 0) {
  230. Zero();
  231. return;
  232. }
  233. if (used_bigits_ == 0) {
  234. return;
  235. }
  236. // The product of a bigit with the factor is of size kBigitSize + 32.
  237. // Assert that this number + 1 (for the carry) fits into double chunk.
  238. DOUBLE_CONVERSION_ASSERT(kDoubleChunkSize >= kBigitSize + 32 + 1);
  239. DoubleChunk carry = 0;
  240. for (int i = 0; i < used_bigits_; ++i) {
  241. const DoubleChunk product = static_cast<DoubleChunk>(factor) * RawBigit(i) + carry;
  242. RawBigit(i) = static_cast<Chunk>(product & kBigitMask);
  243. carry = (product >> kBigitSize);
  244. }
  245. while (carry != 0) {
  246. EnsureCapacity(used_bigits_ + 1);
  247. RawBigit(used_bigits_) = carry & kBigitMask;
  248. used_bigits_++;
  249. carry >>= kBigitSize;
  250. }
  251. }
  252. void Bignum::MultiplyByUInt64(const uint64_t factor) {
  253. if (factor == 1) {
  254. return;
  255. }
  256. if (factor == 0) {
  257. Zero();
  258. return;
  259. }
  260. if (used_bigits_ == 0) {
  261. return;
  262. }
  263. DOUBLE_CONVERSION_ASSERT(kBigitSize < 32);
  264. uint64_t carry = 0;
  265. const uint64_t low = factor & 0xFFFFFFFF;
  266. const uint64_t high = factor >> 32;
  267. for (int i = 0; i < used_bigits_; ++i) {
  268. const uint64_t product_low = low * RawBigit(i);
  269. const uint64_t product_high = high * RawBigit(i);
  270. const uint64_t tmp = (carry & kBigitMask) + product_low;
  271. RawBigit(i) = tmp & kBigitMask;
  272. carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
  273. (product_high << (32 - kBigitSize));
  274. }
  275. while (carry != 0) {
  276. EnsureCapacity(used_bigits_ + 1);
  277. RawBigit(used_bigits_) = carry & kBigitMask;
  278. used_bigits_++;
  279. carry >>= kBigitSize;
  280. }
  281. }
  282. void Bignum::MultiplyByPowerOfTen(const int exponent) {
  283. static const uint64_t kFive27 = DOUBLE_CONVERSION_UINT64_2PART_C(0x6765c793, fa10079d);
  284. static const uint16_t kFive1 = 5;
  285. static const uint16_t kFive2 = kFive1 * 5;
  286. static const uint16_t kFive3 = kFive2 * 5;
  287. static const uint16_t kFive4 = kFive3 * 5;
  288. static const uint16_t kFive5 = kFive4 * 5;
  289. static const uint16_t kFive6 = kFive5 * 5;
  290. static const uint32_t kFive7 = kFive6 * 5;
  291. static const uint32_t kFive8 = kFive7 * 5;
  292. static const uint32_t kFive9 = kFive8 * 5;
  293. static const uint32_t kFive10 = kFive9 * 5;
  294. static const uint32_t kFive11 = kFive10 * 5;
  295. static const uint32_t kFive12 = kFive11 * 5;
  296. static const uint32_t kFive13 = kFive12 * 5;
  297. static const uint32_t kFive1_to_12[] =
  298. { kFive1, kFive2, kFive3, kFive4, kFive5, kFive6,
  299. kFive7, kFive8, kFive9, kFive10, kFive11, kFive12 };
  300. DOUBLE_CONVERSION_ASSERT(exponent >= 0);
  301. if (exponent == 0) {
  302. return;
  303. }
  304. if (used_bigits_ == 0) {
  305. return;
  306. }
  307. // We shift by exponent at the end just before returning.
  308. int remaining_exponent = exponent;
  309. while (remaining_exponent >= 27) {
  310. MultiplyByUInt64(kFive27);
  311. remaining_exponent -= 27;
  312. }
  313. while (remaining_exponent >= 13) {
  314. MultiplyByUInt32(kFive13);
  315. remaining_exponent -= 13;
  316. }
  317. if (remaining_exponent > 0) {
  318. MultiplyByUInt32(kFive1_to_12[remaining_exponent - 1]);
  319. }
  320. ShiftLeft(exponent);
  321. }
  322. void Bignum::Square() {
  323. DOUBLE_CONVERSION_ASSERT(IsClamped());
  324. const int product_length = 2 * used_bigits_;
  325. EnsureCapacity(product_length);
  326. // Comba multiplication: compute each column separately.
  327. // Example: r = a2a1a0 * b2b1b0.
  328. // r = 1 * a0b0 +
  329. // 10 * (a1b0 + a0b1) +
  330. // 100 * (a2b0 + a1b1 + a0b2) +
  331. // 1000 * (a2b1 + a1b2) +
  332. // 10000 * a2b2
  333. //
  334. // In the worst case we have to accumulate nb-digits products of digit*digit.
  335. //
  336. // Assert that the additional number of bits in a DoubleChunk are enough to
  337. // sum up used_digits of Bigit*Bigit.
  338. if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_bigits_) {
  339. DOUBLE_CONVERSION_UNIMPLEMENTED();
  340. }
  341. DoubleChunk accumulator = 0;
  342. // First shift the digits so we don't overwrite them.
  343. const int copy_offset = used_bigits_;
  344. for (int i = 0; i < used_bigits_; ++i) {
  345. RawBigit(copy_offset + i) = RawBigit(i);
  346. }
  347. // We have two loops to avoid some 'if's in the loop.
  348. for (int i = 0; i < used_bigits_; ++i) {
  349. // Process temporary digit i with power i.
  350. // The sum of the two indices must be equal to i.
  351. int bigit_index1 = i;
  352. int bigit_index2 = 0;
  353. // Sum all of the sub-products.
  354. while (bigit_index1 >= 0) {
  355. const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
  356. const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
  357. accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
  358. bigit_index1--;
  359. bigit_index2++;
  360. }
  361. RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
  362. accumulator >>= kBigitSize;
  363. }
  364. for (int i = used_bigits_; i < product_length; ++i) {
  365. int bigit_index1 = used_bigits_ - 1;
  366. int bigit_index2 = i - bigit_index1;
  367. // Invariant: sum of both indices is again equal to i.
  368. // Inner loop runs 0 times on last iteration, emptying accumulator.
  369. while (bigit_index2 < used_bigits_) {
  370. const Chunk chunk1 = RawBigit(copy_offset + bigit_index1);
  371. const Chunk chunk2 = RawBigit(copy_offset + bigit_index2);
  372. accumulator += static_cast<DoubleChunk>(chunk1) * chunk2;
  373. bigit_index1--;
  374. bigit_index2++;
  375. }
  376. // The overwritten RawBigit(i) will never be read in further loop iterations,
  377. // because bigit_index1 and bigit_index2 are always greater
  378. // than i - used_bigits_.
  379. RawBigit(i) = static_cast<Chunk>(accumulator) & kBigitMask;
  380. accumulator >>= kBigitSize;
  381. }
  382. // Since the result was guaranteed to lie inside the number the
  383. // accumulator must be 0 now.
  384. DOUBLE_CONVERSION_ASSERT(accumulator == 0);
  385. // Don't forget to update the used_digits and the exponent.
  386. used_bigits_ = static_cast<int16_t>(product_length);
  387. exponent_ *= 2;
  388. Clamp();
  389. }
  390. void Bignum::AssignPowerUInt16(uint16_t base, const int power_exponent) {
  391. DOUBLE_CONVERSION_ASSERT(base != 0);
  392. DOUBLE_CONVERSION_ASSERT(power_exponent >= 0);
  393. if (power_exponent == 0) {
  394. AssignUInt16(1);
  395. return;
  396. }
  397. Zero();
  398. int shifts = 0;
  399. // We expect base to be in range 2-32, and most often to be 10.
  400. // It does not make much sense to implement different algorithms for counting
  401. // the bits.
  402. while ((base & 1) == 0) {
  403. base >>= 1;
  404. shifts++;
  405. }
  406. int bit_size = 0;
  407. int tmp_base = base;
  408. while (tmp_base != 0) {
  409. tmp_base >>= 1;
  410. bit_size++;
  411. }
  412. const int final_size = bit_size * power_exponent;
  413. // 1 extra bigit for the shifting, and one for rounded final_size.
  414. EnsureCapacity(final_size / kBigitSize + 2);
  415. // Left to Right exponentiation.
  416. int mask = 1;
  417. while (power_exponent >= mask) mask <<= 1;
  418. // The mask is now pointing to the bit above the most significant 1-bit of
  419. // power_exponent.
  420. // Get rid of first 1-bit;
  421. mask >>= 2;
  422. uint64_t this_value = base;
  423. bool delayed_multiplication = false;
  424. const uint64_t max_32bits = 0xFFFFFFFF;
  425. while (mask != 0 && this_value <= max_32bits) {
  426. this_value = this_value * this_value;
  427. // Verify that there is enough space in this_value to perform the
  428. // multiplication. The first bit_size bits must be 0.
  429. if ((power_exponent & mask) != 0) {
  430. DOUBLE_CONVERSION_ASSERT(bit_size > 0);
  431. const uint64_t base_bits_mask =
  432. ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
  433. const bool high_bits_zero = (this_value & base_bits_mask) == 0;
  434. if (high_bits_zero) {
  435. this_value *= base;
  436. } else {
  437. delayed_multiplication = true;
  438. }
  439. }
  440. mask >>= 1;
  441. }
  442. AssignUInt64(this_value);
  443. if (delayed_multiplication) {
  444. MultiplyByUInt32(base);
  445. }
  446. // Now do the same thing as a bignum.
  447. while (mask != 0) {
  448. Square();
  449. if ((power_exponent & mask) != 0) {
  450. MultiplyByUInt32(base);
  451. }
  452. mask >>= 1;
  453. }
  454. // And finally add the saved shifts.
  455. ShiftLeft(shifts * power_exponent);
  456. }
  457. // Precondition: this/other < 16bit.
  458. uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
  459. DOUBLE_CONVERSION_ASSERT(IsClamped());
  460. DOUBLE_CONVERSION_ASSERT(other.IsClamped());
  461. DOUBLE_CONVERSION_ASSERT(other.used_bigits_ > 0);
  462. // Easy case: if we have less digits than the divisor than the result is 0.
  463. // Note: this handles the case where this == 0, too.
  464. if (BigitLength() < other.BigitLength()) {
  465. return 0;
  466. }
  467. Align(other);
  468. uint16_t result = 0;
  469. // Start by removing multiples of 'other' until both numbers have the same
  470. // number of digits.
  471. while (BigitLength() > other.BigitLength()) {
  472. // This naive approach is extremely inefficient if `this` divided by other
  473. // is big. This function is implemented for doubleToString where
  474. // the result should be small (less than 10).
  475. DOUBLE_CONVERSION_ASSERT(other.RawBigit(other.used_bigits_ - 1) >= ((1 << kBigitSize) / 16));
  476. DOUBLE_CONVERSION_ASSERT(RawBigit(used_bigits_ - 1) < 0x10000);
  477. // Remove the multiples of the first digit.
  478. // Example this = 23 and other equals 9. -> Remove 2 multiples.
  479. result += static_cast<uint16_t>(RawBigit(used_bigits_ - 1));
  480. SubtractTimes(other, RawBigit(used_bigits_ - 1));
  481. }
  482. DOUBLE_CONVERSION_ASSERT(BigitLength() == other.BigitLength());
  483. // Both bignums are at the same length now.
  484. // Since other has more than 0 digits we know that the access to
  485. // RawBigit(used_bigits_ - 1) is safe.
  486. const Chunk this_bigit = RawBigit(used_bigits_ - 1);
  487. const Chunk other_bigit = other.RawBigit(other.used_bigits_ - 1);
  488. if (other.used_bigits_ == 1) {
  489. // Shortcut for easy (and common) case.
  490. int quotient = this_bigit / other_bigit;
  491. RawBigit(used_bigits_ - 1) = this_bigit - other_bigit * quotient;
  492. DOUBLE_CONVERSION_ASSERT(quotient < 0x10000);
  493. result += static_cast<uint16_t>(quotient);
  494. Clamp();
  495. return result;
  496. }
  497. const int division_estimate = this_bigit / (other_bigit + 1);
  498. DOUBLE_CONVERSION_ASSERT(division_estimate < 0x10000);
  499. result += static_cast<uint16_t>(division_estimate);
  500. SubtractTimes(other, division_estimate);
  501. if (other_bigit * (division_estimate + 1) > this_bigit) {
  502. // No need to even try to subtract. Even if other's remaining digits were 0
  503. // another subtraction would be too much.
  504. return result;
  505. }
  506. while (LessEqual(other, *this)) {
  507. SubtractBignum(other);
  508. result++;
  509. }
  510. return result;
  511. }
  512. template<typename S>
  513. static int SizeInHexChars(S number) {
  514. DOUBLE_CONVERSION_ASSERT(number > 0);
  515. int result = 0;
  516. while (number != 0) {
  517. number >>= 4;
  518. result++;
  519. }
  520. return result;
  521. }
  522. static char HexCharOfValue(const int value) {
  523. DOUBLE_CONVERSION_ASSERT(0 <= value && value <= 16);
  524. if (value < 10) {
  525. return static_cast<char>(value + '0');
  526. }
  527. return static_cast<char>(value - 10 + 'A');
  528. }
  529. bool Bignum::ToHexString(char* buffer, const int buffer_size) const {
  530. DOUBLE_CONVERSION_ASSERT(IsClamped());
  531. // Each bigit must be printable as separate hex-character.
  532. DOUBLE_CONVERSION_ASSERT(kBigitSize % 4 == 0);
  533. static const int kHexCharsPerBigit = kBigitSize / 4;
  534. if (used_bigits_ == 0) {
  535. if (buffer_size < 2) {
  536. return false;
  537. }
  538. buffer[0] = '0';
  539. buffer[1] = '\0';
  540. return true;
  541. }
  542. // We add 1 for the terminating '\0' character.
  543. const int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
  544. SizeInHexChars(RawBigit(used_bigits_ - 1)) + 1;
  545. if (needed_chars > buffer_size) {
  546. return false;
  547. }
  548. int string_index = needed_chars - 1;
  549. buffer[string_index--] = '\0';
  550. for (int i = 0; i < exponent_; ++i) {
  551. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  552. buffer[string_index--] = '0';
  553. }
  554. }
  555. for (int i = 0; i < used_bigits_ - 1; ++i) {
  556. Chunk current_bigit = RawBigit(i);
  557. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  558. buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
  559. current_bigit >>= 4;
  560. }
  561. }
  562. // And finally the last bigit.
  563. Chunk most_significant_bigit = RawBigit(used_bigits_ - 1);
  564. while (most_significant_bigit != 0) {
  565. buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
  566. most_significant_bigit >>= 4;
  567. }
  568. return true;
  569. }
  570. Bignum::Chunk Bignum::BigitOrZero(const int index) const {
  571. if (index >= BigitLength()) {
  572. return 0;
  573. }
  574. if (index < exponent_) {
  575. return 0;
  576. }
  577. return RawBigit(index - exponent_);
  578. }
  579. int Bignum::Compare(const Bignum& a, const Bignum& b) {
  580. DOUBLE_CONVERSION_ASSERT(a.IsClamped());
  581. DOUBLE_CONVERSION_ASSERT(b.IsClamped());
  582. const int bigit_length_a = a.BigitLength();
  583. const int bigit_length_b = b.BigitLength();
  584. if (bigit_length_a < bigit_length_b) {
  585. return -1;
  586. }
  587. if (bigit_length_a > bigit_length_b) {
  588. return +1;
  589. }
  590. for (int i = bigit_length_a - 1; i >= (std::min)(a.exponent_, b.exponent_); --i) {
  591. const Chunk bigit_a = a.BigitOrZero(i);
  592. const Chunk bigit_b = b.BigitOrZero(i);
  593. if (bigit_a < bigit_b) {
  594. return -1;
  595. }
  596. if (bigit_a > bigit_b) {
  597. return +1;
  598. }
  599. // Otherwise they are equal up to this digit. Try the next digit.
  600. }
  601. return 0;
  602. }
  603. int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
  604. DOUBLE_CONVERSION_ASSERT(a.IsClamped());
  605. DOUBLE_CONVERSION_ASSERT(b.IsClamped());
  606. DOUBLE_CONVERSION_ASSERT(c.IsClamped());
  607. if (a.BigitLength() < b.BigitLength()) {
  608. return PlusCompare(b, a, c);
  609. }
  610. if (a.BigitLength() + 1 < c.BigitLength()) {
  611. return -1;
  612. }
  613. if (a.BigitLength() > c.BigitLength()) {
  614. return +1;
  615. }
  616. // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
  617. // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
  618. // of 'a'.
  619. if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
  620. return -1;
  621. }
  622. Chunk borrow = 0;
  623. // Starting at min_exponent all digits are == 0. So no need to compare them.
  624. const int min_exponent = (std::min)((std::min)(a.exponent_, b.exponent_), c.exponent_);
  625. for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
  626. const Chunk chunk_a = a.BigitOrZero(i);
  627. const Chunk chunk_b = b.BigitOrZero(i);
  628. const Chunk chunk_c = c.BigitOrZero(i);
  629. const Chunk sum = chunk_a + chunk_b;
  630. if (sum > chunk_c + borrow) {
  631. return +1;
  632. } else {
  633. borrow = chunk_c + borrow - sum;
  634. if (borrow > 1) {
  635. return -1;
  636. }
  637. borrow <<= kBigitSize;
  638. }
  639. }
  640. if (borrow == 0) {
  641. return 0;
  642. }
  643. return -1;
  644. }
  645. void Bignum::Clamp() {
  646. while (used_bigits_ > 0 && RawBigit(used_bigits_ - 1) == 0) {
  647. used_bigits_--;
  648. }
  649. if (used_bigits_ == 0) {
  650. // Zero.
  651. exponent_ = 0;
  652. }
  653. }
  654. void Bignum::Align(const Bignum& other) {
  655. if (exponent_ > other.exponent_) {
  656. // If "X" represents a "hidden" bigit (by the exponent) then we are in the
  657. // following case (a == this, b == other):
  658. // a: aaaaaaXXXX or a: aaaaaXXX
  659. // b: bbbbbbX b: bbbbbbbbXX
  660. // We replace some of the hidden digits (X) of a with 0 digits.
  661. // a: aaaaaa000X or a: aaaaa0XX
  662. const int zero_bigits = exponent_ - other.exponent_;
  663. EnsureCapacity(used_bigits_ + zero_bigits);
  664. for (int i = used_bigits_ - 1; i >= 0; --i) {
  665. RawBigit(i + zero_bigits) = RawBigit(i);
  666. }
  667. for (int i = 0; i < zero_bigits; ++i) {
  668. RawBigit(i) = 0;
  669. }
  670. used_bigits_ += static_cast<int16_t>(zero_bigits);
  671. exponent_ -= static_cast<int16_t>(zero_bigits);
  672. DOUBLE_CONVERSION_ASSERT(used_bigits_ >= 0);
  673. DOUBLE_CONVERSION_ASSERT(exponent_ >= 0);
  674. }
  675. }
  676. void Bignum::BigitsShiftLeft(const int shift_amount) {
  677. DOUBLE_CONVERSION_ASSERT(shift_amount < kBigitSize);
  678. DOUBLE_CONVERSION_ASSERT(shift_amount >= 0);
  679. Chunk carry = 0;
  680. for (int i = 0; i < used_bigits_; ++i) {
  681. const Chunk new_carry = RawBigit(i) >> (kBigitSize - shift_amount);
  682. RawBigit(i) = ((RawBigit(i) << shift_amount) + carry) & kBigitMask;
  683. carry = new_carry;
  684. }
  685. if (carry != 0) {
  686. RawBigit(used_bigits_) = carry;
  687. used_bigits_++;
  688. }
  689. }
  690. void Bignum::SubtractTimes(const Bignum& other, const int factor) {
  691. DOUBLE_CONVERSION_ASSERT(exponent_ <= other.exponent_);
  692. if (factor < 3) {
  693. for (int i = 0; i < factor; ++i) {
  694. SubtractBignum(other);
  695. }
  696. return;
  697. }
  698. Chunk borrow = 0;
  699. const int exponent_diff = other.exponent_ - exponent_;
  700. for (int i = 0; i < other.used_bigits_; ++i) {
  701. const DoubleChunk product = static_cast<DoubleChunk>(factor) * other.RawBigit(i);
  702. const DoubleChunk remove = borrow + product;
  703. const Chunk difference = RawBigit(i + exponent_diff) - (remove & kBigitMask);
  704. RawBigit(i + exponent_diff) = difference & kBigitMask;
  705. borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
  706. (remove >> kBigitSize));
  707. }
  708. for (int i = other.used_bigits_ + exponent_diff; i < used_bigits_; ++i) {
  709. if (borrow == 0) {
  710. return;
  711. }
  712. const Chunk difference = RawBigit(i) - borrow;
  713. RawBigit(i) = difference & kBigitMask;
  714. borrow = difference >> (kChunkSize - 1);
  715. }
  716. Clamp();
  717. }
  718. } // namespace double_conversion
  719. // ICU PATCH: Close ICU namespace
  720. U_NAMESPACE_END
  721. #endif // ICU PATCH: close #if !UCONFIG_NO_FORMATTING