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