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
24using namespace icu;
25using namespace icu::number;
26using namespace icu::number::impl;
27
28using icu::double_conversion::DoubleToStringConverter;
29using icu::double_conversion::StringToDoubleConverter;
30
31namespace {
32
33int8_t NEGATIVE_FLAG = 1;
34int8_t INFINITY_FLAG = 2;
35int8_t NAN_FLAG = 4;
36
37/** Helper function for safe subtraction (no overflow). */
38inline int32_t safeSubtract(int32_t a, int32_t b) {
39 // Note: In C++, signed integer subtraction is undefined behavior.
40 int32_t diff = static_cast<int32_t>(static_cast<uint32_t>(a) - static_cast<uint32_t>(b));
41 if (b < 0 && diff < a) { return INT32_MAX; }
42 if (b > 0 && diff > a) { return INT32_MIN; }
43 return diff;
44}
45
46static double DOUBLE_MULTIPLIERS[] = {
47 1e0,
48 1e1,
49 1e2,
50 1e3,
51 1e4,
52 1e5,
53 1e6,
54 1e7,
55 1e8,
56 1e9,
57 1e10,
58 1e11,
59 1e12,
60 1e13,
61 1e14,
62 1e15,
63 1e16,
64 1e17,
65 1e18,
66 1e19,
67 1e20,
68 1e21};
69
70} // namespace
71
72icu::IFixedDecimal::~IFixedDecimal() = default;
73
74DecimalQuantity::DecimalQuantity() {
75 setBcdToZero();
76 flags = 0;
77}
78
79DecimalQuantity::~DecimalQuantity() {
80 if (usingBytes) {
81 uprv_free(fBCD.bcdBytes.ptr);
82 fBCD.bcdBytes.ptr = nullptr;
83 usingBytes = false;
84 }
85}
86
87DecimalQuantity::DecimalQuantity(const DecimalQuantity &other) {
88 *this = other;
89}
90
91DecimalQuantity::DecimalQuantity(DecimalQuantity&& src) U_NOEXCEPT {
92 *this = std::move(src);
93}
94
95DecimalQuantity &DecimalQuantity::operator=(const DecimalQuantity &other) {
96 if (this == &other) {
97 return *this;
98 }
99 copyBcdFrom(other);
100 copyFieldsFrom(other);
101 return *this;
102}
103
104DecimalQuantity& DecimalQuantity::operator=(DecimalQuantity&& src) U_NOEXCEPT {
105 if (this == &src) {
106 return *this;
107 }
108 moveBcdFrom(src);
109 copyFieldsFrom(src);
110 return *this;
111}
112
113void DecimalQuantity::copyFieldsFrom(const DecimalQuantity& other) {
114 bogus = other.bogus;
115 lReqPos = other.lReqPos;
116 rReqPos = other.rReqPos;
117 scale = other.scale;
118 precision = other.precision;
119 flags = other.flags;
120 origDouble = other.origDouble;
121 origDelta = other.origDelta;
122 isApproximate = other.isApproximate;
123 exponent = other.exponent;
124}
125
126void DecimalQuantity::clear() {
127 lReqPos = 0;
128 rReqPos = 0;
129 flags = 0;
130 setBcdToZero(); // sets scale, precision, hasDouble, origDouble, origDelta, and BCD data
131}
132
133void DecimalQuantity::setMinInteger(int32_t minInt) {
134 // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
135 U_ASSERT(minInt >= 0);
136
137 // Special behavior: do not set minInt to be less than what is already set.
138 // This is so significant digits rounding can set the integer length.
139 if (minInt < lReqPos) {
140 minInt = lReqPos;
141 }
142
143 // Save values into internal state
144 lReqPos = minInt;
145}
146
147void DecimalQuantity::setMinFraction(int32_t minFrac) {
148 // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
149 U_ASSERT(minFrac >= 0);
150
151 // Save values into internal state
152 // Negation is safe for minFrac/maxFrac because -Integer.MAX_VALUE > Integer.MIN_VALUE
153 rReqPos = -minFrac;
154}
155
156void DecimalQuantity::applyMaxInteger(int32_t maxInt) {
157 // Validation should happen outside of DecimalQuantity, e.g., in the Precision class.
158 U_ASSERT(maxInt >= 0);
159
160 if (precision == 0) {
161 return;
162 }
163
164 if (maxInt <= scale) {
165 setBcdToZero();
166 return;
167 }
168
169 int32_t magnitude = getMagnitude();
170 if (maxInt <= magnitude) {
171 popFromLeft(magnitude - maxInt + 1);
172 compact();
173 }
174}
175
176uint64_t DecimalQuantity::getPositionFingerprint() const {
177 uint64_t fingerprint = 0;
178 fingerprint ^= (lReqPos << 16);
179 fingerprint ^= (static_cast<uint64_t>(rReqPos) << 32);
180 return fingerprint;
181}
182
183void DecimalQuantity::roundToIncrement(double roundingIncrement, RoundingMode roundingMode,
184 UErrorCode& status) {
185 // Do not call this method with an increment having only a 1 or a 5 digit!
186 // Use a more efficient call to either roundToMagnitude() or roundToNickel().
187 // Check a few popular rounding increments; a more thorough check is in Java.
188 U_ASSERT(roundingIncrement != 0.01);
189 U_ASSERT(roundingIncrement != 0.05);
190 U_ASSERT(roundingIncrement != 0.1);
191 U_ASSERT(roundingIncrement != 0.5);
192 U_ASSERT(roundingIncrement != 1);
193 U_ASSERT(roundingIncrement != 5);
194
195 DecNum incrementDN;
196 incrementDN.setTo(roundingIncrement, status);
197 if (U_FAILURE(status)) { return; }
198
199 // Divide this DecimalQuantity by the increment, round, then multiply back.
200 divideBy(incrementDN, status);
201 if (U_FAILURE(status)) { return; }
202 roundToMagnitude(0, roundingMode, status);
203 if (U_FAILURE(status)) { return; }
204 multiplyBy(incrementDN, status);
205 if (U_FAILURE(status)) { return; }
206}
207
208void DecimalQuantity::multiplyBy(const DecNum& multiplicand, UErrorCode& status) {
209 if (isZeroish()) {
210 return;
211 }
212 // Convert to DecNum, multiply, and convert back.
213 DecNum decnum;
214 toDecNum(decnum, status);
215 if (U_FAILURE(status)) { return; }
216 decnum.multiplyBy(multiplicand, status);
217 if (U_FAILURE(status)) { return; }
218 setToDecNum(decnum, status);
219}
220
221void DecimalQuantity::divideBy(const DecNum& divisor, UErrorCode& status) {
222 if (isZeroish()) {
223 return;
224 }
225 // Convert to DecNum, multiply, and convert back.
226 DecNum decnum;
227 toDecNum(decnum, status);
228 if (U_FAILURE(status)) { return; }
229 decnum.divideBy(divisor, status);
230 if (U_FAILURE(status)) { return; }
231 setToDecNum(decnum, status);
232}
233
234void DecimalQuantity::negate() {
235 flags ^= NEGATIVE_FLAG;
236}
237
238int32_t DecimalQuantity::getMagnitude() const {
239 U_ASSERT(precision != 0);
240 return scale + precision - 1;
241}
242
243bool DecimalQuantity::adjustMagnitude(int32_t delta) {
244 if (precision != 0) {
245 // i.e., scale += delta; origDelta += delta
246 bool overflow = uprv_add32_overflow(scale, delta, &scale);
247 overflow = uprv_add32_overflow(origDelta, delta, &origDelta) || overflow;
248 // Make sure that precision + scale won't overflow, either
249 int32_t dummy;
250 overflow = overflow || uprv_add32_overflow(scale, precision, &dummy);
251 return overflow;
252 }
253 return false;
254}
255
256double DecimalQuantity::getPluralOperand(PluralOperand operand) const {
257 // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
258 // See the comment at the top of this file explaining the "isApproximate" field.
259 U_ASSERT(!isApproximate);
260
261 switch (operand) {
262 case PLURAL_OPERAND_I:
263 // Invert the negative sign if necessary
264 return static_cast<double>(isNegative() ? -toLong(true) : toLong(true));
265 case PLURAL_OPERAND_F:
266 return static_cast<double>(toFractionLong(true));
267 case PLURAL_OPERAND_T:
268 return static_cast<double>(toFractionLong(false));
269 case PLURAL_OPERAND_V:
270 return fractionCount();
271 case PLURAL_OPERAND_W:
272 return fractionCountWithoutTrailingZeros();
273 case PLURAL_OPERAND_E:
274 return static_cast<double>(getExponent());
275 default:
276 return std::abs(toDouble());
277 }
278}
279
280int32_t DecimalQuantity::getExponent() const {
281 return exponent;
282}
283
284void DecimalQuantity::adjustExponent(int delta) {
285 exponent = exponent + delta;
286}
287
288bool DecimalQuantity::hasIntegerValue() const {
289 return scale >= 0;
290}
291
292int32_t DecimalQuantity::getUpperDisplayMagnitude() const {
293 // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
294 // See the comment in the header file explaining the "isApproximate" field.
295 U_ASSERT(!isApproximate);
296
297 int32_t magnitude = scale + precision;
298 int32_t result = (lReqPos > magnitude) ? lReqPos : magnitude;
299 return result - 1;
300}
301
302int32_t DecimalQuantity::getLowerDisplayMagnitude() const {
303 // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
304 // See the comment in the header file explaining the "isApproximate" field.
305 U_ASSERT(!isApproximate);
306
307 int32_t magnitude = scale;
308 int32_t result = (rReqPos < magnitude) ? rReqPos : magnitude;
309 return result;
310}
311
312int8_t DecimalQuantity::getDigit(int32_t magnitude) const {
313 // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
314 // See the comment at the top of this file explaining the "isApproximate" field.
315 U_ASSERT(!isApproximate);
316
317 return getDigitPos(magnitude - scale);
318}
319
320int32_t DecimalQuantity::fractionCount() const {
321 int32_t fractionCountWithExponent = -getLowerDisplayMagnitude() - exponent;
322 return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0;
323}
324
325int32_t DecimalQuantity::fractionCountWithoutTrailingZeros() const {
326 int32_t fractionCountWithExponent = -scale - exponent;
327 return fractionCountWithExponent > 0 ? fractionCountWithExponent : 0; // max(-fractionCountWithExponent, 0)
328}
329
330bool DecimalQuantity::isNegative() const {
331 return (flags & NEGATIVE_FLAG) != 0;
332}
333
334Signum DecimalQuantity::signum() const {
335 bool isZero = (isZeroish() && !isInfinite());
336 bool isNeg = isNegative();
337 if (isZero && isNeg) {
338 return SIGNUM_NEG_ZERO;
339 } else if (isZero) {
340 return SIGNUM_POS_ZERO;
341 } else if (isNeg) {
342 return SIGNUM_NEG;
343 } else {
344 return SIGNUM_POS;
345 }
346}
347
348bool DecimalQuantity::isInfinite() const {
349 return (flags & INFINITY_FLAG) != 0;
350}
351
352bool DecimalQuantity::isNaN() const {
353 return (flags & NAN_FLAG) != 0;
354}
355
356bool DecimalQuantity::isZeroish() const {
357 return precision == 0;
358}
359
360DecimalQuantity &DecimalQuantity::setToInt(int32_t n) {
361 setBcdToZero();
362 flags = 0;
363 if (n == INT32_MIN) {
364 flags |= NEGATIVE_FLAG;
365 // leave as INT32_MIN; handled below in _setToInt()
366 } else if (n < 0) {
367 flags |= NEGATIVE_FLAG;
368 n = -n;
369 }
370 if (n != 0) {
371 _setToInt(n);
372 compact();
373 }
374 return *this;
375}
376
377void DecimalQuantity::_setToInt(int32_t n) {
378 if (n == INT32_MIN) {
379 readLongToBcd(-static_cast<int64_t>(n));
380 } else {
381 readIntToBcd(n);
382 }
383}
384
385DecimalQuantity &DecimalQuantity::setToLong(int64_t n) {
386 setBcdToZero();
387 flags = 0;
388 if (n < 0 && n > INT64_MIN) {
389 flags |= NEGATIVE_FLAG;
390 n = -n;
391 }
392 if (n != 0) {
393 _setToLong(n);
394 compact();
395 }
396 return *this;
397}
398
399void DecimalQuantity::_setToLong(int64_t n) {
400 if (n == INT64_MIN) {
401 DecNum decnum;
402 UErrorCode localStatus = U_ZERO_ERROR;
403 decnum.setTo("9.223372036854775808E+18", localStatus);
404 if (U_FAILURE(localStatus)) { return; } // unexpected
405 flags |= NEGATIVE_FLAG;
406 readDecNumberToBcd(decnum);
407 } else if (n <= INT32_MAX) {
408 readIntToBcd(static_cast<int32_t>(n));
409 } else {
410 readLongToBcd(n);
411 }
412}
413
414DecimalQuantity &DecimalQuantity::setToDouble(double n) {
415 setBcdToZero();
416 flags = 0;
417 // signbit() from <math.h> handles +0.0 vs -0.0
418 if (std::signbit(n)) {
419 flags |= NEGATIVE_FLAG;
420 n = -n;
421 }
422 if (std::isnan(n) != 0) {
423 flags |= NAN_FLAG;
424 } else if (std::isfinite(n) == 0) {
425 flags |= INFINITY_FLAG;
426 } else if (n != 0) {
427 _setToDoubleFast(n);
428 compact();
429 }
430 return *this;
431}
432
433void DecimalQuantity::_setToDoubleFast(double n) {
434 isApproximate = true;
435 origDouble = n;
436 origDelta = 0;
437
438 // Make sure the double is an IEEE 754 double. If not, fall back to the slow path right now.
439 // TODO: Make a fast path for other types of doubles.
440 if (!std::numeric_limits<double>::is_iec559) {
441 convertToAccurateDouble();
442 return;
443 }
444
445 // To get the bits from the double, use memcpy, which takes care of endianness.
446 uint64_t ieeeBits;
447 uprv_memcpy(&ieeeBits, &n, sizeof(n));
448 int32_t exponent = static_cast<int32_t>((ieeeBits & 0x7ff0000000000000L) >> 52) - 0x3ff;
449
450 // Not all integers can be represented exactly for exponent > 52
451 if (exponent <= 52 && static_cast<int64_t>(n) == n) {
452 _setToLong(static_cast<int64_t>(n));
453 return;
454 }
455
456 if (exponent == -1023 || exponent == 1024) {
457 // The extreme values of exponent are special; use slow path.
458 convertToAccurateDouble();
459 return;
460 }
461
462 // 3.3219... is log2(10)
463 auto fracLength = static_cast<int32_t> ((52 - exponent) / 3.32192809488736234787031942948939017586);
464 if (fracLength >= 0) {
465 int32_t i = fracLength;
466 // 1e22 is the largest exact double.
467 for (; i >= 22; i -= 22) n *= 1e22;
468 n *= DOUBLE_MULTIPLIERS[i];
469 } else {
470 int32_t i = fracLength;
471 // 1e22 is the largest exact double.
472 for (; i <= -22; i += 22) n /= 1e22;
473 n /= DOUBLE_MULTIPLIERS[-i];
474 }
475 auto result = static_cast<int64_t>(uprv_round(n));
476 if (result != 0) {
477 _setToLong(result);
478 scale -= fracLength;
479 }
480}
481
482void DecimalQuantity::convertToAccurateDouble() {
483 U_ASSERT(origDouble != 0);
484 int32_t delta = origDelta;
485
486 // Call the slow oracle function (Double.toString in Java, DoubleToAscii in C++).
487 char buffer[DoubleToStringConverter::kBase10MaximalLength + 1];
488 bool sign; // unused; always positive
489 int32_t length;
490 int32_t point;
491 DoubleToStringConverter::DoubleToAscii(
492 origDouble,
493 DoubleToStringConverter::DtoaMode::SHORTEST,
494 0,
495 buffer,
496 sizeof(buffer),
497 &sign,
498 &length,
499 &point
500 );
501
502 setBcdToZero();
503 readDoubleConversionToBcd(buffer, length, point);
504 scale += delta;
505 explicitExactDouble = true;
506}
507
508DecimalQuantity &DecimalQuantity::setToDecNumber(StringPiece n, UErrorCode& status) {
509 setBcdToZero();
510 flags = 0;
511
512 // Compute the decNumber representation
513 DecNum decnum;
514 decnum.setTo(n, status);
515
516 _setToDecNum(decnum, status);
517 return *this;
518}
519
520DecimalQuantity& DecimalQuantity::setToDecNum(const DecNum& decnum, UErrorCode& status) {
521 setBcdToZero();
522 flags = 0;
523
524 _setToDecNum(decnum, status);
525 return *this;
526}
527
528void DecimalQuantity::_setToDecNum(const DecNum& decnum, UErrorCode& status) {
529 if (U_FAILURE(status)) { return; }
530 if (decnum.isNegative()) {
531 flags |= NEGATIVE_FLAG;
532 }
533 if (!decnum.isZero()) {
534 readDecNumberToBcd(decnum);
535 compact();
536 }
537}
538
539int64_t DecimalQuantity::toLong(bool truncateIfOverflow) const {
540 // NOTE: Call sites should be guarded by fitsInLong(), like this:
541 // if (dq.fitsInLong()) { /* use dq.toLong() */ } else { /* use some fallback */ }
542 // Fallback behavior upon truncateIfOverflow is to truncate at 17 digits.
543 uint64_t result = 0L;
544 int32_t upperMagnitude = exponent + scale + precision - 1;
545 if (truncateIfOverflow) {
546 upperMagnitude = std::min(upperMagnitude, 17);
547 }
548 for (int32_t magnitude = upperMagnitude; magnitude >= 0; magnitude--) {
549 result = result * 10 + getDigitPos(magnitude - scale - exponent);
550 }
551 if (isNegative()) {
552 return static_cast<int64_t>(0LL - result); // i.e., -result
553 }
554 return static_cast<int64_t>(result);
555}
556
557uint64_t DecimalQuantity::toFractionLong(bool includeTrailingZeros) const {
558 uint64_t result = 0L;
559 int32_t magnitude = -1 - exponent;
560 int32_t lowerMagnitude = scale;
561 if (includeTrailingZeros) {
562 lowerMagnitude = std::min(lowerMagnitude, rReqPos);
563 }
564 for (; magnitude >= lowerMagnitude && result <= 1e18L; magnitude--) {
565 result = result * 10 + getDigitPos(magnitude - scale);
566 }
567 // Remove trailing zeros; this can happen during integer overflow cases.
568 if (!includeTrailingZeros) {
569 while (result > 0 && (result % 10) == 0) {
570 result /= 10;
571 }
572 }
573 return result;
574}
575
576bool DecimalQuantity::fitsInLong(bool ignoreFraction) const {
577 if (isInfinite() || isNaN()) {
578 return false;
579 }
580 if (isZeroish()) {
581 return true;
582 }
583 if (exponent + scale < 0 && !ignoreFraction) {
584 return false;
585 }
586 int magnitude = getMagnitude();
587 if (magnitude < 18) {
588 return true;
589 }
590 if (magnitude > 18) {
591 return false;
592 }
593 // Hard case: the magnitude is 10^18.
594 // The largest int64 is: 9,223,372,036,854,775,807
595 for (int p = 0; p < precision; p++) {
596 int8_t digit = getDigit(18 - p);
597 static int8_t INT64_BCD[] = { 9, 2, 2, 3, 3, 7, 2, 0, 3, 6, 8, 5, 4, 7, 7, 5, 8, 0, 8 };
598 if (digit < INT64_BCD[p]) {
599 return true;
600 } else if (digit > INT64_BCD[p]) {
601 return false;
602 }
603 }
604 // Exactly equal to max long plus one.
605 return isNegative();
606}
607
608double DecimalQuantity::toDouble() const {
609 // If this assertion fails, you need to call roundToInfinity() or some other rounding method.
610 // See the comment in the header file explaining the "isApproximate" field.
611 U_ASSERT(!isApproximate);
612
613 if (isNaN()) {
614 return NAN;
615 } else if (isInfinite()) {
616 return isNegative() ? -INFINITY : INFINITY;
617 }
618
619 // We are processing well-formed input, so we don't need any special options to StringToDoubleConverter.
620 StringToDoubleConverter converter(0, 0, 0, "", "");
621 UnicodeString numberString = this->toScientificString();
622 int32_t count;
623 return converter.StringToDouble(
624 reinterpret_cast<const uint16_t*>(numberString.getBuffer()),
625 numberString.length(),
626 &count);
627}
628
629void DecimalQuantity::toDecNum(DecNum& output, UErrorCode& status) const {
630 // Special handling for zero
631 if (precision == 0) {
632 output.setTo("0", status);
633 }
634
635 // Use the BCD constructor. We need to do a little bit of work to convert, though.
636 // The decNumber constructor expects most-significant first, but we store least-significant first.
637 MaybeStackArray<uint8_t, 20> ubcd(precision);
638 for (int32_t m = 0; m < precision; m++) {
639 ubcd[precision - m - 1] = static_cast<uint8_t>(getDigitPos(m));
640 }
641 output.setTo(ubcd.getAlias(), precision, scale, isNegative(), status);
642}
643
644void DecimalQuantity::truncate() {
645 if (scale < 0) {
646 shiftRight(-scale);
647 scale = 0;
648 compact();
649 }
650}
651
652void DecimalQuantity::roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
653 roundToMagnitude(magnitude, roundingMode, true, status);
654}
655
656void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status) {
657 roundToMagnitude(magnitude, roundingMode, false, status);
658}
659
660void DecimalQuantity::roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status) {
661 // The position in the BCD at which rounding will be performed; digits to the right of position
662 // will be rounded away.
663 int position = safeSubtract(magnitude, scale);
664
665 // "trailing" = least significant digit to the left of rounding
666 int8_t trailingDigit = getDigitPos(position);
667
668 if (position <= 0 && !isApproximate && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
669 // All digits are to the left of the rounding magnitude.
670 } else if (precision == 0) {
671 // No rounding for zero.
672 } else {
673 // Perform rounding logic.
674 // "leading" = most significant digit to the right of rounding
675 int8_t leadingDigit = getDigitPos(safeSubtract(position, 1));
676
677 // Compute which section of the number we are in.
678 // EDGE means we are at the bottom or top edge, like 1.000 or 1.999 (used by doubles)
679 // LOWER means we are between the bottom edge and the midpoint, like 1.391
680 // MIDPOINT means we are exactly in the middle, like 1.500
681 // UPPER means we are between the midpoint and the top edge, like 1.916
682 roundingutils::Section section;
683 if (!isApproximate) {
684 if (nickel && trailingDigit != 2 && trailingDigit != 7) {
685 // Nickel rounding, and not at .02x or .07x
686 if (trailingDigit < 2) {
687 // .00, .01 => down to .00
688 section = roundingutils::SECTION_LOWER;
689 } else if (trailingDigit < 5) {
690 // .03, .04 => up to .05
691 section = roundingutils::SECTION_UPPER;
692 } else if (trailingDigit < 7) {
693 // .05, .06 => down to .05
694 section = roundingutils::SECTION_LOWER;
695 } else {
696 // .08, .09 => up to .10
697 section = roundingutils::SECTION_UPPER;
698 }
699 } else if (leadingDigit < 5) {
700 // Includes nickel rounding .020-.024 and .070-.074
701 section = roundingutils::SECTION_LOWER;
702 } else if (leadingDigit > 5) {
703 // Includes nickel rounding .026-.029 and .076-.079
704 section = roundingutils::SECTION_UPPER;
705 } else {
706 // Includes nickel rounding .025 and .075
707 section = roundingutils::SECTION_MIDPOINT;
708 for (int p = safeSubtract(position, 2); p >= 0; p--) {
709 if (getDigitPos(p) != 0) {
710 section = roundingutils::SECTION_UPPER;
711 break;
712 }
713 }
714 }
715 } else {
716 int32_t p = safeSubtract(position, 2);
717 int32_t minP = uprv_max(0, precision - 14);
718 if (leadingDigit == 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
719 section = roundingutils::SECTION_LOWER_EDGE;
720 for (; p >= minP; p--) {
721 if (getDigitPos(p) != 0) {
722 section = roundingutils::SECTION_LOWER;
723 break;
724 }
725 }
726 } else if (leadingDigit == 4 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
727 section = roundingutils::SECTION_MIDPOINT;
728 for (; p >= minP; p--) {
729 if (getDigitPos(p) != 9) {
730 section = roundingutils::SECTION_LOWER;
731 break;
732 }
733 }
734 } else if (leadingDigit == 5 && (!nickel || trailingDigit == 2 || trailingDigit == 7)) {
735 section = roundingutils::SECTION_MIDPOINT;
736 for (; p >= minP; p--) {
737 if (getDigitPos(p) != 0) {
738 section = roundingutils::SECTION_UPPER;
739 break;
740 }
741 }
742 } else if (leadingDigit == 9 && (!nickel || trailingDigit == 4 || trailingDigit == 9)) {
743 section = roundingutils::SECTION_UPPER_EDGE;
744 for (; p >= minP; p--) {
745 if (getDigitPos(p) != 9) {
746 section = roundingutils::SECTION_UPPER;
747 break;
748 }
749 }
750 } else if (nickel && trailingDigit != 2 && trailingDigit != 7) {
751 // Nickel rounding, and not at .02x or .07x
752 if (trailingDigit < 2) {
753 // .00, .01 => down to .00
754 section = roundingutils::SECTION_LOWER;
755 } else if (trailingDigit < 5) {
756 // .03, .04 => up to .05
757 section = roundingutils::SECTION_UPPER;
758 } else if (trailingDigit < 7) {
759 // .05, .06 => down to .05
760 section = roundingutils::SECTION_LOWER;
761 } else {
762 // .08, .09 => up to .10
763 section = roundingutils::SECTION_UPPER;
764 }
765 } else if (leadingDigit < 5) {
766 // Includes nickel rounding .020-.024 and .070-.074
767 section = roundingutils::SECTION_LOWER;
768 } else {
769 // Includes nickel rounding .026-.029 and .076-.079
770 section = roundingutils::SECTION_UPPER;
771 }
772
773 bool roundsAtMidpoint = roundingutils::roundsAtMidpoint(roundingMode);
774 if (safeSubtract(position, 1) < precision - 14 ||
775 (roundsAtMidpoint && section == roundingutils::SECTION_MIDPOINT) ||
776 (!roundsAtMidpoint && section < 0 /* i.e. at upper or lower edge */)) {
777 // Oops! This means that we have to get the exact representation of the double,
778 // because the zone of uncertainty is along the rounding boundary.
779 convertToAccurateDouble();
780 roundToMagnitude(magnitude, roundingMode, nickel, status); // start over
781 return;
782 }
783
784 // Turn off the approximate double flag, since the value is now confirmed to be exact.
785 isApproximate = false;
786 origDouble = 0.0;
787 origDelta = 0;
788
789 if (position <= 0 && (!nickel || trailingDigit == 0 || trailingDigit == 5)) {
790 // All digits are to the left of the rounding magnitude.
791 return;
792 }
793
794 // Good to continue rounding.
795 if (section == -1) { section = roundingutils::SECTION_LOWER; }
796 if (section == -2) { section = roundingutils::SECTION_UPPER; }
797 }
798
799 // Nickel rounding "half even" goes to the nearest whole (away from the 5).
800 bool isEven = nickel
801 ? (trailingDigit < 2 || trailingDigit > 7
802 || (trailingDigit == 2 && section != roundingutils::SECTION_UPPER)
803 || (trailingDigit == 7 && section == roundingutils::SECTION_UPPER))
804 : (trailingDigit % 2) == 0;
805
806 bool roundDown = roundingutils::getRoundingDirection(isEven,
807 isNegative(),
808 section,
809 roundingMode,
810 status);
811 if (U_FAILURE(status)) {
812 return;
813 }
814
815 // Perform truncation
816 if (position >= precision) {
817 setBcdToZero();
818 scale = magnitude;
819 } else {
820 shiftRight(position);
821 }
822
823 if (nickel) {
824 if (trailingDigit < 5 && roundDown) {
825 setDigitPos(0, 0);
826 compact();
827 return;
828 } else if (trailingDigit >= 5 && !roundDown) {
829 setDigitPos(0, 9);
830 trailingDigit = 9;
831 // do not return: use the bubbling logic below
832 } else {
833 setDigitPos(0, 5);
834 // compact not necessary: digit at position 0 is nonzero
835 return;
836 }
837 }
838
839 // Bubble the result to the higher digits
840 if (!roundDown) {
841 if (trailingDigit == 9) {
842 int bubblePos = 0;
843 // Note: in the long implementation, the most digits BCD can have at this point is
844 // 15, so bubblePos <= 15 and getDigitPos(bubblePos) is safe.
845 for (; getDigitPos(bubblePos) == 9; bubblePos++) {}
846 shiftRight(bubblePos); // shift off the trailing 9s
847 }
848 int8_t digit0 = getDigitPos(0);
849 U_ASSERT(digit0 != 9);
850 setDigitPos(0, static_cast<int8_t>(digit0 + 1));
851 precision += 1; // in case an extra digit got added
852 }
853
854 compact();
855 }
856}
857
858void DecimalQuantity::roundToInfinity() {
859 if (isApproximate) {
860 convertToAccurateDouble();
861 }
862}
863
864void DecimalQuantity::appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger) {
865 U_ASSERT(leadingZeros >= 0);
866
867 // Zero requires special handling to maintain the invariant that the least-significant digit
868 // in the BCD is nonzero.
869 if (value == 0) {
870 if (appendAsInteger && precision != 0) {
871 scale += leadingZeros + 1;
872 }
873 return;
874 }
875
876 // Deal with trailing zeros
877 if (scale > 0) {
878 leadingZeros += scale;
879 if (appendAsInteger) {
880 scale = 0;
881 }
882 }
883
884 // Append digit
885 shiftLeft(leadingZeros + 1);
886 setDigitPos(0, value);
887
888 // Fix scale if in integer mode
889 if (appendAsInteger) {
890 scale += leadingZeros + 1;
891 }
892}
893
894UnicodeString DecimalQuantity::toPlainString() const {
895 U_ASSERT(!isApproximate);
896 UnicodeString sb;
897 if (isNegative()) {
898 sb.append(u'-');
899 }
900 if (precision == 0) {
901 sb.append(u'0');
902 return sb;
903 }
904 int32_t upper = scale + precision + exponent - 1;
905 int32_t lower = scale + exponent;
906 if (upper < lReqPos - 1) {
907 upper = lReqPos - 1;
908 }
909 if (lower > rReqPos) {
910 lower = rReqPos;
911 }
912 int32_t p = upper;
913 if (p < 0) {
914 sb.append(u'0');
915 }
916 for (; p >= 0; p--) {
917 sb.append(u'0' + getDigitPos(p - scale - exponent));
918 }
919 if (lower < 0) {
920 sb.append(u'.');
921 }
922 for(; p >= lower; p--) {
923 sb.append(u'0' + getDigitPos(p - scale - exponent));
924 }
925 return sb;
926}
927
928UnicodeString DecimalQuantity::toScientificString() const {
929 U_ASSERT(!isApproximate);
930 UnicodeString result;
931 if (isNegative()) {
932 result.append(u'-');
933 }
934 if (precision == 0) {
935 result.append(u"0E+0", -1);
936 return result;
937 }
938 int32_t upperPos = precision - 1;
939 int32_t lowerPos = 0;
940 int32_t p = upperPos;
941 result.append(u'0' + getDigitPos(p));
942 if ((--p) >= lowerPos) {
943 result.append(u'.');
944 for (; p >= lowerPos; p--) {
945 result.append(u'0' + getDigitPos(p));
946 }
947 }
948 result.append(u'E');
949 int32_t _scale = upperPos + scale + exponent;
950 if (_scale == INT32_MIN) {
951 result.append({u"-2147483648", -1});
952 return result;
953 } else if (_scale < 0) {
954 _scale *= -1;
955 result.append(u'-');
956 } else {
957 result.append(u'+');
958 }
959 if (_scale == 0) {
960 result.append(u'0');
961 }
962 int32_t insertIndex = result.length();
963 while (_scale > 0) {
964 std::div_t res = std::div(_scale, 10);
965 result.insert(insertIndex, u'0' + res.rem);
966 _scale = res.quot;
967 }
968 return result;
969}
970
971////////////////////////////////////////////////////
972/// End of DecimalQuantity_AbstractBCD.java ///
973/// Start of DecimalQuantity_DualStorageBCD.java ///
974////////////////////////////////////////////////////
975
976int8_t DecimalQuantity::getDigitPos(int32_t position) const {
977 if (usingBytes) {
978 if (position < 0 || position >= precision) { return 0; }
979 return fBCD.bcdBytes.ptr[position];
980 } else {
981 if (position < 0 || position >= 16) { return 0; }
982 return (int8_t) ((fBCD.bcdLong >> (position * 4)) & 0xf);
983 }
984}
985
986void DecimalQuantity::setDigitPos(int32_t position, int8_t value) {
987 U_ASSERT(position >= 0);
988 if (usingBytes) {
989 ensureCapacity(position + 1);
990 fBCD.bcdBytes.ptr[position] = value;
991 } else if (position >= 16) {
992 switchStorage();
993 ensureCapacity(position + 1);
994 fBCD.bcdBytes.ptr[position] = value;
995 } else {
996 int shift = position * 4;
997 fBCD.bcdLong = (fBCD.bcdLong & ~(0xfL << shift)) | ((long) value << shift);
998 }
999}
1000
1001void DecimalQuantity::shiftLeft(int32_t numDigits) {
1002 if (!usingBytes && precision + numDigits > 16) {
1003 switchStorage();
1004 }
1005 if (usingBytes) {
1006 ensureCapacity(precision + numDigits);
1007 int i = precision + numDigits - 1;
1008 for (; i >= numDigits; i--) {
1009 fBCD.bcdBytes.ptr[i] = fBCD.bcdBytes.ptr[i - numDigits];
1010 }
1011 for (; i >= 0; i--) {
1012 fBCD.bcdBytes.ptr[i] = 0;
1013 }
1014 } else {
1015 fBCD.bcdLong <<= (numDigits * 4);
1016 }
1017 scale -= numDigits;
1018 precision += numDigits;
1019}
1020
1021void 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
1037void 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
1050void 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
1065void 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
1079void 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
1104void 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
1122void 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
1142void 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
1186void DecimalQuantity::ensureCapacity() {
1187 ensureCapacity(40);
1188}
1189
1190void 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
1213void 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
1238void 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
1248void 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
1262const 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
1300bool 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
1326UnicodeString DecimalQuantity::toString() const {
1327 MaybeStackArray<char, 30> digits(precision + 1);
1328 for (int32_t i = 0; i < precision; i++) {
1329 digits[i] = getDigitPos(precision - i - 1) + '0';
1330 }
1331 digits[precision] = 0; // terminate buffer
1332 char buffer8[100];
1333 snprintf(
1334 buffer8,
1335 sizeof(buffer8),
1336 "<DecimalQuantity %d:%d %s %s%s%s%d>",
1337 lReqPos,
1338 rReqPos,
1339 (usingBytes ? "bytes" : "long"),
1340 (isNegative() ? "-" : ""),
1341 (precision == 0 ? "0" : digits.getAlias()),
1342 "E",
1343 scale);
1344 return UnicodeString(buffer8, -1, US_INV);
1345}
1346
1347#endif /* #if !UCONFIG_NO_FORMATTING */
1348