Coverage Report

Created: 2023-02-22 06:51

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