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