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