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