Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

764 Zeilen
22 KiB

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