25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

766 lines
23 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 "double-conversion/bignum.h"
  28. #include "double-conversion/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. (void) value; // Mark variable as used.
  39. return 8 * sizeof(value);
  40. }
  41. // Guaranteed to lie in one Bigit.
  42. void Bignum::AssignUInt16(uint16_t value) {
  43. ASSERT(kBigitSize >= BitSize(value));
  44. Zero();
  45. if (value == 0) return;
  46. EnsureCapacity(1);
  47. bigits_[0] = value;
  48. used_digits_ = 1;
  49. }
  50. void Bignum::AssignUInt64(uint64_t value) {
  51. const int kUInt64Size = 64;
  52. Zero();
  53. if (value == 0) return;
  54. int needed_bigits = kUInt64Size / kBigitSize + 1;
  55. EnsureCapacity(needed_bigits);
  56. for (int i = 0; i < needed_bigits; ++i) {
  57. bigits_[i] = value & kBigitMask;
  58. value = value >> kBigitSize;
  59. }
  60. used_digits_ = needed_bigits;
  61. Clamp();
  62. }
  63. void Bignum::AssignBignum(const Bignum& other) {
  64. exponent_ = other.exponent_;
  65. for (int i = 0; i < other.used_digits_; ++i) {
  66. bigits_[i] = other.bigits_[i];
  67. }
  68. // Clear the excess digits (if there were any).
  69. for (int i = other.used_digits_; i < used_digits_; ++i) {
  70. bigits_[i] = 0;
  71. }
  72. used_digits_ = other.used_digits_;
  73. }
  74. static uint64_t ReadUInt64(Vector<const char> buffer,
  75. int from,
  76. int digits_to_read) {
  77. uint64_t result = 0;
  78. for (int i = from; i < from + digits_to_read; ++i) {
  79. int digit = buffer[i] - '0';
  80. ASSERT(0 <= digit && digit <= 9);
  81. result = result * 10 + digit;
  82. }
  83. return result;
  84. }
  85. void Bignum::AssignDecimalString(Vector<const char> value) {
  86. // 2^64 = 18446744073709551616 > 10^19
  87. const int kMaxUint64DecimalDigits = 19;
  88. Zero();
  89. int length = value.length();
  90. unsigned int pos = 0;
  91. // Let's just say that each digit needs 4 bits.
  92. while (length >= kMaxUint64DecimalDigits) {
  93. uint64_t digits = ReadUInt64(value, pos, kMaxUint64DecimalDigits);
  94. pos += kMaxUint64DecimalDigits;
  95. length -= kMaxUint64DecimalDigits;
  96. MultiplyByPowerOfTen(kMaxUint64DecimalDigits);
  97. AddUInt64(digits);
  98. }
  99. uint64_t digits = ReadUInt64(value, pos, length);
  100. MultiplyByPowerOfTen(length);
  101. AddUInt64(digits);
  102. Clamp();
  103. }
  104. static int HexCharValue(char c) {
  105. if ('0' <= c && c <= '9') return c - '0';
  106. if ('a' <= c && c <= 'f') return 10 + c - 'a';
  107. ASSERT('A' <= c && c <= 'F');
  108. return 10 + c - 'A';
  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 `this` divided by other
  442. // is 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. ASSERT(bigits_[used_digits_ - 1] < 0x10000);
  446. // Remove the multiples of the first digit.
  447. // Example this = 23 and other equals 9. -> Remove 2 multiples.
  448. result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
  449. SubtractTimes(other, bigits_[used_digits_ - 1]);
  450. }
  451. ASSERT(BigitLength() == other.BigitLength());
  452. // Both bignums are at the same length now.
  453. // Since other has more than 0 digits we know that the access to
  454. // bigits_[used_digits_ - 1] is safe.
  455. Chunk this_bigit = bigits_[used_digits_ - 1];
  456. Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
  457. if (other.used_digits_ == 1) {
  458. // Shortcut for easy (and common) case.
  459. int quotient = this_bigit / other_bigit;
  460. bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
  461. ASSERT(quotient < 0x10000);
  462. result += static_cast<uint16_t>(quotient);
  463. Clamp();
  464. return result;
  465. }
  466. int division_estimate = this_bigit / (other_bigit + 1);
  467. ASSERT(division_estimate < 0x10000);
  468. result += static_cast<uint16_t>(division_estimate);
  469. SubtractTimes(other, division_estimate);
  470. if (other_bigit * (division_estimate + 1) > this_bigit) {
  471. // No need to even try to subtract. Even if other's remaining digits were 0
  472. // another subtraction would be too much.
  473. return result;
  474. }
  475. while (LessEqual(other, *this)) {
  476. SubtractBignum(other);
  477. result++;
  478. }
  479. return result;
  480. }
  481. template<typename S>
  482. static int SizeInHexChars(S number) {
  483. ASSERT(number > 0);
  484. int result = 0;
  485. while (number != 0) {
  486. number >>= 4;
  487. result++;
  488. }
  489. return result;
  490. }
  491. static char HexCharOfValue(int value) {
  492. ASSERT(0 <= value && value <= 16);
  493. if (value < 10) return static_cast<char>(value + '0');
  494. return static_cast<char>(value - 10 + 'A');
  495. }
  496. bool Bignum::ToHexString(char* buffer, int buffer_size) const {
  497. ASSERT(IsClamped());
  498. // Each bigit must be printable as separate hex-character.
  499. ASSERT(kBigitSize % 4 == 0);
  500. const int kHexCharsPerBigit = kBigitSize / 4;
  501. if (used_digits_ == 0) {
  502. if (buffer_size < 2) return false;
  503. buffer[0] = '0';
  504. buffer[1] = '\0';
  505. return true;
  506. }
  507. // We add 1 for the terminating '\0' character.
  508. int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
  509. SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
  510. if (needed_chars > buffer_size) return false;
  511. int string_index = needed_chars - 1;
  512. buffer[string_index--] = '\0';
  513. for (int i = 0; i < exponent_; ++i) {
  514. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  515. buffer[string_index--] = '0';
  516. }
  517. }
  518. for (int i = 0; i < used_digits_ - 1; ++i) {
  519. Chunk current_bigit = bigits_[i];
  520. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  521. buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
  522. current_bigit >>= 4;
  523. }
  524. }
  525. // And finally the last bigit.
  526. Chunk most_significant_bigit = bigits_[used_digits_ - 1];
  527. while (most_significant_bigit != 0) {
  528. buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
  529. most_significant_bigit >>= 4;
  530. }
  531. return true;
  532. }
  533. Bignum::Chunk Bignum::BigitAt(int index) const {
  534. if (index >= BigitLength()) return 0;
  535. if (index < exponent_) return 0;
  536. return bigits_[index - exponent_];
  537. }
  538. int Bignum::Compare(const Bignum& a, const Bignum& b) {
  539. ASSERT(a.IsClamped());
  540. ASSERT(b.IsClamped());
  541. int bigit_length_a = a.BigitLength();
  542. int bigit_length_b = b.BigitLength();
  543. if (bigit_length_a < bigit_length_b) return -1;
  544. if (bigit_length_a > bigit_length_b) return +1;
  545. for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
  546. Chunk bigit_a = a.BigitAt(i);
  547. Chunk bigit_b = b.BigitAt(i);
  548. if (bigit_a < bigit_b) return -1;
  549. if (bigit_a > bigit_b) return +1;
  550. // Otherwise they are equal up to this digit. Try the next digit.
  551. }
  552. return 0;
  553. }
  554. int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
  555. ASSERT(a.IsClamped());
  556. ASSERT(b.IsClamped());
  557. ASSERT(c.IsClamped());
  558. if (a.BigitLength() < b.BigitLength()) {
  559. return PlusCompare(b, a, c);
  560. }
  561. if (a.BigitLength() + 1 < c.BigitLength()) return -1;
  562. if (a.BigitLength() > c.BigitLength()) return +1;
  563. // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
  564. // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
  565. // of 'a'.
  566. if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
  567. return -1;
  568. }
  569. Chunk borrow = 0;
  570. // Starting at min_exponent all digits are == 0. So no need to compare them.
  571. int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
  572. for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
  573. Chunk chunk_a = a.BigitAt(i);
  574. Chunk chunk_b = b.BigitAt(i);
  575. Chunk chunk_c = c.BigitAt(i);
  576. Chunk sum = chunk_a + chunk_b;
  577. if (sum > chunk_c + borrow) {
  578. return +1;
  579. } else {
  580. borrow = chunk_c + borrow - sum;
  581. if (borrow > 1) return -1;
  582. borrow <<= kBigitSize;
  583. }
  584. }
  585. if (borrow == 0) return 0;
  586. return -1;
  587. }
  588. void Bignum::Clamp() {
  589. while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
  590. used_digits_--;
  591. }
  592. if (used_digits_ == 0) {
  593. // Zero.
  594. exponent_ = 0;
  595. }
  596. }
  597. bool Bignum::IsClamped() const {
  598. return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
  599. }
  600. void Bignum::Zero() {
  601. for (int i = 0; i < used_digits_; ++i) {
  602. bigits_[i] = 0;
  603. }
  604. used_digits_ = 0;
  605. exponent_ = 0;
  606. }
  607. void Bignum::Align(const Bignum& other) {
  608. if (exponent_ > other.exponent_) {
  609. // If "X" represents a "hidden" digit (by the exponent) then we are in the
  610. // following case (a == this, b == other):
  611. // a: aaaaaaXXXX or a: aaaaaXXX
  612. // b: bbbbbbX b: bbbbbbbbXX
  613. // We replace some of the hidden digits (X) of a with 0 digits.
  614. // a: aaaaaa000X or a: aaaaa0XX
  615. int zero_digits = exponent_ - other.exponent_;
  616. EnsureCapacity(used_digits_ + zero_digits);
  617. for (int i = used_digits_ - 1; i >= 0; --i) {
  618. bigits_[i + zero_digits] = bigits_[i];
  619. }
  620. for (int i = 0; i < zero_digits; ++i) {
  621. bigits_[i] = 0;
  622. }
  623. used_digits_ += zero_digits;
  624. exponent_ -= zero_digits;
  625. ASSERT(used_digits_ >= 0);
  626. ASSERT(exponent_ >= 0);
  627. }
  628. }
  629. void Bignum::BigitsShiftLeft(int shift_amount) {
  630. ASSERT(shift_amount < kBigitSize);
  631. ASSERT(shift_amount >= 0);
  632. Chunk carry = 0;
  633. for (int i = 0; i < used_digits_; ++i) {
  634. Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
  635. bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
  636. carry = new_carry;
  637. }
  638. if (carry != 0) {
  639. bigits_[used_digits_] = carry;
  640. used_digits_++;
  641. }
  642. }
  643. void Bignum::SubtractTimes(const Bignum& other, int factor) {
  644. ASSERT(exponent_ <= other.exponent_);
  645. if (factor < 3) {
  646. for (int i = 0; i < factor; ++i) {
  647. SubtractBignum(other);
  648. }
  649. return;
  650. }
  651. Chunk borrow = 0;
  652. int exponent_diff = other.exponent_ - exponent_;
  653. for (int i = 0; i < other.used_digits_; ++i) {
  654. DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
  655. DoubleChunk remove = borrow + product;
  656. Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
  657. bigits_[i + exponent_diff] = difference & kBigitMask;
  658. borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
  659. (remove >> kBigitSize));
  660. }
  661. for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
  662. if (borrow == 0) return;
  663. Chunk difference = bigits_[i] - borrow;
  664. bigits_[i] = difference & kBigitMask;
  665. borrow = difference >> (kChunkSize - 1);
  666. }
  667. Clamp();
  668. }
  669. } // namespace double_conversion