bignum.cc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767
  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_buffer_(), 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_multiplication = 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. ASSERT(bit_size > 0);
  401. uint64_t base_bits_mask =
  402. ~((static_cast<uint64_t>(1) << (64 - bit_size)) - 1);
  403. bool high_bits_zero = (this_value & base_bits_mask) == 0;
  404. if (high_bits_zero) {
  405. this_value *= base;
  406. } else {
  407. delayed_multiplication = true;
  408. }
  409. }
  410. mask >>= 1;
  411. }
  412. AssignUInt64(this_value);
  413. if (delayed_multiplication) {
  414. MultiplyByUInt32(base);
  415. }
  416. // Now do the same thing as a bignum.
  417. while (mask != 0) {
  418. Square();
  419. if ((power_exponent & mask) != 0) {
  420. MultiplyByUInt32(base);
  421. }
  422. mask >>= 1;
  423. }
  424. // And finally add the saved shifts.
  425. ShiftLeft(shifts * power_exponent);
  426. }
  427. // Precondition: this/other < 16bit.
  428. uint16_t Bignum::DivideModuloIntBignum(const Bignum& other) {
  429. ASSERT(IsClamped());
  430. ASSERT(other.IsClamped());
  431. ASSERT(other.used_digits_ > 0);
  432. // Easy case: if we have less digits than the divisor than the result is 0.
  433. // Note: this handles the case where this == 0, too.
  434. if (BigitLength() < other.BigitLength()) {
  435. return 0;
  436. }
  437. Align(other);
  438. uint16_t result = 0;
  439. // Start by removing multiples of 'other' until both numbers have the same
  440. // number of digits.
  441. while (BigitLength() > other.BigitLength()) {
  442. // This naive approach is extremely inefficient if `this` divided by other
  443. // is big. This function is implemented for doubleToString where
  444. // the result should be small (less than 10).
  445. ASSERT(other.bigits_[other.used_digits_ - 1] >= ((1 << kBigitSize) / 16));
  446. ASSERT(bigits_[used_digits_ - 1] < 0x10000);
  447. // Remove the multiples of the first digit.
  448. // Example this = 23 and other equals 9. -> Remove 2 multiples.
  449. result += static_cast<uint16_t>(bigits_[used_digits_ - 1]);
  450. SubtractTimes(other, bigits_[used_digits_ - 1]);
  451. }
  452. ASSERT(BigitLength() == other.BigitLength());
  453. // Both bignums are at the same length now.
  454. // Since other has more than 0 digits we know that the access to
  455. // bigits_[used_digits_ - 1] is safe.
  456. Chunk this_bigit = bigits_[used_digits_ - 1];
  457. Chunk other_bigit = other.bigits_[other.used_digits_ - 1];
  458. if (other.used_digits_ == 1) {
  459. // Shortcut for easy (and common) case.
  460. int quotient = this_bigit / other_bigit;
  461. bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
  462. ASSERT(quotient < 0x10000);
  463. result += static_cast<uint16_t>(quotient);
  464. Clamp();
  465. return result;
  466. }
  467. int division_estimate = this_bigit / (other_bigit + 1);
  468. ASSERT(division_estimate < 0x10000);
  469. result += static_cast<uint16_t>(division_estimate);
  470. SubtractTimes(other, division_estimate);
  471. if (other_bigit * (division_estimate + 1) > this_bigit) {
  472. // No need to even try to subtract. Even if other's remaining digits were 0
  473. // another subtraction would be too much.
  474. return result;
  475. }
  476. while (LessEqual(other, *this)) {
  477. SubtractBignum(other);
  478. result++;
  479. }
  480. return result;
  481. }
  482. template<typename S>
  483. static int SizeInHexChars(S number) {
  484. ASSERT(number > 0);
  485. int result = 0;
  486. while (number != 0) {
  487. number >>= 4;
  488. result++;
  489. }
  490. return result;
  491. }
  492. static char HexCharOfValue(int value) {
  493. ASSERT(0 <= value && value <= 16);
  494. if (value < 10) return static_cast<char>(value + '0');
  495. return static_cast<char>(value - 10 + 'A');
  496. }
  497. bool Bignum::ToHexString(char* buffer, int buffer_size) const {
  498. ASSERT(IsClamped());
  499. // Each bigit must be printable as separate hex-character.
  500. ASSERT(kBigitSize % 4 == 0);
  501. const int kHexCharsPerBigit = kBigitSize / 4;
  502. if (used_digits_ == 0) {
  503. if (buffer_size < 2) return false;
  504. buffer[0] = '0';
  505. buffer[1] = '\0';
  506. return true;
  507. }
  508. // We add 1 for the terminating '\0' character.
  509. int needed_chars = (BigitLength() - 1) * kHexCharsPerBigit +
  510. SizeInHexChars(bigits_[used_digits_ - 1]) + 1;
  511. if (needed_chars > buffer_size) return false;
  512. int string_index = needed_chars - 1;
  513. buffer[string_index--] = '\0';
  514. for (int i = 0; i < exponent_; ++i) {
  515. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  516. buffer[string_index--] = '0';
  517. }
  518. }
  519. for (int i = 0; i < used_digits_ - 1; ++i) {
  520. Chunk current_bigit = bigits_[i];
  521. for (int j = 0; j < kHexCharsPerBigit; ++j) {
  522. buffer[string_index--] = HexCharOfValue(current_bigit & 0xF);
  523. current_bigit >>= 4;
  524. }
  525. }
  526. // And finally the last bigit.
  527. Chunk most_significant_bigit = bigits_[used_digits_ - 1];
  528. while (most_significant_bigit != 0) {
  529. buffer[string_index--] = HexCharOfValue(most_significant_bigit & 0xF);
  530. most_significant_bigit >>= 4;
  531. }
  532. return true;
  533. }
  534. Bignum::Chunk Bignum::BigitAt(int index) const {
  535. if (index >= BigitLength()) return 0;
  536. if (index < exponent_) return 0;
  537. return bigits_[index - exponent_];
  538. }
  539. int Bignum::Compare(const Bignum& a, const Bignum& b) {
  540. ASSERT(a.IsClamped());
  541. ASSERT(b.IsClamped());
  542. int bigit_length_a = a.BigitLength();
  543. int bigit_length_b = b.BigitLength();
  544. if (bigit_length_a < bigit_length_b) return -1;
  545. if (bigit_length_a > bigit_length_b) return +1;
  546. for (int i = bigit_length_a - 1; i >= Min(a.exponent_, b.exponent_); --i) {
  547. Chunk bigit_a = a.BigitAt(i);
  548. Chunk bigit_b = b.BigitAt(i);
  549. if (bigit_a < bigit_b) return -1;
  550. if (bigit_a > bigit_b) return +1;
  551. // Otherwise they are equal up to this digit. Try the next digit.
  552. }
  553. return 0;
  554. }
  555. int Bignum::PlusCompare(const Bignum& a, const Bignum& b, const Bignum& c) {
  556. ASSERT(a.IsClamped());
  557. ASSERT(b.IsClamped());
  558. ASSERT(c.IsClamped());
  559. if (a.BigitLength() < b.BigitLength()) {
  560. return PlusCompare(b, a, c);
  561. }
  562. if (a.BigitLength() + 1 < c.BigitLength()) return -1;
  563. if (a.BigitLength() > c.BigitLength()) return +1;
  564. // The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
  565. // 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
  566. // of 'a'.
  567. if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength()) {
  568. return -1;
  569. }
  570. Chunk borrow = 0;
  571. // Starting at min_exponent all digits are == 0. So no need to compare them.
  572. int min_exponent = Min(Min(a.exponent_, b.exponent_), c.exponent_);
  573. for (int i = c.BigitLength() - 1; i >= min_exponent; --i) {
  574. Chunk chunk_a = a.BigitAt(i);
  575. Chunk chunk_b = b.BigitAt(i);
  576. Chunk chunk_c = c.BigitAt(i);
  577. Chunk sum = chunk_a + chunk_b;
  578. if (sum > chunk_c + borrow) {
  579. return +1;
  580. } else {
  581. borrow = chunk_c + borrow - sum;
  582. if (borrow > 1) return -1;
  583. borrow <<= kBigitSize;
  584. }
  585. }
  586. if (borrow == 0) return 0;
  587. return -1;
  588. }
  589. void Bignum::Clamp() {
  590. while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) {
  591. used_digits_--;
  592. }
  593. if (used_digits_ == 0) {
  594. // Zero.
  595. exponent_ = 0;
  596. }
  597. }
  598. bool Bignum::IsClamped() const {
  599. return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
  600. }
  601. void Bignum::Zero() {
  602. for (int i = 0; i < used_digits_; ++i) {
  603. bigits_[i] = 0;
  604. }
  605. used_digits_ = 0;
  606. exponent_ = 0;
  607. }
  608. void Bignum::Align(const Bignum& other) {
  609. if (exponent_ > other.exponent_) {
  610. // If "X" represents a "hidden" digit (by the exponent) then we are in the
  611. // following case (a == this, b == other):
  612. // a: aaaaaaXXXX or a: aaaaaXXX
  613. // b: bbbbbbX b: bbbbbbbbXX
  614. // We replace some of the hidden digits (X) of a with 0 digits.
  615. // a: aaaaaa000X or a: aaaaa0XX
  616. int zero_digits = exponent_ - other.exponent_;
  617. EnsureCapacity(used_digits_ + zero_digits);
  618. for (int i = used_digits_ - 1; i >= 0; --i) {
  619. bigits_[i + zero_digits] = bigits_[i];
  620. }
  621. for (int i = 0; i < zero_digits; ++i) {
  622. bigits_[i] = 0;
  623. }
  624. used_digits_ += zero_digits;
  625. exponent_ -= zero_digits;
  626. ASSERT(used_digits_ >= 0);
  627. ASSERT(exponent_ >= 0);
  628. }
  629. }
  630. void Bignum::BigitsShiftLeft(int shift_amount) {
  631. ASSERT(shift_amount < kBigitSize);
  632. ASSERT(shift_amount >= 0);
  633. Chunk carry = 0;
  634. for (int i = 0; i < used_digits_; ++i) {
  635. Chunk new_carry = bigits_[i] >> (kBigitSize - shift_amount);
  636. bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
  637. carry = new_carry;
  638. }
  639. if (carry != 0) {
  640. bigits_[used_digits_] = carry;
  641. used_digits_++;
  642. }
  643. }
  644. void Bignum::SubtractTimes(const Bignum& other, int factor) {
  645. ASSERT(exponent_ <= other.exponent_);
  646. if (factor < 3) {
  647. for (int i = 0; i < factor; ++i) {
  648. SubtractBignum(other);
  649. }
  650. return;
  651. }
  652. Chunk borrow = 0;
  653. int exponent_diff = other.exponent_ - exponent_;
  654. for (int i = 0; i < other.used_digits_; ++i) {
  655. DoubleChunk product = static_cast<DoubleChunk>(factor) * other.bigits_[i];
  656. DoubleChunk remove = borrow + product;
  657. Chunk difference = bigits_[i + exponent_diff] - (remove & kBigitMask);
  658. bigits_[i + exponent_diff] = difference & kBigitMask;
  659. borrow = static_cast<Chunk>((difference >> (kChunkSize - 1)) +
  660. (remove >> kBigitSize));
  661. }
  662. for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i) {
  663. if (borrow == 0) return;
  664. Chunk difference = bigits_[i] - borrow;
  665. bigits_[i] = difference & kBigitMask;
  666. borrow = difference >> (kChunkSize - 1);
  667. }
  668. Clamp();
  669. }
  670. } // namespace double_conversion