• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // © 2017 and later: Unicode, Inc. and others.
2 // License & terms of use: http://www.unicode.org/copyright.html
3 
4 #include "unicode/utypes.h"
5 
6 #if !UCONFIG_NO_FORMATTING
7 
8 #include <cstdlib>
9 #include <cmath>
10 #include <limits>
11 #include <stdlib.h>
12 
13 #include "unicode/plurrule.h"
14 #include "cmemory.h"
15 #include "number_decnum.h"
16 #include "putilimp.h"
17 #include "number_decimalquantity.h"
18 #include "number_roundingutils.h"
19 #include "double-conversion.h"
20 #include "charstr.h"
21 #include "number_utils.h"
22 #include "uassert.h"
23 #include "util.h"
24 
25 using namespace icu;
26 using namespace icu::number;
27 using namespace icu::number::impl;
28 
29 using icu::double_conversion::DoubleToStringConverter;
30 using icu::double_conversion::StringToDoubleConverter;
31 
32 namespace {
33 
34 int8_t NEGATIVE_FLAG = 1;
35 int8_t INFINITY_FLAG = 2;
36 int8_t NAN_FLAG = 4;
37 
38 /** Helper function for safe subtraction (no overflow). */
safeSubtract(int32_t a,int32_t b)39 inline int32_t safeSubtract(int32_t a, int32_t b) {
40     // Note: In C++, signed integer subtraction is undefined behavior.
41     int32_t diff = static_cast<int32_t>(static_cast<uint32_t>(a) - static_cast<uint32_t>(b));
42     if (b < 0 && diff < a) { return INT32_MAX; }
43     if (b > 0 && diff > a) { return INT32_MIN; }
44     return diff;
45 }
46 
47 static double DOUBLE_MULTIPLIERS[] = {
48         1e0,
49         1e1,
50         1e2,
51         1e3,
52         1e4,
53         1e5,
54         1e6,
55         1e7,
56         1e8,
57         1e9,
58         1e10,
59         1e11,
60         1e12,
61         1e13,
62         1e14,
63         1e15,
64         1e16,
65         1e17,
66         1e18,
67         1e19,
68         1e20,
69         1e21};
70 
71 }  // namespace
72 
73 icu::IFixedDecimal::~IFixedDecimal() = default;
74 
DecimalQuantity()75 DecimalQuantity::DecimalQuantity() {
76     setBcdToZero();
77     flags = 0;
78 }
79 
~DecimalQuantity()80 DecimalQuantity::~DecimalQuantity() {
81     if (usingBytes) {
82         uprv_free(fBCD.bcdBytes.ptr);
83         fBCD.bcdBytes.ptr = nullptr;
84         usingBytes = false;
85     }
86 }
87 
DecimalQuantity(const DecimalQuantity & other)88 DecimalQuantity::DecimalQuantity(const DecimalQuantity &other) {
89     *this = other;
90 }
91 
DecimalQuantity(DecimalQuantity && src)92 DecimalQuantity::DecimalQuantity(DecimalQuantity&& src) U_NOEXCEPT {
93     *this = std::move(src);
94 }
95 
operator =(const DecimalQuantity & other)96 DecimalQuantity &DecimalQuantity::operator=(const DecimalQuantity &other) {
97     if (this == &other) {
98         return *this;
99     }
100     copyBcdFrom(other);
101     copyFieldsFrom(other);
102     return *this;
103 }
104 
operator =(DecimalQuantity && src)105 DecimalQuantity& DecimalQuantity::operator=(DecimalQuantity&& src) U_NOEXCEPT {
106     if (this == &src) {
107         return *this;
108     }
109     moveBcdFrom(src);
110     copyFieldsFrom(src);
111     return *this;
112 }
113 
copyFieldsFrom(const DecimalQuantity & other)114 void DecimalQuantity::copyFieldsFrom(const DecimalQuantity& other) {
115     bogus = other.bogus;
116     lReqPos = other.lReqPos;
117     rReqPos = other.rReqPos;
118     scale = other.scale;
119     precision = other.precision;
120     flags = other.flags;
121     origDouble = other.origDouble;
122     origDelta = other.origDelta;
123     isApproximate = other.isApproximate;
124     exponent = other.exponent;
125 }
126 
clear()127 void DecimalQuantity::clear() {
128     lReqPos = 0;
129     rReqPos = 0;
130     flags = 0;
131     setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data
132 }
133 
setMinInteger(int32_t minInt)134 void DecimalQuantity::setMinInteger(int32_t minInt) {
135     // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
136     U_ASSERT(minInt >= 0);
137 
138     // Special behavior: do not set minInt to be less than what is already set.
139     // This is so significant digits rounding can set the integer length.
140     if (minInt < lReqPos) {
141         minInt = lReqPos;
142     }
143 
144     // Save values into internal state
145     lReqPos = minInt;
146 }
147 
setMinFraction(int32_t minFrac)148 void DecimalQuantity::setMinFraction(int32_t minFrac) {
149     // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
150     U_ASSERT(minFrac >= 0);
151 
152     // Save values into internal state
153     // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE
154     rReqPos = -minFrac;
155 }
156 
applyMaxInteger(int32_t maxInt)157 void DecimalQuantity::applyMaxInteger(int32_t maxInt) {
158     // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
159     U_ASSERT(maxInt >= 0);
160 
161     if (precision == 0) {
162         return;
163     }
164 
165     if (maxInt <= scale) {
166         setBcdToZero();
167         return;
168     }
169 
170     int32_t magnitude = getMagnitude();
171     if (maxInt <= magnitude) {
172         popFromLeft(magnitude - maxInt + 1);
173         compact();
174     }
175 }
176 
getPositionFingerprint() const177 uint64_t DecimalQuantity::getPositionFingerprint() const {
178     uint64_t fingerprint = 0;
179     fingerprint ^= (lReqPos << 16);
180     fingerprint ^= (static_cast<uint64_t>(rReqPos) << 32);
181     return fingerprint;
182 }
183 
roundToIncrement(double roundingIncrement,RoundingMode roundingMode,UErrorCode & status)184 void DecimalQuantity::roundToIncrement(double roundingIncrement, RoundingMode roundingMode,
185                                        UErrorCode& status) {
186     // Do not call this method with an increment having only a 1 or a 5 digit!
187     // Use a more efficient call to either roundToMagnitude() or roundToNickel().
188     // Check a few popular rounding increments; a more thorough check is in Java.
189     U_ASSERT(roundingIncrement != 0.01);
190     U_ASSERT(roundingIncrement != 0.05);
191     U_ASSERT(roundingIncrement != 0.1);
192     U_ASSERT(roundingIncrement != 0.5);
193     U_ASSERT(roundingIncrement != 1);
194     U_ASSERT(roundingIncrement != 5);
195 
196     DecNum incrementDN;
197     incrementDN.setTo(roundingIncrement, status);
198     if (U_FAILURE(status)) { return; }
199 
200     // Divide this DecimalQuantity by the increment, round, then multiply back.
201     divideBy(incrementDN, status);
202     if (U_FAILURE(status)) { return; }
203     roundToMagnitude(0, roundingMode, status);
204     if (U_FAILURE(status)) { return; }
205     multiplyBy(incrementDN, status);
206     if (U_FAILURE(status)) { return; }
207 }
208 
multiplyBy(const DecNum & multiplicand,UErrorCode & status)209 void DecimalQuantity::multiplyBy(const DecNum& multiplicand, UErrorCode& status) {
210     if (isZeroish()) {
211         return;
212     }
213     // Convert to DecNum, multiply, and convert back.
214     DecNum decnum;
215     toDecNum(decnum, status);
216     if (U_FAILURE(status)) { return; }
217     decnum.multiplyBy(multiplicand, status);
218     if (U_FAILURE(status)) { return; }
219     setToDecNum(decnum, status);
220 }
221 
divideBy(const DecNum & divisor,UErrorCode & status)222 void DecimalQuantity::divideBy(const DecNum& divisor, UErrorCode& status) {
223     if (isZeroish()) {
224         return;
225     }
226     // Convert to DecNum, multiply, and convert back.
227     DecNum decnum;
228     toDecNum(decnum, status);
229     if (U_FAILURE(status)) { return; }
230     decnum.divideBy(divisor, status);
231     if (U_FAILURE(status)) { return; }
232     setToDecNum(decnum, status);
233 }
234 
negate()235 void DecimalQuantity::negate() {
236     flags ^= NEGATIVE_FLAG;
237 }
238 
getMagnitude() const239 int32_t DecimalQuantity::getMagnitude() const {
240     U_ASSERT(precision != 0);
241     return scale + precision - 1;
242 }
243 
adjustMagnitude(int32_t delta)244 bool DecimalQuantity::adjustMagnitude(int32_t delta) {
245     if (precision != 0) {
246         // i.e., scale += delta; origDelta += delta
247         bool overflow = uprv_add32_overflow(scale, delta, &scale);
248         overflow = uprv_add32_overflow(origDelta, delta, &origDelta) || overflow;
249         // Make sure that precision + scale won't overflow, either
250         int32_t dummy;
251         overflow = overflow || uprv_add32_overflow(scale, precision, &dummy);
252         return overflow;
253     }
254     return false;
255 }
256 
getPluralOperand(PluralOperand operand) const257 double DecimalQuantity::getPluralOperand(PluralOperand operand) const {
258     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
259     // See the comment at the top of this file explaining the "isApproximate" field.
260     U_ASSERT(!isApproximate);
261 
262     switch (operand) {
263         case PLURAL_OPERAND_I:
264             // Invert the negative sign if necessary
265             return static_cast<double>(isNegative() ? -toLong(true) : toLong(true));
266         case PLURAL_OPERAND_F:
267             return static_cast<double>(toFractionLong(true));
268         case PLURAL_OPERAND_T:
269             return static_cast<double>(toFractionLong(false));
270         case PLURAL_OPERAND_V:
271             return fractionCount();
272         case PLURAL_OPERAND_W:
273             return fractionCountWithoutTrailingZeros();
274         case PLURAL_OPERAND_E:
275             return static_cast<double>(getExponent());
276         case PLURAL_OPERAND_C:
277             // Plural operand `c` is currently an alias for `e`.
278             return static_cast<double>(getExponent());
279         default:
280             return std::abs(toDouble());
281     }
282 }
283 
getExponent() const284 int32_t DecimalQuantity::getExponent() const {
285     return exponent;
286 }
287 
adjustExponent(int delta)288 void DecimalQuantity::adjustExponent(int delta) {
289     exponent = exponent + delta;
290 }
291 
resetExponent()292 void DecimalQuantity::resetExponent() {
293     adjustMagnitude(exponent);
294     exponent = 0;
295 }
296 
hasIntegerValue() const297 bool DecimalQuantity::hasIntegerValue() const {
298     return scale >= 0;
299 }
300 
getUpperDisplayMagnitude() const301 int32_t DecimalQuantity::getUpperDisplayMagnitude() const {
302     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
303     // See the comment in the header file explaining the "isApproximate" field.
304     U_ASSERT(!isApproximate);
305 
306     int32_t magnitude = scale + precision;
307     int32_t result = (lReqPos > magnitude) ? lReqPos : magnitude;
308     return result - 1;
309 }
310 
getLowerDisplayMagnitude() const311 int32_t DecimalQuantity::getLowerDisplayMagnitude() const {
312     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
313     // See the comment in the header file explaining the "isApproximate" field.
314     U_ASSERT(!isApproximate);
315 
316     int32_t magnitude = scale;
317     int32_t result = (rReqPos < magnitude) ? rReqPos : magnitude;
318     return result;
319 }
320 
getDigit(int32_t magnitude) const321 int8_t DecimalQuantity::getDigit(int32_t magnitude) const {
322     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
323     // See the comment at the top of this file explaining the "isApproximate" field.
324     U_ASSERT(!isApproximate);
325 
326     return getDigitPos(magnitude - scale);
327 }
328 
fractionCount() const329 int32_t DecimalQuantity::fractionCount() const {
330     int32_t fractionCountWithExponent = -getLowerDisplayMagnitude() - exponent;
331     return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;
332 }
333 
fractionCountWithoutTrailingZeros() const334 int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const {
335     int32_t fractionCountWithExponent = -scale - exponent;
336     return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;  // max(-fractionCountWithExponent, 0)
337 }
338 
isNegative() const339 bool DecimalQuantity::isNegative() const {
340     return (flags & NEGATIVE_FLAG) != 0;
341 }
342 
signum() const343 Signum DecimalQuantity::signum() const {
344     bool isZero = (isZeroish() && !isInfinite());
345     bool isNeg = isNegative();
346     if (isZero && isNeg) {
347         return SIGNUM_NEG_ZERO;
348     } else if (isZero) {
349         return SIGNUM_POS_ZERO;
350     } else if (isNeg) {
351         return SIGNUM_NEG;
352     } else {
353         return SIGNUM_POS;
354     }
355 }
356 
isInfinite() const357 bool DecimalQuantity::isInfinite() const {
358     return (flags & INFINITY_FLAG) != 0;
359 }
360 
isNaN() const361 bool DecimalQuantity::isNaN() const {
362     return (flags & NAN_FLAG) != 0;
363 }
364 
isZeroish() const365 bool DecimalQuantity::isZeroish() const {
366     return precision == 0;
367 }
368 
setToInt(int32_t n)369 DecimalQuantity &DecimalQuantity::setToInt(int32_t n) {
370     setBcdToZero();
371     flags = 0;
372     if (n == INT32_MIN) {
373         flags |= NEGATIVE_FLAG;
374         // leave as INT32_MIN; handled below in _setToInt()
375     } else if (n < 0) {
376         flags |= NEGATIVE_FLAG;
377         n = -n;
378     }
379     if (n != 0) {
380         _setToInt(n);
381         compact();
382     }
383     return *this;
384 }
385 
_setToInt(int32_t n)386 void DecimalQuantity::_setToInt(int32_t n) {
387     if (n == INT32_MIN) {
388         readLongToBcd(-static_cast<int64_t>(n));
389     } else {
390         readIntToBcd(n);
391     }
392 }
393 
setToLong(int64_t n)394 DecimalQuantity &DecimalQuantity::setToLong(int64_t n) {
395     setBcdToZero();
396     flags = 0;
397     if (n < 0 && n > INT64_MIN) {
398         flags |= NEGATIVE_FLAG;
399         n = -n;
400     }
401     if (n != 0) {
402         _setToLong(n);
403         compact();
404     }
405     return *this;
406 }
407 
_setToLong(int64_t n)408 void DecimalQuantity::_setToLong(int64_t n) {
409     if (n == INT64_MIN) {
410         DecNum decnum;
411         UErrorCode localStatus = U_ZERO_ERROR;
412         decnum.setTo("9.223372036854775808E+18", localStatus);
413         if (U_FAILURE(localStatus)) { return; } // unexpected
414         flags |= NEGATIVE_FLAG;
415         readDecNumberToBcd(decnum);
416     } else if (n <= INT32_MAX) {
417         readIntToBcd(static_cast<int32_t>(n));
418     } else {
419         readLongToBcd(n);
420     }
421 }
422 
setToDouble(double n)423 DecimalQuantity &DecimalQuantity::setToDouble(double n) {
424     setBcdToZero();
425     flags = 0;
426     // signbit() from <math.h> handles +0.0 vs -0.0
427     if (std::signbit(n)) {
428         flags |= NEGATIVE_FLAG;
429         n = -n;
430     }
431     if (std::isnan(n) != 0) {
432         flags |= NAN_FLAG;
433     } else if (std::isfinite(n) == 0) {
434         flags |= INFINITY_FLAG;
435     } else if (n != 0) {
436         _setToDoubleFast(n);
437         compact();
438     }
439     return *this;
440 }
441 
_setToDoubleFast(double n)442 void DecimalQuantity::_setToDoubleFast(double n) {
443     isApproximate = true;
444     origDouble = n;
445     origDelta = 0;
446 
447     // Make sure the double is an IEEE 754 double.  If not, fall back to the slow path right now.
448     // TODO: Make a fast path for other types of doubles.
449     if (!std::numeric_limits<double>::is_iec559) {
450         convertToAccurateDouble();
451         return;
452     }
453 
454     // To get the bits from the double, use memcpy, which takes care of endianness.
455     uint64_t ieeeBits;
456     uprv_memcpy(&ieeeBits, &n, sizeof(n));
457     int32_t exponent = static_cast<int32_t>((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff;
458 
459     // Not all integers can be represented exactly for exponent > 52
460     if (exponent <= 52 && static_cast<int64_t>(n) == n) {
461         _setToLong(static_cast<int64_t>(n));
462         return;
463     }
464 
465     if (exponent == -1023 || exponent == 1024) {
466         // The extreme values of exponent are special; use slow path.
467         convertToAccurateDouble();
468         return;
469     }
470 
471     // 3.3219... is log2(10)
472     auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809488736234787031942948939017586);
473     if (fracLength >= 0) {
474         int32_t i = fracLength;
475         // 1e22 is the largest exact double.
476         for (; i >= 22; i -= 22) n *= 1e22;
477         n *= DOUBLE_MULTIPLIERS[i];
478     } else {
479         int32_t i = fracLength;
480         // 1e22 is the largest exact double.
481         for (; i <= -22; i += 22) n /= 1e22;
482         n /= DOUBLE_MULTIPLIERS[-i];
483     }
484     auto result = static_cast<int64_t>(uprv_round(n));
485     if (result != 0) {
486         _setToLong(result);
487         scale -= fracLength;
488     }
489 }
490 
convertToAccurateDouble()491 void DecimalQuantity::convertToAccurateDouble() {
492     U_ASSERT(origDouble != 0);
493     int32_t delta = origDelta;
494 
495     // Call the slow oracle function (Double.toString in Java, DoubleToAscii in C++).
496     char buffer[DoubleToStringConverter::kBase10MaximalLength + 1];
497     bool sign; // unused; always positive
498     int32_t length;
499     int32_t point;
500     DoubleToStringConverter::DoubleToAscii(
501         origDouble,
502         DoubleToStringConverter::DtoaMode::SHORTEST,
503         0,
504         buffer,
505         sizeof(buffer),
506         &sign,
507         &length,
508         &point
509     );
510 
511     setBcdToZero();
512     readDoubleConversionToBcd(buffer, length, point);
513     scale += delta;
514     explicitExactDouble = true;
515 }
516 
setToDecNumber(StringPiece n,UErrorCode & status)517 DecimalQuantity &DecimalQuantity::setToDecNumber(StringPiece n, UErrorCode& status) {
518     setBcdToZero();
519     flags = 0;
520 
521     // Compute the decNumber representation
522     DecNum decnum;
523     decnum.setTo(n, status);
524 
525     _setToDecNum(decnum, status);
526     return *this;
527 }
528 
setToDecNum(const DecNum & decnum,UErrorCode & status)529 DecimalQuantity& DecimalQuantity::setToDecNum(const DecNum& decnum, UErrorCode& status) {
530     setBcdToZero();
531     flags = 0;
532 
533     _setToDecNum(decnum, status);
534     return *this;
535 }
536 
_setToDecNum(const DecNum & decnum,UErrorCode & status)537 void DecimalQuantity::_setToDecNum(const DecNum& decnum, UErrorCode& status) {
538     if (U_FAILURE(status)) { return; }
539     if (decnum.isNegative()) {
540         flags |= NEGATIVE_FLAG;
541     }
542     if (decnum.isNaN()) {
543         flags |= NAN_FLAG;
544     } else if (decnum.isInfinity()) {
545         flags |= INFINITY_FLAG;
546     } else if (!decnum.isZero()) {
547         readDecNumberToBcd(decnum);
548         compact();
549     }
550 }
551 
toLong(bool truncateIfOverflow) const552 int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const {
553     // NOTE: Call sites should be guarded by fitsInLong(), like this:
554     // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ }
555     // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits.
556     uint64_t result = 0L;
557     int32_t upperMagnitude = exponent + scale + precision - 1;
558     if (truncateIfOverflow) {
559         upperMagnitude = std::min(upperMagnitude, 17);
560     }
561     for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) {
562         result = result * 10 + getDigitPos(magnitude - scale - exponent);
563     }
564     if (isNegative()) {
565         return static_cast<int64_t>(0LL - result); // i.e., -result
566     }
567     return static_cast<int64_t>(result);
568 }
569 
toFractionLong(bool includeTrailingZeros) const570 uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const {
571     uint64_t result = 0L;
572     int32_t magnitude = -1 - exponent;
573     int32_t lowerMagnitude = scale;
574     if (includeTrailingZeros) {
575         lowerMagnitude = std::min(lowerMagnitude, rReqPos);
576     }
577     for (; magnitude >= lowerMagnitude && result <= 1e18L; magnitude--) {
578         result = result * 10 + getDigitPos(magnitude - scale);
579     }
580     // Remove trailing zeros; this can happen during integer overflow cases.
581     if (!includeTrailingZeros) {
582         while (result > 0 && (result % 10) == 0) {
583             result /= 10;
584         }
585     }
586     return result;
587 }
588 
fitsInLong(bool ignoreFraction) const589 bool DecimalQuantity::fitsInLong(bool ignoreFraction) const {
590     if (isInfinite() || isNaN()) {
591         return false;
592     }
593     if (isZeroish()) {
594         return true;
595     }
596     if (exponent + scale < 0 && !ignoreFraction) {
597         return false;
598     }
599     int magnitude = getMagnitude();
600     if (magnitude < 18) {
601         return true;
602     }
603     if (magnitude > 18) {
604         return false;
605     }
606     // Hard case: the magnitude is 10^18.
607     // The largest int64 is: 9,223,372,036,854,775,807
608     for (int p = 0; p < precision; p++) {
609         int8_t digit = getDigit(18 - p);
610         static int8_t INT64_BCD[] = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 };
611         if (digit < INT64_BCD[p]) {
612             return true;
613         } else if (digit > INT64_BCD[p]) {
614             return false;
615         }
616     }
617     // Exactly equal to max long plus one.
618     return isNegative();
619 }
620 
toDouble() const621 double DecimalQuantity::toDouble() const {
622     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
623     // See the comment in the header file explaining the "isApproximate" field.
624     U_ASSERT(!isApproximate);
625 
626     if (isNaN()) {
627         return NAN;
628     } else if (isInfinite()) {
629         return isNegative() ? -INFINITY : INFINITY;
630     }
631 
632     // We are processing well-formed input, so we don't need any special options to StringToDoubleConverter.
633     StringToDoubleConverter converter(0, 0, 0, "", "");
634     UnicodeString numberString = this->toScientificString();
635     int32_t count;
636     return converter.StringToDouble(
637             reinterpret_cast<const uint16_t*>(numberString.getBuffer()),
638             numberString.length(),
639             &count);
640 }
641 
toDecNum(DecNum & output,UErrorCode & status) const642 DecNum& DecimalQuantity::toDecNum(DecNum& output, UErrorCode& status) const {
643     // Special handling for zero
644     if (precision == 0) {
645         output.setTo("0", status);
646         return output;
647     }
648 
649     // Use the BCD constructor. We need to do a little bit of work to convert, though.
650     // The decNumber constructor expects most-significant first, but we store least-significant first.
651     MaybeStackArray<uint8_t, 20> ubcd(precision, status);
652     if (U_FAILURE(status)) {
653         return output;
654     }
655     for (int32_t m = 0; m < precision; m++) {
656         ubcd[precision - m - 1] = static_cast<uint8_t>(getDigitPos(m));
657     }
658     output.setTo(ubcd.getAlias(), precision, scale, isNegative(), status);
659     return output;
660 }
661 
truncate()662 void DecimalQuantity::truncate() {
663     if (scale < 0) {
664         shiftRight(-scale);
665         scale = 0;
666         compact();
667     }
668 }
669 
roundToNickel(int32_t magnitude,RoundingMode roundingMode,UErrorCode & status)670 void DecimalQuantity::roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
671     roundToMagnitude(magnitude, roundingMode, true, status);
672 }
673 
roundToMagnitude(int32_t magnitude,RoundingMode roundingMode,UErrorCode & status)674 void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
675     roundToMagnitude(magnitude, roundingMode, false, status);
676 }
677 
roundToMagnitude(int32_t magnitude,RoundingMode roundingMode,bool nickel,UErrorCode & status)678 void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status) {
679     // The position in the BCD at which rounding will be performed; digits to the right of position
680     // will be rounded away.
681     int position = safeSubtract(magnitude, scale);
682 
683     // "trailing" = least significant digit to the left of rounding
684     int8_t trailingDigit = getDigitPos(position);
685 
686     if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
687         // All digits are to the left of the rounding magnitude.
688     } else if (precision == 0) {
689         // No rounding for zero.
690     } else {
691         // Perform rounding logic.
692         // "leading" = most significant digit to the right of rounding
693         int8_t leadingDigit = getDigitPos(safeSubtract(position, 1));
694 
695         // Compute which section of the number we are in.
696         // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles)
697         // LOWER means we are between the bottom edge and the midpoint, like 1.391
698         // MIDPOINT means we are exactly in the middle, like 1.500
699         // UPPER means we are between the midpoint and the top edge, like 1.916
700         roundingutils::Section section;
701         if (!isApproximate) {
702             if (nickel && trailingDigit != 2 && trailingDigit != 7) {
703                 // Nickel rounding, and not at .02x or .07x
704                 if (trailingDigit < 2) {
705                     // .00, .01 => down to .00
706                     section = roundingutils::SECTION_LOWER;
707                 } else if (trailingDigit < 5) {
708                     // .03, .04 => up to .05
709                     section = roundingutils::SECTION_UPPER;
710                 } else if (trailingDigit < 7) {
711                     // .05, .06 => down to .05
712                     section = roundingutils::SECTION_LOWER;
713                 } else {
714                     // .08, .09 => up to .10
715                     section = roundingutils::SECTION_UPPER;
716                 }
717             } else if (leadingDigit < 5) {
718                 // Includes nickel rounding .020-.024 and .070-.074
719                 section = roundingutils::SECTION_LOWER;
720             } else if (leadingDigit > 5) {
721                 // Includes nickel rounding .026-.029 and .076-.079
722                 section = roundingutils::SECTION_UPPER;
723             } else {
724                 // Includes nickel rounding .025 and .075
725                 section = roundingutils::SECTION_MIDPOINT;
726                 for (int p = safeSubtract(position, 2); p >= 0; p--) {
727                     if (getDigitPos(p) != 0) {
728                         section = roundingutils::SECTION_UPPER;
729                         break;
730                     }
731                 }
732             }
733         } else {
734             int32_t p = safeSubtract(position, 2);
735             int32_t minP = uprv_max(0, precision - 14);
736             if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
737                 section = roundingutils::SECTION_LOWER_EDGE;
738                 for (; p >= minP; p--) {
739                     if (getDigitPos(p) != 0) {
740                         section = roundingutils::SECTION_LOWER;
741                         break;
742                     }
743                 }
744             } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
745                 section = roundingutils::SECTION_MIDPOINT;
746                 for (; p >= minP; p--) {
747                     if (getDigitPos(p) != 9) {
748                         section = roundingutils::SECTION_LOWER;
749                         break;
750                     }
751                 }
752             } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
753                 section = roundingutils::SECTION_MIDPOINT;
754                 for (; p >= minP; p--) {
755                     if (getDigitPos(p) != 0) {
756                         section = roundingutils::SECTION_UPPER;
757                         break;
758                     }
759                 }
760             } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) {
761                 section = roundingutils::SECTION_UPPER_EDGE;
762                 for (; p >= minP; p--) {
763                     if (getDigitPos(p) != 9) {
764                         section = roundingutils::SECTION_UPPER;
765                         break;
766                     }
767                 }
768             } else if (nickel && trailingDigit != 2 && trailingDigit != 7) {
769                 // Nickel rounding, and not at .02x or .07x
770                 if (trailingDigit < 2) {
771                     // .00, .01 => down to .00
772                     section = roundingutils::SECTION_LOWER;
773                 } else if (trailingDigit < 5) {
774                     // .03, .04 => up to .05
775                     section = roundingutils::SECTION_UPPER;
776                 } else if (trailingDigit < 7) {
777                     // .05, .06 => down to .05
778                     section = roundingutils::SECTION_LOWER;
779                 } else {
780                     // .08, .09 => up to .10
781                     section = roundingutils::SECTION_UPPER;
782                 }
783             } else if (leadingDigit < 5) {
784                 // Includes nickel rounding .020-.024 and .070-.074
785                 section = roundingutils::SECTION_LOWER;
786             } else {
787                 // Includes nickel rounding .026-.029 and .076-.079
788                 section = roundingutils::SECTION_UPPER;
789             }
790 
791             bool roundsAtMidpoint = roundingutils::roundsAtMidpoint(roundingMode);
792             if (safeSubtract(position, 1) < precision - 14 ||
793                 (roundsAtMidpoint && section == roundingutils::SECTION_MIDPOINT) ||
794                 (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) {
795                 // Oops! This means that we have to get the exact representation of the double,
796                 // because the zone of uncertainty is along the rounding boundary.
797                 convertToAccurateDouble();
798                 roundToMagnitude(magnitude, roundingMode, nickel, status); // start over
799                 return;
800             }
801 
802             // Turn off the approximate double flag, since the value is now confirmed to be exact.
803             isApproximate = false;
804             origDouble = 0.0;
805             origDelta = 0;
806 
807             if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
808                 // All digits are to the left of the rounding magnitude.
809                 return;
810             }
811 
812             // Good to continue rounding.
813             if (section == -1) { section = roundingutils::SECTION_LOWER; }
814             if (section == -2) { section = roundingutils::SECTION_UPPER; }
815         }
816 
817         // Nickel rounding "half even" goes to the nearest whole (away from the 5).
818         bool isEven = nickel
819                 ? (trailingDigit < 2 || trailingDigit > 7
820                         || (trailingDigit == 2 && section != roundingutils::SECTION_UPPER)
821                         || (trailingDigit == 7 && section == roundingutils::SECTION_UPPER))
822                 : (trailingDigit % 2) == 0;
823 
824         bool roundDown = roundingutils::getRoundingDirection(isEven,
825                 isNegative(),
826                 section,
827                 roundingMode,
828                 status);
829         if (U_FAILURE(status)) {
830             return;
831         }
832 
833         // Perform truncation
834         if (position >= precision) {
835             U_ASSERT(trailingDigit == 0);
836             setBcdToZero();
837             scale = magnitude;
838         } else {
839             shiftRight(position);
840         }
841 
842         if (nickel) {
843             if (trailingDigit < 5 && roundDown) {
844                 setDigitPos(0, 0);
845                 compact();
846                 return;
847             } else if (trailingDigit >= 5 && !roundDown) {
848                 setDigitPos(0, 9);
849                 trailingDigit = 9;
850                 // do not return: use the bubbling logic below
851             } else {
852                 setDigitPos(0, 5);
853                 // If the quantity was set to 0, we may need to restore a digit.
854                 if (precision == 0) {
855                     precision = 1;
856                 }
857                 // compact not necessary: digit at position 0 is nonzero
858                 return;
859             }
860         }
861 
862         // Bubble the result to the higher digits
863         if (!roundDown) {
864             if (trailingDigit == 9) {
865                 int bubblePos = 0;
866                 // Note: in the long implementation, the most digits BCD can have at this point is
867                 // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe.
868                 for (; getDigitPos(bubblePos) == 9; bubblePos++) {}
869                 shiftRight(bubblePos); // shift off the trailing 9s
870             }
871             int8_t digit0 = getDigitPos(0);
872             U_ASSERT(digit0 != 9);
873             setDigitPos(0, static_cast<int8_t>(digit0 + 1));
874             precision += 1; // in case an extra digit got added
875         }
876 
877         compact();
878     }
879 }
880 
roundToInfinity()881 void DecimalQuantity::roundToInfinity() {
882     if (isApproximate) {
883         convertToAccurateDouble();
884     }
885 }
886 
appendDigit(int8_t value,int32_t leadingZeros,bool appendAsInteger)887 void DecimalQuantity::appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger) {
888     U_ASSERT(leadingZeros >= 0);
889 
890     // Zero requires special handling to maintain the invariant that the least-significant digit
891     // in the BCD is nonzero.
892     if (value == 0) {
893         if (appendAsInteger && precision != 0) {
894             scale += leadingZeros + 1;
895         }
896         return;
897     }
898 
899     // Deal with trailing zeros
900     if (scale > 0) {
901         leadingZeros += scale;
902         if (appendAsInteger) {
903             scale = 0;
904         }
905     }
906 
907     // Append digit
908     shiftLeft(leadingZeros + 1);
909     setDigitPos(0, value);
910 
911     // Fix scale if in integer mode
912     if (appendAsInteger) {
913         scale += leadingZeros + 1;
914     }
915 }
916 
toPlainString() const917 UnicodeString DecimalQuantity::toPlainString() const {
918     U_ASSERT(!isApproximate);
919     UnicodeString sb;
920     if (isNegative()) {
921         sb.append(u'-');
922     }
923     if (precision == 0) {
924         sb.append(u'0');
925         return sb;
926     }
927     int32_t upper = scale + precision + exponent - 1;
928     int32_t lower = scale + exponent;
929     if (upper < lReqPos - 1) {
930         upper = lReqPos - 1;
931     }
932     if (lower > rReqPos) {
933         lower = rReqPos;
934     }
935     int32_t p = upper;
936     if (p < 0) {
937         sb.append(u'0');
938     }
939     for (; p >= 0; p--) {
940         sb.append(u'0' + getDigitPos(p - scale - exponent));
941     }
942     if (lower < 0) {
943         sb.append(u'.');
944     }
945     for(; p >= lower; p--) {
946         sb.append(u'0' + getDigitPos(p - scale - exponent));
947     }
948     return sb;
949 }
950 
toScientificString() const951 UnicodeString DecimalQuantity::toScientificString() const {
952     U_ASSERT(!isApproximate);
953     UnicodeString result;
954     if (isNegative()) {
955         result.append(u'-');
956     }
957     if (precision == 0) {
958         result.append(u"0E+0", -1);
959         return result;
960     }
961     int32_t upperPos = precision - 1;
962     int32_t lowerPos = 0;
963     int32_t p = upperPos;
964     result.append(u'0' + getDigitPos(p));
965     if ((--p) >= lowerPos) {
966         result.append(u'.');
967         for (; p >= lowerPos; p--) {
968             result.append(u'0' + getDigitPos(p));
969         }
970     }
971     result.append(u'E');
972     int32_t _scale = upperPos + scale + exponent;
973     if (_scale == INT32_MIN) {
974         result.append({u"-2147483648", -1});
975         return result;
976     } else if (_scale < 0) {
977         _scale *= -1;
978         result.append(u'-');
979     } else {
980         result.append(u'+');
981     }
982     if (_scale == 0) {
983         result.append(u'0');
984     }
985     int32_t insertIndex = result.length();
986     while (_scale > 0) {
987         std::div_t res = std::div(_scale, 10);
988         result.insert(insertIndex, u'0' + res.rem);
989         _scale = res.quot;
990     }
991     return result;
992 }
993 
994 ////////////////////////////////////////////////////
995 /// End of DecimalQuantity_AbstractBCD.java      ///
996 /// Start of DecimalQuantity_DualStorageBCD.java ///
997 ////////////////////////////////////////////////////
998 
getDigitPos(int32_t position) const999 int8_t DecimalQuantity::getDigitPos(int32_t position) const {
1000     if (usingBytes) {
1001         if (position < 0 || position >= precision) { return 0; }
1002         return fBCD.bcdBytes.ptr[position];
1003     } else {
1004         if (position < 0 || position >= 16) { return 0; }
1005         return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf);
1006     }
1007 }
1008 
setDigitPos(int32_t position,int8_t value)1009 void DecimalQuantity::setDigitPos(int32_t position, int8_t value) {
1010     U_ASSERT(position >= 0);
1011     if (usingBytes) {
1012         ensureCapacity(position + 1);
1013         fBCD.bcdBytes.ptr[position] = value;
1014     } else if (position >= 16) {
1015         switchStorage();
1016         ensureCapacity(position + 1);
1017         fBCD.bcdBytes.ptr[position] = value;
1018     } else {
1019         int shift = position * 4;
1020         fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift);
1021     }
1022 }
1023 
shiftLeft(int32_t numDigits)1024 void DecimalQuantity::shiftLeft(int32_t numDigits) {
1025     if (!usingBytes && precision + numDigits > 16) {
1026         switchStorage();
1027     }
1028     if (usingBytes) {
1029         ensureCapacity(precision + numDigits);
1030         uprv_memmove(fBCD.bcdBytes.ptr + numDigits, fBCD.bcdBytes.ptr, precision);
1031         uprv_memset(fBCD.bcdBytes.ptr, 0, numDigits);
1032     } else {
1033         fBCD.bcdLong <<= (numDigits * 4);
1034     }
1035     scale -= numDigits;
1036     precision += numDigits;
1037 }
1038 
shiftRight(int32_t numDigits)1039 void DecimalQuantity::shiftRight(int32_t numDigits) {
1040     if (usingBytes) {
1041         int i = 0;
1042         for (; i < precision - numDigits; i++) {
1043             fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i + numDigits];
1044         }
1045         for (; i < precision; i++) {
1046             fBCD.bcdBytes.ptr[i] = 0;
1047         }
1048     } else {
1049         fBCD.bcdLong >>= (numDigits * 4);
1050     }
1051     scale += numDigits;
1052     precision -= numDigits;
1053 }
1054 
popFromLeft(int32_t numDigits)1055 void DecimalQuantity::popFromLeft(int32_t numDigits) {
1056     U_ASSERT(numDigits <= precision);
1057     if (usingBytes) {
1058         int i = precision - 1;
1059         for (; i >= precision - numDigits; i--) {
1060             fBCD.bcdBytes.ptr[i] = 0;
1061         }
1062     } else {
1063         fBCD.bcdLong &= (static_cast<uint64_t>(1) << ((precision - numDigits) * 4)) - 1;
1064     }
1065     precision -= numDigits;
1066 }
1067 
setBcdToZero()1068 void DecimalQuantity::setBcdToZero() {
1069     if (usingBytes) {
1070         uprv_free(fBCD.bcdBytes.ptr);
1071         fBCD.bcdBytes.ptr = nullptr;
1072         usingBytes = false;
1073     }
1074     fBCD.bcdLong = 0L;
1075     scale = 0;
1076     precision = 0;
1077     isApproximate = false;
1078     origDouble = 0;
1079     origDelta = 0;
1080     exponent = 0;
1081 }
1082 
readIntToBcd(int32_t n)1083 void DecimalQuantity::readIntToBcd(int32_t n) {
1084     U_ASSERT(n != 0);
1085     // ints always fit inside the long implementation.
1086     uint64_t result = 0L;
1087     int i = 16;
1088     for (; n != 0; n /= 10, i--) {
1089         result = (result >> 4) + ((static_cast<uint64_t>(n) % 10) << 60);
1090     }
1091     U_ASSERT(!usingBytes);
1092     fBCD.bcdLong = result >> (i * 4);
1093     scale = 0;
1094     precision = 16 - i;
1095 }
1096 
readLongToBcd(int64_t n)1097 void DecimalQuantity::readLongToBcd(int64_t n) {
1098     U_ASSERT(n != 0);
1099     if (n >= 10000000000000000L) {
1100         ensureCapacity();
1101         int i = 0;
1102         for (; n != 0L; n /= 10L, i++) {
1103             fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(n % 10);
1104         }
1105         U_ASSERT(usingBytes);
1106         scale = 0;
1107         precision = i;
1108     } else {
1109         uint64_t result = 0L;
1110         int i = 16;
1111         for (; n != 0L; n /= 10L, i--) {
1112             result = (result >> 4) + ((n % 10) << 60);
1113         }
1114         U_ASSERT(i >= 0);
1115         U_ASSERT(!usingBytes);
1116         fBCD.bcdLong = result >> (i * 4);
1117         scale = 0;
1118         precision = 16 - i;
1119     }
1120 }
1121 
readDecNumberToBcd(const DecNum & decnum)1122 void DecimalQuantity::readDecNumberToBcd(const DecNum& decnum) {
1123     const decNumber* dn = decnum.getRawDecNumber();
1124     if (dn->digits > 16) {
1125         ensureCapacity(dn->digits);
1126         for (int32_t i = 0; i < dn->digits; i++) {
1127             fBCD.bcdBytes.ptr[i] = dn->lsu[i];
1128         }
1129     } else {
1130         uint64_t result = 0L;
1131         for (int32_t i = 0; i < dn->digits; i++) {
1132             result |= static_cast<uint64_t>(dn->lsu[i]) << (4 * i);
1133         }
1134         fBCD.bcdLong = result;
1135     }
1136     scale = dn->exponent;
1137     precision = dn->digits;
1138 }
1139 
readDoubleConversionToBcd(const char * buffer,int32_t length,int32_t point)1140 void DecimalQuantity::readDoubleConversionToBcd(
1141         const char* buffer, int32_t length, int32_t point) {
1142     // NOTE: Despite the fact that double-conversion's API is called
1143     // "DoubleToAscii", they actually use '0' (as opposed to u8'0').
1144     if (length > 16) {
1145         ensureCapacity(length);
1146         for (int32_t i = 0; i < length; i++) {
1147             fBCD.bcdBytes.ptr[i] = buffer[length-i-1] - '0';
1148         }
1149     } else {
1150         uint64_t result = 0L;
1151         for (int32_t i = 0; i < length; i++) {
1152             result |= static_cast<uint64_t>(buffer[length-i-1] - '0') << (4 * i);
1153         }
1154         fBCD.bcdLong = result;
1155     }
1156     scale = point - length;
1157     precision = length;
1158 }
1159 
compact()1160 void DecimalQuantity::compact() {
1161     if (usingBytes) {
1162         int32_t delta = 0;
1163         for (; delta < precision && fBCD.bcdBytes.ptr[delta] == 0; delta++);
1164         if (delta == precision) {
1165             // Number is zero
1166             setBcdToZero();
1167             return;
1168         } else {
1169             // Remove trailing zeros
1170             shiftRight(delta);
1171         }
1172 
1173         // Compute precision
1174         int32_t leading = precision - 1;
1175         for (; leading >= 0 && fBCD.bcdBytes.ptr[leading] == 0; leading--);
1176         precision = leading + 1;
1177 
1178         // Switch storage mechanism if possible
1179         if (precision <= 16) {
1180             switchStorage();
1181         }
1182 
1183     } else {
1184         if (fBCD.bcdLong == 0L) {
1185             // Number is zero
1186             setBcdToZero();
1187             return;
1188         }
1189 
1190         // Compact the number (remove trailing zeros)
1191         // TODO: Use a more efficient algorithm here and below. There is a logarithmic one.
1192         int32_t delta = 0;
1193         for (; delta < precision && getDigitPos(delta) == 0; delta++);
1194         fBCD.bcdLong >>= delta * 4;
1195         scale += delta;
1196 
1197         // Compute precision
1198         int32_t leading = precision - 1;
1199         for (; leading >= 0 && getDigitPos(leading) == 0; leading--);
1200         precision = leading + 1;
1201     }
1202 }
1203 
ensureCapacity()1204 void DecimalQuantity::ensureCapacity() {
1205     ensureCapacity(40);
1206 }
1207 
ensureCapacity(int32_t capacity)1208 void DecimalQuantity::ensureCapacity(int32_t capacity) {
1209     if (capacity == 0) { return; }
1210     int32_t oldCapacity = usingBytes ? fBCD.bcdBytes.len : 0;
1211     if (!usingBytes) {
1212         // TODO: There is nothing being done to check for memory allocation failures.
1213         // TODO: Consider indexing by nybbles instead of bytes in C++, so that we can
1214         // make these arrays half the size.
1215         fBCD.bcdBytes.ptr = static_cast<int8_t*>(uprv_malloc(capacity * sizeof(int8_t)));
1216         fBCD.bcdBytes.len = capacity;
1217         // Initialize the byte array to zeros (this is done automatically in Java)
1218         uprv_memset(fBCD.bcdBytes.ptr, 0, capacity * sizeof(int8_t));
1219     } else if (oldCapacity < capacity) {
1220         auto bcd1 = static_cast<int8_t*>(uprv_malloc(capacity * 2 * sizeof(int8_t)));
1221         uprv_memcpy(bcd1, fBCD.bcdBytes.ptr, oldCapacity * sizeof(int8_t));
1222         // Initialize the rest of the byte array to zeros (this is done automatically in Java)
1223         uprv_memset(bcd1 + oldCapacity, 0, (capacity - oldCapacity) * sizeof(int8_t));
1224         uprv_free(fBCD.bcdBytes.ptr);
1225         fBCD.bcdBytes.ptr = bcd1;
1226         fBCD.bcdBytes.len = capacity * 2;
1227     }
1228     usingBytes = true;
1229 }
1230 
switchStorage()1231 void DecimalQuantity::switchStorage() {
1232     if (usingBytes) {
1233         // Change from bytes to long
1234         uint64_t bcdLong = 0L;
1235         for (int i = precision - 1; i >= 0; i--) {
1236             bcdLong <<= 4;
1237             bcdLong |= fBCD.bcdBytes.ptr[i];
1238         }
1239         uprv_free(fBCD.bcdBytes.ptr);
1240         fBCD.bcdBytes.ptr = nullptr;
1241         fBCD.bcdLong = bcdLong;
1242         usingBytes = false;
1243     } else {
1244         // Change from long to bytes
1245         // Copy the long into a local variable since it will get munged when we allocate the bytes
1246         uint64_t bcdLong = fBCD.bcdLong;
1247         ensureCapacity();
1248         for (int i = 0; i < precision; i++) {
1249             fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(bcdLong & 0xf);
1250             bcdLong >>= 4;
1251         }
1252         U_ASSERT(usingBytes);
1253     }
1254 }
1255 
copyBcdFrom(const DecimalQuantity & other)1256 void DecimalQuantity::copyBcdFrom(const DecimalQuantity &other) {
1257     setBcdToZero();
1258     if (other.usingBytes) {
1259         ensureCapacity(other.precision);
1260         uprv_memcpy(fBCD.bcdBytes.ptr, other.fBCD.bcdBytes.ptr, other.precision * sizeof(int8_t));
1261     } else {
1262         fBCD.bcdLong = other.fBCD.bcdLong;
1263     }
1264 }
1265 
moveBcdFrom(DecimalQuantity & other)1266 void DecimalQuantity::moveBcdFrom(DecimalQuantity &other) {
1267     setBcdToZero();
1268     if (other.usingBytes) {
1269         usingBytes = true;
1270         fBCD.bcdBytes.ptr = other.fBCD.bcdBytes.ptr;
1271         fBCD.bcdBytes.len = other.fBCD.bcdBytes.len;
1272         // Take ownership away from the old instance:
1273         other.fBCD.bcdBytes.ptr = nullptr;
1274         other.usingBytes = false;
1275     } else {
1276         fBCD.bcdLong = other.fBCD.bcdLong;
1277     }
1278 }
1279 
checkHealth() const1280 const char16_t* DecimalQuantity::checkHealth() const {
1281     if (usingBytes) {
1282         if (precision == 0) { return u"Zero precision but we are in byte mode"; }
1283         int32_t capacity = fBCD.bcdBytes.len;
1284         if (precision > capacity) { return u"Precision exceeds length of byte array"; }
1285         if (getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in byte mode"; }
1286         if (getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; }
1287         for (int i = 0; i < precision; i++) {
1288             if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in byte array"; }
1289             if (getDigitPos(i) < 0) { return u"Digit below 0 in byte array"; }
1290         }
1291         for (int i = precision; i < capacity; i++) {
1292             if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in byte array"; }
1293         }
1294     } else {
1295         if (precision == 0 && fBCD.bcdLong != 0) {
1296             return u"Value in bcdLong even though precision is zero";
1297         }
1298         if (precision > 16) { return u"Precision exceeds length of long"; }
1299         if (precision != 0 && getDigitPos(precision - 1) == 0) {
1300             return u"Most significant digit is zero in long mode";
1301         }
1302         if (precision != 0 && getDigitPos(0) == 0) {
1303             return u"Least significant digit is zero in long mode";
1304         }
1305         for (int i = 0; i < precision; i++) {
1306             if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in long"; }
1307             if (getDigitPos(i) < 0) { return u"Digit below 0 in long (?!)"; }
1308         }
1309         for (int i = precision; i < 16; i++) {
1310             if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in long"; }
1311         }
1312     }
1313 
1314     // No error
1315     return nullptr;
1316 }
1317 
operator ==(const DecimalQuantity & other) const1318 bool DecimalQuantity::operator==(const DecimalQuantity& other) const {
1319     bool basicEquals =
1320             scale == other.scale
1321             && precision == other.precision
1322             && flags == other.flags
1323             && lReqPos == other.lReqPos
1324             && rReqPos == other.rReqPos
1325             && isApproximate == other.isApproximate;
1326     if (!basicEquals) {
1327         return false;
1328     }
1329 
1330     if (precision == 0) {
1331         return true;
1332     } else if (isApproximate) {
1333         return origDouble == other.origDouble && origDelta == other.origDelta;
1334     } else {
1335         for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) {
1336             if (getDigit(m) != other.getDigit(m)) {
1337                 return false;
1338             }
1339         }
1340         return true;
1341     }
1342 }
1343 
toString() const1344 UnicodeString DecimalQuantity::toString() const {
1345     UErrorCode localStatus = U_ZERO_ERROR;
1346     MaybeStackArray<char, 30> digits(precision + 1, localStatus);
1347     if (U_FAILURE(localStatus)) {
1348         return ICU_Utility::makeBogusString();
1349     }
1350     for (int32_t i = 0; i < precision; i++) {
1351         digits[i] = getDigitPos(precision - i - 1) + '0';
1352     }
1353     digits[precision] = 0; // terminate buffer
1354     char buffer8[100];
1355     snprintf(
1356             buffer8,
1357             sizeof(buffer8),
1358             "<DecimalQuantity %d:%d %s %s%s%s%d>",
1359             lReqPos,
1360             rReqPos,
1361             (usingBytes ? "bytes" : "long"),
1362             (isNegative() ? "-" : ""),
1363             (precision == 0 ? "0" : digits.getAlias()),
1364             "E",
1365             scale);
1366     return UnicodeString(buffer8, -1, US_INV);
1367 }
1368 
1369 #endif /* #if !UCONFIG_NO_FORMATTING */
1370