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 
hasIntegerValue() const292 bool DecimalQuantity::hasIntegerValue() const {
293     return scale >= 0;
294 }
295 
getUpperDisplayMagnitude() const296 int32_t DecimalQuantity::getUpperDisplayMagnitude() const {
297     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
298     // See the comment in the header file explaining the "isApproximate" field.
299     U_ASSERT(!isApproximate);
300 
301     int32_t magnitude = scale + precision;
302     int32_t result = (lReqPos > magnitude) ? lReqPos : magnitude;
303     return result - 1;
304 }
305 
getLowerDisplayMagnitude() const306 int32_t DecimalQuantity::getLowerDisplayMagnitude() const {
307     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
308     // See the comment in the header file explaining the "isApproximate" field.
309     U_ASSERT(!isApproximate);
310 
311     int32_t magnitude = scale;
312     int32_t result = (rReqPos < magnitude) ? rReqPos : magnitude;
313     return result;
314 }
315 
getDigit(int32_t magnitude) const316 int8_t DecimalQuantity::getDigit(int32_t magnitude) const {
317     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
318     // See the comment at the top of this file explaining the "isApproximate" field.
319     U_ASSERT(!isApproximate);
320 
321     return getDigitPos(magnitude - scale);
322 }
323 
fractionCount() const324 int32_t DecimalQuantity::fractionCount() const {
325     int32_t fractionCountWithExponent = -getLowerDisplayMagnitude() - exponent;
326     return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;
327 }
328 
fractionCountWithoutTrailingZeros() const329 int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const {
330     int32_t fractionCountWithExponent = -scale - exponent;
331     return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;  // max(-fractionCountWithExponent, 0)
332 }
333 
isNegative() const334 bool DecimalQuantity::isNegative() const {
335     return (flags & NEGATIVE_FLAG) != 0;
336 }
337 
signum() const338 Signum DecimalQuantity::signum() const {
339     bool isZero = (isZeroish() && !isInfinite());
340     bool isNeg = isNegative();
341     if (isZero && isNeg) {
342         return SIGNUM_NEG_ZERO;
343     } else if (isZero) {
344         return SIGNUM_POS_ZERO;
345     } else if (isNeg) {
346         return SIGNUM_NEG;
347     } else {
348         return SIGNUM_POS;
349     }
350 }
351 
isInfinite() const352 bool DecimalQuantity::isInfinite() const {
353     return (flags & INFINITY_FLAG) != 0;
354 }
355 
isNaN() const356 bool DecimalQuantity::isNaN() const {
357     return (flags & NAN_FLAG) != 0;
358 }
359 
isZeroish() const360 bool DecimalQuantity::isZeroish() const {
361     return precision == 0;
362 }
363 
setToInt(int32_t n)364 DecimalQuantity &DecimalQuantity::setToInt(int32_t n) {
365     setBcdToZero();
366     flags = 0;
367     if (n == INT32_MIN) {
368         flags |= NEGATIVE_FLAG;
369         // leave as INT32_MIN; handled below in _setToInt()
370     } else if (n < 0) {
371         flags |= NEGATIVE_FLAG;
372         n = -n;
373     }
374     if (n != 0) {
375         _setToInt(n);
376         compact();
377     }
378     return *this;
379 }
380 
_setToInt(int32_t n)381 void DecimalQuantity::_setToInt(int32_t n) {
382     if (n == INT32_MIN) {
383         readLongToBcd(-static_cast<int64_t>(n));
384     } else {
385         readIntToBcd(n);
386     }
387 }
388 
setToLong(int64_t n)389 DecimalQuantity &DecimalQuantity::setToLong(int64_t n) {
390     setBcdToZero();
391     flags = 0;
392     if (n < 0 && n > INT64_MIN) {
393         flags |= NEGATIVE_FLAG;
394         n = -n;
395     }
396     if (n != 0) {
397         _setToLong(n);
398         compact();
399     }
400     return *this;
401 }
402 
_setToLong(int64_t n)403 void DecimalQuantity::_setToLong(int64_t n) {
404     if (n == INT64_MIN) {
405         DecNum decnum;
406         UErrorCode localStatus = U_ZERO_ERROR;
407         decnum.setTo("9.223372036854775808E+18", localStatus);
408         if (U_FAILURE(localStatus)) { return; } // unexpected
409         flags |= NEGATIVE_FLAG;
410         readDecNumberToBcd(decnum);
411     } else if (n <= INT32_MAX) {
412         readIntToBcd(static_cast<int32_t>(n));
413     } else {
414         readLongToBcd(n);
415     }
416 }
417 
setToDouble(double n)418 DecimalQuantity &DecimalQuantity::setToDouble(double n) {
419     setBcdToZero();
420     flags = 0;
421     // signbit() from <math.h> handles +0.0 vs -0.0
422     if (std::signbit(n)) {
423         flags |= NEGATIVE_FLAG;
424         n = -n;
425     }
426     if (std::isnan(n) != 0) {
427         flags |= NAN_FLAG;
428     } else if (std::isfinite(n) == 0) {
429         flags |= INFINITY_FLAG;
430     } else if (n != 0) {
431         _setToDoubleFast(n);
432         compact();
433     }
434     return *this;
435 }
436 
_setToDoubleFast(double n)437 void DecimalQuantity::_setToDoubleFast(double n) {
438     isApproximate = true;
439     origDouble = n;
440     origDelta = 0;
441 
442     // Make sure the double is an IEEE 754 double.  If not, fall back to the slow path right now.
443     // TODO: Make a fast path for other types of doubles.
444     if (!std::numeric_limits<double>::is_iec559) {
445         convertToAccurateDouble();
446         return;
447     }
448 
449     // To get the bits from the double, use memcpy, which takes care of endianness.
450     uint64_t ieeeBits;
451     uprv_memcpy(&ieeeBits, &n, sizeof(n));
452     int32_t exponent = static_cast<int32_t>((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff;
453 
454     // Not all integers can be represented exactly for exponent > 52
455     if (exponent <= 52 && static_cast<int64_t>(n) == n) {
456         _setToLong(static_cast<int64_t>(n));
457         return;
458     }
459 
460     if (exponent == -1023 || exponent == 1024) {
461         // The extreme values of exponent are special; use slow path.
462         convertToAccurateDouble();
463         return;
464     }
465 
466     // 3.3219... is log2(10)
467     auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809488736234787031942948939017586);
468     if (fracLength >= 0) {
469         int32_t i = fracLength;
470         // 1e22 is the largest exact double.
471         for (; i >= 22; i -= 22) n *= 1e22;
472         n *= DOUBLE_MULTIPLIERS[i];
473     } else {
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     }
479     auto result = static_cast<int64_t>(uprv_round(n));
480     if (result != 0) {
481         _setToLong(result);
482         scale -= fracLength;
483     }
484 }
485 
convertToAccurateDouble()486 void DecimalQuantity::convertToAccurateDouble() {
487     U_ASSERT(origDouble != 0);
488     int32_t delta = origDelta;
489 
490     // Call the slow oracle function (Double.toString in Java, DoubleToAscii in C++).
491     char buffer[DoubleToStringConverter::kBase10MaximalLength + 1];
492     bool sign; // unused; always positive
493     int32_t length;
494     int32_t point;
495     DoubleToStringConverter::DoubleToAscii(
496         origDouble,
497         DoubleToStringConverter::DtoaMode::SHORTEST,
498         0,
499         buffer,
500         sizeof(buffer),
501         &sign,
502         &length,
503         &point
504     );
505 
506     setBcdToZero();
507     readDoubleConversionToBcd(buffer, length, point);
508     scale += delta;
509     explicitExactDouble = true;
510 }
511 
setToDecNumber(StringPiece n,UErrorCode & status)512 DecimalQuantity &DecimalQuantity::setToDecNumber(StringPiece n, UErrorCode& status) {
513     setBcdToZero();
514     flags = 0;
515 
516     // Compute the decNumber representation
517     DecNum decnum;
518     decnum.setTo(n, status);
519 
520     _setToDecNum(decnum, status);
521     return *this;
522 }
523 
setToDecNum(const DecNum & decnum,UErrorCode & status)524 DecimalQuantity& DecimalQuantity::setToDecNum(const DecNum& decnum, UErrorCode& status) {
525     setBcdToZero();
526     flags = 0;
527 
528     _setToDecNum(decnum, status);
529     return *this;
530 }
531 
_setToDecNum(const DecNum & decnum,UErrorCode & status)532 void DecimalQuantity::_setToDecNum(const DecNum& decnum, UErrorCode& status) {
533     if (U_FAILURE(status)) { return; }
534     if (decnum.isNegative()) {
535         flags |= NEGATIVE_FLAG;
536     }
537     if (!decnum.isZero()) {
538         readDecNumberToBcd(decnum);
539         compact();
540     }
541 }
542 
toLong(bool truncateIfOverflow) const543 int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const {
544     // NOTE: Call sites should be guarded by fitsInLong(), like this:
545     // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ }
546     // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits.
547     uint64_t result = 0L;
548     int32_t upperMagnitude = exponent + scale + precision - 1;
549     if (truncateIfOverflow) {
550         upperMagnitude = std::min(upperMagnitude, 17);
551     }
552     for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) {
553         result = result * 10 + getDigitPos(magnitude - scale - exponent);
554     }
555     if (isNegative()) {
556         return static_cast<int64_t>(0LL - result); // i.e., -result
557     }
558     return static_cast<int64_t>(result);
559 }
560 
toFractionLong(bool includeTrailingZeros) const561 uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const {
562     uint64_t result = 0L;
563     int32_t magnitude = -1 - exponent;
564     int32_t lowerMagnitude = scale;
565     if (includeTrailingZeros) {
566         lowerMagnitude = std::min(lowerMagnitude, rReqPos);
567     }
568     for (; magnitude >= lowerMagnitude && result <= 1e18L; magnitude--) {
569         result = result * 10 + getDigitPos(magnitude - scale);
570     }
571     // Remove trailing zeros; this can happen during integer overflow cases.
572     if (!includeTrailingZeros) {
573         while (result > 0 && (result % 10) == 0) {
574             result /= 10;
575         }
576     }
577     return result;
578 }
579 
fitsInLong(bool ignoreFraction) const580 bool DecimalQuantity::fitsInLong(bool ignoreFraction) const {
581     if (isInfinite() || isNaN()) {
582         return false;
583     }
584     if (isZeroish()) {
585         return true;
586     }
587     if (exponent + scale < 0 && !ignoreFraction) {
588         return false;
589     }
590     int magnitude = getMagnitude();
591     if (magnitude < 18) {
592         return true;
593     }
594     if (magnitude > 18) {
595         return false;
596     }
597     // Hard case: the magnitude is 10^18.
598     // The largest int64 is: 9,223,372,036,854,775,807
599     for (int p = 0; p < precision; p++) {
600         int8_t digit = getDigit(18 - p);
601         static int8_t INT64_BCD[] = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 };
602         if (digit < INT64_BCD[p]) {
603             return true;
604         } else if (digit > INT64_BCD[p]) {
605             return false;
606         }
607     }
608     // Exactly equal to max long plus one.
609     return isNegative();
610 }
611 
toDouble() const612 double DecimalQuantity::toDouble() const {
613     // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
614     // See the comment in the header file explaining the "isApproximate" field.
615     U_ASSERT(!isApproximate);
616 
617     if (isNaN()) {
618         return NAN;
619     } else if (isInfinite()) {
620         return isNegative() ? -INFINITY : INFINITY;
621     }
622 
623     // We are processing well-formed input, so we don't need any special options to StringToDoubleConverter.
624     StringToDoubleConverter converter(0, 0, 0, "", "");
625     UnicodeString numberString = this->toScientificString();
626     int32_t count;
627     return converter.StringToDouble(
628             reinterpret_cast<const uint16_t*>(numberString.getBuffer()),
629             numberString.length(),
630             &count);
631 }
632 
toDecNum(DecNum & output,UErrorCode & status) const633 DecNum& DecimalQuantity::toDecNum(DecNum& output, UErrorCode& status) const {
634     // Special handling for zero
635     if (precision == 0) {
636         output.setTo("0", status);
637     }
638 
639     // Use the BCD constructor. We need to do a little bit of work to convert, though.
640     // The decNumber constructor expects most-significant first, but we store least-significant first.
641     MaybeStackArray<uint8_t, 20> ubcd(precision, status);
642     if (U_FAILURE(status)) {
643         return output;
644     }
645     for (int32_t m = 0; m < precision; m++) {
646         ubcd[precision - m - 1] = static_cast<uint8_t>(getDigitPos(m));
647     }
648     output.setTo(ubcd.getAlias(), precision, scale, isNegative(), status);
649     return output;
650 }
651 
truncate()652 void DecimalQuantity::truncate() {
653     if (scale < 0) {
654         shiftRight(-scale);
655         scale = 0;
656         compact();
657     }
658 }
659 
roundToNickel(int32_t magnitude,RoundingMode roundingMode,UErrorCode & status)660 void DecimalQuantity::roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
661     roundToMagnitude(magnitude, roundingMode, true, status);
662 }
663 
roundToMagnitude(int32_t magnitude,RoundingMode roundingMode,UErrorCode & status)664 void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
665     roundToMagnitude(magnitude, roundingMode, false, status);
666 }
667 
roundToMagnitude(int32_t magnitude,RoundingMode roundingMode,bool nickel,UErrorCode & status)668 void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status) {
669     // The position in the BCD at which rounding will be performed; digits to the right of position
670     // will be rounded away.
671     int position = safeSubtract(magnitude, scale);
672 
673     // "trailing" = least significant digit to the left of rounding
674     int8_t trailingDigit = getDigitPos(position);
675 
676     if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
677         // All digits are to the left of the rounding magnitude.
678     } else if (precision == 0) {
679         // No rounding for zero.
680     } else {
681         // Perform rounding logic.
682         // "leading" = most significant digit to the right of rounding
683         int8_t leadingDigit = getDigitPos(safeSubtract(position, 1));
684 
685         // Compute which section of the number we are in.
686         // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles)
687         // LOWER means we are between the bottom edge and the midpoint, like 1.391
688         // MIDPOINT means we are exactly in the middle, like 1.500
689         // UPPER means we are between the midpoint and the top edge, like 1.916
690         roundingutils::Section section;
691         if (!isApproximate) {
692             if (nickel && trailingDigit != 2 && trailingDigit != 7) {
693                 // Nickel rounding, and not at .02x or .07x
694                 if (trailingDigit < 2) {
695                     // .00, .01 => down to .00
696                     section = roundingutils::SECTION_LOWER;
697                 } else if (trailingDigit < 5) {
698                     // .03, .04 => up to .05
699                     section = roundingutils::SECTION_UPPER;
700                 } else if (trailingDigit < 7) {
701                     // .05, .06 => down to .05
702                     section = roundingutils::SECTION_LOWER;
703                 } else {
704                     // .08, .09 => up to .10
705                     section = roundingutils::SECTION_UPPER;
706                 }
707             } else if (leadingDigit < 5) {
708                 // Includes nickel rounding .020-.024 and .070-.074
709                 section = roundingutils::SECTION_LOWER;
710             } else if (leadingDigit > 5) {
711                 // Includes nickel rounding .026-.029 and .076-.079
712                 section = roundingutils::SECTION_UPPER;
713             } else {
714                 // Includes nickel rounding .025 and .075
715                 section = roundingutils::SECTION_MIDPOINT;
716                 for (int p = safeSubtract(position, 2); p >= 0; p--) {
717                     if (getDigitPos(p) != 0) {
718                         section = roundingutils::SECTION_UPPER;
719                         break;
720                     }
721                 }
722             }
723         } else {
724             int32_t p = safeSubtract(position, 2);
725             int32_t minP = uprv_max(0, precision - 14);
726             if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
727                 section = roundingutils::SECTION_LOWER_EDGE;
728                 for (; p >= minP; p--) {
729                     if (getDigitPos(p) != 0) {
730                         section = roundingutils::SECTION_LOWER;
731                         break;
732                     }
733                 }
734             } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
735                 section = roundingutils::SECTION_MIDPOINT;
736                 for (; p >= minP; p--) {
737                     if (getDigitPos(p) != 9) {
738                         section = roundingutils::SECTION_LOWER;
739                         break;
740                     }
741                 }
742             } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
743                 section = roundingutils::SECTION_MIDPOINT;
744                 for (; p >= minP; p--) {
745                     if (getDigitPos(p) != 0) {
746                         section = roundingutils::SECTION_UPPER;
747                         break;
748                     }
749                 }
750             } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) {
751                 section = roundingutils::SECTION_UPPER_EDGE;
752                 for (; p >= minP; p--) {
753                     if (getDigitPos(p) != 9) {
754                         section = roundingutils::SECTION_UPPER;
755                         break;
756                     }
757                 }
758             } else if (nickel && trailingDigit != 2 && trailingDigit != 7) {
759                 // Nickel rounding, and not at .02x or .07x
760                 if (trailingDigit < 2) {
761                     // .00, .01 => down to .00
762                     section = roundingutils::SECTION_LOWER;
763                 } else if (trailingDigit < 5) {
764                     // .03, .04 => up to .05
765                     section = roundingutils::SECTION_UPPER;
766                 } else if (trailingDigit < 7) {
767                     // .05, .06 => down to .05
768                     section = roundingutils::SECTION_LOWER;
769                 } else {
770                     // .08, .09 => up to .10
771                     section = roundingutils::SECTION_UPPER;
772                 }
773             } else if (leadingDigit < 5) {
774                 // Includes nickel rounding .020-.024 and .070-.074
775                 section = roundingutils::SECTION_LOWER;
776             } else {
777                 // Includes nickel rounding .026-.029 and .076-.079
778                 section = roundingutils::SECTION_UPPER;
779             }
780 
781             bool roundsAtMidpoint = roundingutils::roundsAtMidpoint(roundingMode);
782             if (safeSubtract(position, 1) < precision - 14 ||
783                 (roundsAtMidpoint && section == roundingutils::SECTION_MIDPOINT) ||
784                 (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) {
785                 // Oops! This means that we have to get the exact representation of the double,
786                 // because the zone of uncertainty is along the rounding boundary.
787                 convertToAccurateDouble();
788                 roundToMagnitude(magnitude, roundingMode, nickel, status); // start over
789                 return;
790             }
791 
792             // Turn off the approximate double flag, since the value is now confirmed to be exact.
793             isApproximate = false;
794             origDouble = 0.0;
795             origDelta = 0;
796 
797             if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
798                 // All digits are to the left of the rounding magnitude.
799                 return;
800             }
801 
802             // Good to continue rounding.
803             if (section == -1) { section = roundingutils::SECTION_LOWER; }
804             if (section == -2) { section = roundingutils::SECTION_UPPER; }
805         }
806 
807         // Nickel rounding "half even" goes to the nearest whole (away from the 5).
808         bool isEven = nickel
809                 ? (trailingDigit < 2 || trailingDigit > 7
810                         || (trailingDigit == 2 && section != roundingutils::SECTION_UPPER)
811                         || (trailingDigit == 7 && section == roundingutils::SECTION_UPPER))
812                 : (trailingDigit % 2) == 0;
813 
814         bool roundDown = roundingutils::getRoundingDirection(isEven,
815                 isNegative(),
816                 section,
817                 roundingMode,
818                 status);
819         if (U_FAILURE(status)) {
820             return;
821         }
822 
823         // Perform truncation
824         if (position >= precision) {
825             setBcdToZero();
826             scale = magnitude;
827         } else {
828             shiftRight(position);
829         }
830 
831         if (nickel) {
832             if (trailingDigit < 5 && roundDown) {
833                 setDigitPos(0, 0);
834                 compact();
835                 return;
836             } else if (trailingDigit >= 5 && !roundDown) {
837                 setDigitPos(0, 9);
838                 trailingDigit = 9;
839                 // do not return: use the bubbling logic below
840             } else {
841                 setDigitPos(0, 5);
842                 // compact not necessary: digit at position 0 is nonzero
843                 return;
844             }
845         }
846 
847         // Bubble the result to the higher digits
848         if (!roundDown) {
849             if (trailingDigit == 9) {
850                 int bubblePos = 0;
851                 // Note: in the long implementation, the most digits BCD can have at this point is
852                 // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe.
853                 for (; getDigitPos(bubblePos) == 9; bubblePos++) {}
854                 shiftRight(bubblePos); // shift off the trailing 9s
855             }
856             int8_t digit0 = getDigitPos(0);
857             U_ASSERT(digit0 != 9);
858             setDigitPos(0, static_cast<int8_t>(digit0 + 1));
859             precision += 1; // in case an extra digit got added
860         }
861 
862         compact();
863     }
864 }
865 
roundToInfinity()866 void DecimalQuantity::roundToInfinity() {
867     if (isApproximate) {
868         convertToAccurateDouble();
869     }
870 }
871 
appendDigit(int8_t value,int32_t leadingZeros,bool appendAsInteger)872 void DecimalQuantity::appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger) {
873     U_ASSERT(leadingZeros >= 0);
874 
875     // Zero requires special handling to maintain the invariant that the least-significant digit
876     // in the BCD is nonzero.
877     if (value == 0) {
878         if (appendAsInteger && precision != 0) {
879             scale += leadingZeros + 1;
880         }
881         return;
882     }
883 
884     // Deal with trailing zeros
885     if (scale > 0) {
886         leadingZeros += scale;
887         if (appendAsInteger) {
888             scale = 0;
889         }
890     }
891 
892     // Append digit
893     shiftLeft(leadingZeros + 1);
894     setDigitPos(0, value);
895 
896     // Fix scale if in integer mode
897     if (appendAsInteger) {
898         scale += leadingZeros + 1;
899     }
900 }
901 
toPlainString() const902 UnicodeString DecimalQuantity::toPlainString() const {
903     U_ASSERT(!isApproximate);
904     UnicodeString sb;
905     if (isNegative()) {
906         sb.append(u'-');
907     }
908     if (precision == 0) {
909         sb.append(u'0');
910         return sb;
911     }
912     int32_t upper = scale + precision + exponent - 1;
913     int32_t lower = scale + exponent;
914     if (upper < lReqPos - 1) {
915         upper = lReqPos - 1;
916     }
917     if (lower > rReqPos) {
918         lower = rReqPos;
919     }
920     int32_t p = upper;
921     if (p < 0) {
922         sb.append(u'0');
923     }
924     for (; p >= 0; p--) {
925         sb.append(u'0' + getDigitPos(p - scale - exponent));
926     }
927     if (lower < 0) {
928         sb.append(u'.');
929     }
930     for(; p >= lower; p--) {
931         sb.append(u'0' + getDigitPos(p - scale - exponent));
932     }
933     return sb;
934 }
935 
toScientificString() const936 UnicodeString DecimalQuantity::toScientificString() const {
937     U_ASSERT(!isApproximate);
938     UnicodeString result;
939     if (isNegative()) {
940         result.append(u'-');
941     }
942     if (precision == 0) {
943         result.append(u"0E+0", -1);
944         return result;
945     }
946     int32_t upperPos = precision - 1;
947     int32_t lowerPos = 0;
948     int32_t p = upperPos;
949     result.append(u'0' + getDigitPos(p));
950     if ((--p) >= lowerPos) {
951         result.append(u'.');
952         for (; p >= lowerPos; p--) {
953             result.append(u'0' + getDigitPos(p));
954         }
955     }
956     result.append(u'E');
957     int32_t _scale = upperPos + scale + exponent;
958     if (_scale == INT32_MIN) {
959         result.append({u"-2147483648", -1});
960         return result;
961     } else if (_scale < 0) {
962         _scale *= -1;
963         result.append(u'-');
964     } else {
965         result.append(u'+');
966     }
967     if (_scale == 0) {
968         result.append(u'0');
969     }
970     int32_t insertIndex = result.length();
971     while (_scale > 0) {
972         std::div_t res = std::div(_scale, 10);
973         result.insert(insertIndex, u'0' + res.rem);
974         _scale = res.quot;
975     }
976     return result;
977 }
978 
979 ////////////////////////////////////////////////////
980 /// End of DecimalQuantity_AbstractBCD.java      ///
981 /// Start of DecimalQuantity_DualStorageBCD.java ///
982 ////////////////////////////////////////////////////
983 
getDigitPos(int32_t position) const984 int8_t DecimalQuantity::getDigitPos(int32_t position) const {
985     if (usingBytes) {
986         if (position < 0 || position >= precision) { return 0; }
987         return fBCD.bcdBytes.ptr[position];
988     } else {
989         if (position < 0 || position >= 16) { return 0; }
990         return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf);
991     }
992 }
993 
setDigitPos(int32_t position,int8_t value)994 void DecimalQuantity::setDigitPos(int32_t position, int8_t value) {
995     U_ASSERT(position >= 0);
996     if (usingBytes) {
997         ensureCapacity(position + 1);
998         fBCD.bcdBytes.ptr[position] = value;
999     } else if (position >= 16) {
1000         switchStorage();
1001         ensureCapacity(position + 1);
1002         fBCD.bcdBytes.ptr[position] = value;
1003     } else {
1004         int shift = position * 4;
1005         fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift);
1006     }
1007 }
1008 
shiftLeft(int32_t numDigits)1009 void DecimalQuantity::shiftLeft(int32_t numDigits) {
1010     if (!usingBytes && precision + numDigits > 16) {
1011         switchStorage();
1012     }
1013     if (usingBytes) {
1014         ensureCapacity(precision + numDigits);
1015         uprv_memmove(fBCD.bcdBytes.ptr + numDigits, fBCD.bcdBytes.ptr, precision);
1016         uprv_memset(fBCD.bcdBytes.ptr, 0, numDigits);
1017     } else {
1018         fBCD.bcdLong <<= (numDigits * 4);
1019     }
1020     scale -= numDigits;
1021     precision += numDigits;
1022 }
1023 
shiftRight(int32_t numDigits)1024 void DecimalQuantity::shiftRight(int32_t numDigits) {
1025     if (usingBytes) {
1026         int i = 0;
1027         for (; i < precision - numDigits; i++) {
1028             fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i + numDigits];
1029         }
1030         for (; i < precision; i++) {
1031             fBCD.bcdBytes.ptr[i] = 0;
1032         }
1033     } else {
1034         fBCD.bcdLong >>= (numDigits * 4);
1035     }
1036     scale += numDigits;
1037     precision -= numDigits;
1038 }
1039 
popFromLeft(int32_t numDigits)1040 void DecimalQuantity::popFromLeft(int32_t numDigits) {
1041     U_ASSERT(numDigits <= precision);
1042     if (usingBytes) {
1043         int i = precision - 1;
1044         for (; i >= precision - numDigits; i--) {
1045             fBCD.bcdBytes.ptr[i] = 0;
1046         }
1047     } else {
1048         fBCD.bcdLong &= (static_cast<uint64_t>(1) << ((precision - numDigits) * 4)) - 1;
1049     }
1050     precision -= numDigits;
1051 }
1052 
setBcdToZero()1053 void DecimalQuantity::setBcdToZero() {
1054     if (usingBytes) {
1055         uprv_free(fBCD.bcdBytes.ptr);
1056         fBCD.bcdBytes.ptr = nullptr;
1057         usingBytes = false;
1058     }
1059     fBCD.bcdLong = 0L;
1060     scale = 0;
1061     precision = 0;
1062     isApproximate = false;
1063     origDouble = 0;
1064     origDelta = 0;
1065     exponent = 0;
1066 }
1067 
readIntToBcd(int32_t n)1068 void DecimalQuantity::readIntToBcd(int32_t n) {
1069     U_ASSERT(n != 0);
1070     // ints always fit inside the long implementation.
1071     uint64_t result = 0L;
1072     int i = 16;
1073     for (; n != 0; n /= 10, i--) {
1074         result = (result >> 4) + ((static_cast<uint64_t>(n) % 10) << 60);
1075     }
1076     U_ASSERT(!usingBytes);
1077     fBCD.bcdLong = result >> (i * 4);
1078     scale = 0;
1079     precision = 16 - i;
1080 }
1081 
readLongToBcd(int64_t n)1082 void DecimalQuantity::readLongToBcd(int64_t n) {
1083     U_ASSERT(n != 0);
1084     if (n >= 10000000000000000L) {
1085         ensureCapacity();
1086         int i = 0;
1087         for (; n != 0L; n /= 10L, i++) {
1088             fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(n % 10);
1089         }
1090         U_ASSERT(usingBytes);
1091         scale = 0;
1092         precision = i;
1093     } else {
1094         uint64_t result = 0L;
1095         int i = 16;
1096         for (; n != 0L; n /= 10L, i--) {
1097             result = (result >> 4) + ((n % 10) << 60);
1098         }
1099         U_ASSERT(i >= 0);
1100         U_ASSERT(!usingBytes);
1101         fBCD.bcdLong = result >> (i * 4);
1102         scale = 0;
1103         precision = 16 - i;
1104     }
1105 }
1106 
readDecNumberToBcd(const DecNum & decnum)1107 void DecimalQuantity::readDecNumberToBcd(const DecNum& decnum) {
1108     const decNumber* dn = decnum.getRawDecNumber();
1109     if (dn->digits > 16) {
1110         ensureCapacity(dn->digits);
1111         for (int32_t i = 0; i < dn->digits; i++) {
1112             fBCD.bcdBytes.ptr[i] = dn->lsu[i];
1113         }
1114     } else {
1115         uint64_t result = 0L;
1116         for (int32_t i = 0; i < dn->digits; i++) {
1117             result |= static_cast<uint64_t>(dn->lsu[i]) << (4 * i);
1118         }
1119         fBCD.bcdLong = result;
1120     }
1121     scale = dn->exponent;
1122     precision = dn->digits;
1123 }
1124 
readDoubleConversionToBcd(const char * buffer,int32_t length,int32_t point)1125 void DecimalQuantity::readDoubleConversionToBcd(
1126         const char* buffer, int32_t length, int32_t point) {
1127     // NOTE: Despite the fact that double-conversion's API is called
1128     // "DoubleToAscii", they actually use '0' (as opposed to u8'0').
1129     if (length > 16) {
1130         ensureCapacity(length);
1131         for (int32_t i = 0; i < length; i++) {
1132             fBCD.bcdBytes.ptr[i] = buffer[length-i-1] - '0';
1133         }
1134     } else {
1135         uint64_t result = 0L;
1136         for (int32_t i = 0; i < length; i++) {
1137             result |= static_cast<uint64_t>(buffer[length-i-1] - '0') << (4 * i);
1138         }
1139         fBCD.bcdLong = result;
1140     }
1141     scale = point - length;
1142     precision = length;
1143 }
1144 
compact()1145 void DecimalQuantity::compact() {
1146     if (usingBytes) {
1147         int32_t delta = 0;
1148         for (; delta < precision && fBCD.bcdBytes.ptr[delta] == 0; delta++);
1149         if (delta == precision) {
1150             // Number is zero
1151             setBcdToZero();
1152             return;
1153         } else {
1154             // Remove trailing zeros
1155             shiftRight(delta);
1156         }
1157 
1158         // Compute precision
1159         int32_t leading = precision - 1;
1160         for (; leading >= 0 && fBCD.bcdBytes.ptr[leading] == 0; leading--);
1161         precision = leading + 1;
1162 
1163         // Switch storage mechanism if possible
1164         if (precision <= 16) {
1165             switchStorage();
1166         }
1167 
1168     } else {
1169         if (fBCD.bcdLong == 0L) {
1170             // Number is zero
1171             setBcdToZero();
1172             return;
1173         }
1174 
1175         // Compact the number (remove trailing zeros)
1176         // TODO: Use a more efficient algorithm here and below. There is a logarithmic one.
1177         int32_t delta = 0;
1178         for (; delta < precision && getDigitPos(delta) == 0; delta++);
1179         fBCD.bcdLong >>= delta * 4;
1180         scale += delta;
1181 
1182         // Compute precision
1183         int32_t leading = precision - 1;
1184         for (; leading >= 0 && getDigitPos(leading) == 0; leading--);
1185         precision = leading + 1;
1186     }
1187 }
1188 
ensureCapacity()1189 void DecimalQuantity::ensureCapacity() {
1190     ensureCapacity(40);
1191 }
1192 
ensureCapacity(int32_t capacity)1193 void DecimalQuantity::ensureCapacity(int32_t capacity) {
1194     if (capacity == 0) { return; }
1195     int32_t oldCapacity = usingBytes ? fBCD.bcdBytes.len : 0;
1196     if (!usingBytes) {
1197         // TODO: There is nothing being done to check for memory allocation failures.
1198         // TODO: Consider indexing by nybbles instead of bytes in C++, so that we can
1199         // make these arrays half the size.
1200         fBCD.bcdBytes.ptr = static_cast<int8_t*>(uprv_malloc(capacity * sizeof(int8_t)));
1201         fBCD.bcdBytes.len = capacity;
1202         // Initialize the byte array to zeros (this is done automatically in Java)
1203         uprv_memset(fBCD.bcdBytes.ptr, 0, capacity * sizeof(int8_t));
1204     } else if (oldCapacity < capacity) {
1205         auto bcd1 = static_cast<int8_t*>(uprv_malloc(capacity * 2 * sizeof(int8_t)));
1206         uprv_memcpy(bcd1, fBCD.bcdBytes.ptr, oldCapacity * sizeof(int8_t));
1207         // Initialize the rest of the byte array to zeros (this is done automatically in Java)
1208         uprv_memset(bcd1 + oldCapacity, 0, (capacity - oldCapacity) * sizeof(int8_t));
1209         uprv_free(fBCD.bcdBytes.ptr);
1210         fBCD.bcdBytes.ptr = bcd1;
1211         fBCD.bcdBytes.len = capacity * 2;
1212     }
1213     usingBytes = true;
1214 }
1215 
switchStorage()1216 void DecimalQuantity::switchStorage() {
1217     if (usingBytes) {
1218         // Change from bytes to long
1219         uint64_t bcdLong = 0L;
1220         for (int i = precision - 1; i >= 0; i--) {
1221             bcdLong <<= 4;
1222             bcdLong |= fBCD.bcdBytes.ptr[i];
1223         }
1224         uprv_free(fBCD.bcdBytes.ptr);
1225         fBCD.bcdBytes.ptr = nullptr;
1226         fBCD.bcdLong = bcdLong;
1227         usingBytes = false;
1228     } else {
1229         // Change from long to bytes
1230         // Copy the long into a local variable since it will get munged when we allocate the bytes
1231         uint64_t bcdLong = fBCD.bcdLong;
1232         ensureCapacity();
1233         for (int i = 0; i < precision; i++) {
1234             fBCD.bcdBytes.ptr[i] = static_cast<int8_t>(bcdLong & 0xf);
1235             bcdLong >>= 4;
1236         }
1237         U_ASSERT(usingBytes);
1238     }
1239 }
1240 
copyBcdFrom(const DecimalQuantity & other)1241 void DecimalQuantity::copyBcdFrom(const DecimalQuantity &other) {
1242     setBcdToZero();
1243     if (other.usingBytes) {
1244         ensureCapacity(other.precision);
1245         uprv_memcpy(fBCD.bcdBytes.ptr, other.fBCD.bcdBytes.ptr, other.precision * sizeof(int8_t));
1246     } else {
1247         fBCD.bcdLong = other.fBCD.bcdLong;
1248     }
1249 }
1250 
moveBcdFrom(DecimalQuantity & other)1251 void DecimalQuantity::moveBcdFrom(DecimalQuantity &other) {
1252     setBcdToZero();
1253     if (other.usingBytes) {
1254         usingBytes = true;
1255         fBCD.bcdBytes.ptr = other.fBCD.bcdBytes.ptr;
1256         fBCD.bcdBytes.len = other.fBCD.bcdBytes.len;
1257         // Take ownership away from the old instance:
1258         other.fBCD.bcdBytes.ptr = nullptr;
1259         other.usingBytes = false;
1260     } else {
1261         fBCD.bcdLong = other.fBCD.bcdLong;
1262     }
1263 }
1264 
checkHealth() const1265 const char16_t* DecimalQuantity::checkHealth() const {
1266     if (usingBytes) {
1267         if (precision == 0) { return u"Zero precision but we are in byte mode"; }
1268         int32_t capacity = fBCD.bcdBytes.len;
1269         if (precision > capacity) { return u"Precision exceeds length of byte array"; }
1270         if (getDigitPos(precision - 1) == 0) { return u"Most significant digit is zero in byte mode"; }
1271         if (getDigitPos(0) == 0) { return u"Least significant digit is zero in long mode"; }
1272         for (int i = 0; i < precision; i++) {
1273             if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in byte array"; }
1274             if (getDigitPos(i) < 0) { return u"Digit below 0 in byte array"; }
1275         }
1276         for (int i = precision; i < capacity; i++) {
1277             if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in byte array"; }
1278         }
1279     } else {
1280         if (precision == 0 && fBCD.bcdLong != 0) {
1281             return u"Value in bcdLong even though precision is zero";
1282         }
1283         if (precision > 16) { return u"Precision exceeds length of long"; }
1284         if (precision != 0 && getDigitPos(precision - 1) == 0) {
1285             return u"Most significant digit is zero in long mode";
1286         }
1287         if (precision != 0 && getDigitPos(0) == 0) {
1288             return u"Least significant digit is zero in long mode";
1289         }
1290         for (int i = 0; i < precision; i++) {
1291             if (getDigitPos(i) >= 10) { return u"Digit exceeding 10 in long"; }
1292             if (getDigitPos(i) < 0) { return u"Digit below 0 in long (?!)"; }
1293         }
1294         for (int i = precision; i < 16; i++) {
1295             if (getDigitPos(i) != 0) { return u"Nonzero digits outside of range in long"; }
1296         }
1297     }
1298 
1299     // No error
1300     return nullptr;
1301 }
1302 
operator ==(const DecimalQuantity & other) const1303 bool DecimalQuantity::operator==(const DecimalQuantity& other) const {
1304     bool basicEquals =
1305             scale == other.scale
1306             && precision == other.precision
1307             && flags == other.flags
1308             && lReqPos == other.lReqPos
1309             && rReqPos == other.rReqPos
1310             && isApproximate == other.isApproximate;
1311     if (!basicEquals) {
1312         return false;
1313     }
1314 
1315     if (precision == 0) {
1316         return true;
1317     } else if (isApproximate) {
1318         return origDouble == other.origDouble && origDelta == other.origDelta;
1319     } else {
1320         for (int m = getUpperDisplayMagnitude(); m >= getLowerDisplayMagnitude(); m--) {
1321             if (getDigit(m) != other.getDigit(m)) {
1322                 return false;
1323             }
1324         }
1325         return true;
1326     }
1327 }
1328 
toString() const1329 UnicodeString DecimalQuantity::toString() const {
1330     UErrorCode localStatus = U_ZERO_ERROR;
1331     MaybeStackArray<char, 30> digits(precision + 1, localStatus);
1332     if (U_FAILURE(localStatus)) {
1333         return ICU_Utility::makeBogusString();
1334     }
1335     for (int32_t i = 0; i < precision; i++) {
1336         digits[i] = getDigitPos(precision - i - 1) + '0';
1337     }
1338     digits[precision] = 0; // terminate buffer
1339     char buffer8[100];
1340     snprintf(
1341             buffer8,
1342             sizeof(buffer8),
1343             "<DecimalQuantity %d:%d %s %s%s%s%d>",
1344             lReqPos,
1345             rReqPos,
1346             (usingBytes ? "bytes" : "long"),
1347             (isNegative() ? "-" : ""),
1348             (precision == 0 ? "0" : digits.getAlias()),
1349             "E",
1350             scale);
1351     return UnicodeString(buffer8, -1, US_INV);
1352 }
1353 
1354 #endif /* #if !UCONFIG_NO_FORMATTING */
1355