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 #ifndef __NUMBER_DECIMALQUANTITY_H__ 8 #define __NUMBER_DECIMALQUANTITY_H__ 9 10 #include <cstdint> 11 #include "unicode/umachine.h" 12 #include "standardplural.h" 13 #include "plurrule_impl.h" 14 #include "number_types.h" 15 16 U_NAMESPACE_BEGIN namespace number { 17 namespace impl { 18 19 // Forward-declare (maybe don't want number_utils.h included here): 20 class DecNum; 21 22 /** 23 * A class for representing a number to be processed by the decimal formatting pipeline. Includes 24 * methods for rounding, plural rules, and decimal digit extraction. 25 * 26 * <p>By design, this is NOT IMMUTABLE and NOT THREAD SAFE. It is intended to be an intermediate 27 * object holding state during a pass through the decimal formatting pipeline. 28 * 29 * <p>Represents numbers and digit display properties using Binary Coded Decimal (BCD). 30 * 31 * <p>Java has multiple implementations for testing, but C++ has only one implementation. 32 */ 33 class U_I18N_API DecimalQuantity : public IFixedDecimal, public UMemory { 34 public: 35 /** Copy constructor. */ 36 DecimalQuantity(const DecimalQuantity &other); 37 38 /** Move constructor. */ 39 DecimalQuantity(DecimalQuantity &&src) noexcept; 40 41 DecimalQuantity(); 42 43 ~DecimalQuantity() override; 44 45 /** 46 * Sets this instance to be equal to another instance. 47 * 48 * @param other The instance to copy from. 49 */ 50 DecimalQuantity &operator=(const DecimalQuantity &other); 51 52 /** Move assignment */ 53 DecimalQuantity &operator=(DecimalQuantity&& src) noexcept; 54 55 /** 56 * Sets the minimum integer digits that this {@link DecimalQuantity} should generate. 57 * This method does not perform rounding. 58 * 59 * @param minInt The minimum number of integer digits. 60 */ 61 void setMinInteger(int32_t minInt); 62 63 /** 64 * Sets the minimum fraction digits that this {@link DecimalQuantity} should generate. 65 * This method does not perform rounding. 66 * 67 * @param minFrac The minimum number of fraction digits. 68 */ 69 void setMinFraction(int32_t minFrac); 70 71 /** 72 * Truncates digits from the upper magnitude of the number in order to satisfy the 73 * specified maximum number of integer digits. 74 * 75 * @param maxInt The maximum number of integer digits. 76 */ 77 void applyMaxInteger(int32_t maxInt); 78 79 /** 80 * Rounds the number to a specified interval, such as 0.05. 81 * 82 * <p>If rounding to a power of ten, use the more efficient {@link #roundToMagnitude} instead. 83 * 84 * @param increment The increment to which to round. 85 * @param magnitude The power of 10 to which to round. 86 * @param roundingMode The {@link RoundingMode} to use if rounding is necessary. 87 */ 88 void roundToIncrement( 89 uint64_t increment, 90 digits_t magnitude, 91 RoundingMode roundingMode, 92 UErrorCode& status); 93 94 /** Removes all fraction digits. */ 95 void truncate(); 96 97 /** 98 * Rounds the number to the nearest multiple of 5 at the specified magnitude. 99 * For example, when magnitude == -2, this performs rounding to the nearest 0.05. 100 * 101 * @param magnitude The magnitude at which the digit should become either 0 or 5. 102 * @param roundingMode Rounding strategy. 103 */ 104 void roundToNickel(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status); 105 106 /** 107 * Rounds the number to a specified magnitude (power of ten). 108 * 109 * @param roundingMagnitude The power of ten to which to round. For example, a value of -2 will 110 * round to 2 decimal places. 111 * @param roundingMode The {@link RoundingMode} to use if rounding is necessary. 112 */ 113 void roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, UErrorCode& status); 114 115 /** 116 * Rounds the number to an infinite number of decimal points. This has no effect except for 117 * forcing the double in {@link DecimalQuantity_AbstractBCD} to adopt its exact representation. 118 */ 119 void roundToInfinity(); 120 121 /** 122 * Multiply the internal value. Uses decNumber. 123 * 124 * @param multiplicand The value by which to multiply. 125 */ 126 void multiplyBy(const DecNum& multiplicand, UErrorCode& status); 127 128 /** 129 * Divide the internal value. Uses decNumber. 130 * 131 * @param multiplicand The value by which to multiply. 132 */ 133 void divideBy(const DecNum& divisor, UErrorCode& status); 134 135 /** Flips the sign from positive to negative and back. */ 136 void negate(); 137 138 /** 139 * Scales the number by a power of ten. For example, if the value is currently "1234.56", calling 140 * this method with delta=-3 will change the value to "1.23456". 141 * 142 * @param delta The number of magnitudes of ten to change by. 143 * @return true if integer overflow occurred; false otherwise. 144 */ 145 bool adjustMagnitude(int32_t delta); 146 147 /** 148 * Scales the number such that the least significant nonzero digit is at magnitude 0. 149 * 150 * @return The previous magnitude of the least significant digit. 151 */ 152 int32_t adjustToZeroScale(); 153 154 /** 155 * @return The power of ten corresponding to the most significant nonzero digit. 156 * The number must not be zero. 157 */ 158 int32_t getMagnitude() const; 159 160 /** 161 * @return The value of the (suppressed) exponent after the number has been 162 * put into a notation with exponents (ex: compact, scientific). Ex: given 163 * the number 1000 as "1K" / "1E3", the return value will be 3 (positive). 164 */ 165 int32_t getExponent() const; 166 167 /** 168 * Adjusts the value for the (suppressed) exponent stored when using 169 * notation with exponents (ex: compact, scientific). 170 * 171 * <p>Adjusting the exponent is decoupled from {@link #adjustMagnitude} in 172 * order to allow flexibility for {@link StandardPlural} to be selected in 173 * formatting (ex: for compact notation) either with or without the exponent 174 * applied in the value of the number. 175 * @param delta 176 * The value to adjust the exponent by. 177 */ 178 void adjustExponent(int32_t delta); 179 180 /** 181 * Resets the DecimalQuantity to the value before adjustMagnitude and adjustExponent. 182 */ 183 void resetExponent(); 184 185 /** 186 * @return Whether the value represented by this {@link DecimalQuantity} is 187 * zero, infinity, or NaN. 188 */ 189 bool isZeroish() const; 190 191 /** @return Whether the value represented by this {@link DecimalQuantity} is less than zero. */ 192 bool isNegative() const; 193 194 /** @return The appropriate value from the Signum enum. */ 195 Signum signum() const; 196 197 /** @return Whether the value represented by this {@link DecimalQuantity} is infinite. */ 198 bool isInfinite() const override; 199 200 /** @return Whether the value represented by this {@link DecimalQuantity} is not a number. */ 201 bool isNaN() const override; 202 203 /** 204 * Note: this method incorporates the value of {@code exponent} 205 * (for cases such as compact notation) to return the proper long value 206 * represented by the result. 207 * @param truncateIfOverflow if false and the number does NOT fit, fails with an assertion error. 208 */ 209 int64_t toLong(bool truncateIfOverflow = false) const; 210 211 /** 212 * Note: this method incorporates the value of {@code exponent} 213 * (for cases such as compact notation) to return the proper long value 214 * represented by the result. 215 */ 216 uint64_t toFractionLong(bool includeTrailingZeros) const; 217 218 /** 219 * Returns whether or not a Long can fully represent the value stored in this DecimalQuantity. 220 * @param ignoreFraction if true, silently ignore digits after the decimal place. 221 */ 222 bool fitsInLong(bool ignoreFraction = false) const; 223 224 /** @return The value contained in this {@link DecimalQuantity} approximated as a double. */ 225 double toDouble() const; 226 227 /** Computes a DecNum representation of this DecimalQuantity, saving it to the output parameter. */ 228 DecNum& toDecNum(DecNum& output, UErrorCode& status) const; 229 230 DecimalQuantity &setToInt(int32_t n); 231 232 DecimalQuantity &setToLong(int64_t n); 233 234 DecimalQuantity &setToDouble(double n); 235 236 /** 237 * Produces a DecimalQuantity that was parsed from a string by the decNumber 238 * C Library. 239 * 240 * decNumber is similar to BigDecimal in Java, and supports parsing strings 241 * such as "123.456621E+40". 242 */ 243 DecimalQuantity &setToDecNumber(StringPiece n, UErrorCode& status); 244 245 /** Internal method if the caller already has a DecNum. */ 246 DecimalQuantity &setToDecNum(const DecNum& n, UErrorCode& status); 247 248 /** Returns a DecimalQuantity after parsing the input string. */ 249 static DecimalQuantity fromExponentString(UnicodeString n, UErrorCode& status); 250 251 /** 252 * Appends a digit, optionally with one or more leading zeros, to the end of the value represented 253 * by this DecimalQuantity. 254 * 255 * <p>The primary use of this method is to construct numbers during a parsing loop. It allows 256 * parsing to take advantage of the digit list infrastructure primarily designed for formatting. 257 * 258 * @param value The digit to append. 259 * @param leadingZeros The number of zeros to append before the digit. For example, if the value 260 * in this instance starts as 12.3, and you append a 4 with 1 leading zero, the value becomes 261 * 12.304. 262 * @param appendAsInteger If true, increase the magnitude of existing digits to make room for the 263 * new digit. If false, append to the end like a fraction digit. If true, there must not be 264 * any fraction digits already in the number. 265 * @internal 266 * @deprecated This API is ICU internal only. 267 */ 268 void appendDigit(int8_t value, int32_t leadingZeros, bool appendAsInteger); 269 270 double getPluralOperand(PluralOperand operand) const override; 271 272 bool hasIntegerValue() const override; 273 274 /** 275 * Gets the digit at the specified magnitude. For example, if the represented number is 12.3, 276 * getDigit(-1) returns 3, since 3 is the digit corresponding to 10^-1. 277 * 278 * @param magnitude The magnitude of the digit. 279 * @return The digit at the specified magnitude. 280 */ 281 int8_t getDigit(int32_t magnitude) const; 282 283 /** 284 * Gets the largest power of ten that needs to be displayed. The value returned by this function 285 * will be bounded between minInt and maxInt. 286 * 287 * @return The highest-magnitude digit to be displayed. 288 */ 289 int32_t getUpperDisplayMagnitude() const; 290 291 /** 292 * Gets the smallest power of ten that needs to be displayed. The value returned by this function 293 * will be bounded between -minFrac and -maxFrac. 294 * 295 * @return The lowest-magnitude digit to be displayed. 296 */ 297 int32_t getLowerDisplayMagnitude() const; 298 299 int32_t fractionCount() const; 300 301 int32_t fractionCountWithoutTrailingZeros() const; 302 303 void clear(); 304 305 /** This method is for internal testing only. */ 306 uint64_t getPositionFingerprint() const; 307 308 // /** 309 // * If the given {@link FieldPosition} is a {@link UFieldPosition}, populates it with the fraction 310 // * length and fraction long value. If the argument is not a {@link UFieldPosition}, nothing 311 // * happens. 312 // * 313 // * @param fp The {@link UFieldPosition} to populate. 314 // */ 315 // void populateUFieldPosition(FieldPosition fp); 316 317 /** 318 * Checks whether the bytes stored in this instance are all valid. For internal unit testing only. 319 * 320 * @return An error message if this instance is invalid, or null if this instance is healthy. 321 */ 322 const char16_t* checkHealth() const; 323 324 UnicodeString toString() const; 325 326 /** Returns the string in standard exponential notation. */ 327 UnicodeString toScientificString() const; 328 329 /** Returns the string without exponential notation. Slightly slower than toScientificString(). */ 330 UnicodeString toPlainString() const; 331 332 /** Returns the string using ASCII digits and using exponential notation for non-zero 333 exponents, following the UTS 35 specification for plural rule samples. */ 334 UnicodeString toExponentString() const; 335 336 /** Visible for testing */ isUsingBytes()337 inline bool isUsingBytes() { return usingBytes; } 338 339 /** Visible for testing */ isExplicitExactDouble()340 inline bool isExplicitExactDouble() { return explicitExactDouble; } 341 342 bool operator==(const DecimalQuantity& other) const; 343 344 inline bool operator!=(const DecimalQuantity& other) const { 345 return !(*this == other); 346 } 347 348 /** 349 * Bogus flag for when a DecimalQuantity is stored on the stack. 350 */ 351 bool bogus = false; 352 353 private: 354 /** 355 * The power of ten corresponding to the least significant digit in the BCD. For example, if this 356 * object represents the number "3.14", the BCD will be "0x314" and the scale will be -2. 357 * 358 * <p>Note that in {@link java.math.BigDecimal}, the scale is defined differently: the number of 359 * digits after the decimal place, which is the negative of our definition of scale. 360 */ 361 int32_t scale; 362 363 /** 364 * The number of digits in the BCD. For example, "1007" has BCD "0x1007" and precision 4. The 365 * maximum precision is 16 since a long can hold only 16 digits. 366 * 367 * <p>This value must be re-calculated whenever the value in bcd changes by using {@link 368 * #computePrecisionAndCompact()}. 369 */ 370 int32_t precision; 371 372 /** 373 * A bitmask of properties relating to the number represented by this object. 374 * 375 * @see #NEGATIVE_FLAG 376 * @see #INFINITY_FLAG 377 * @see #NAN_FLAG 378 */ 379 int8_t flags; 380 381 // The following three fields relate to the double-to-ascii fast path algorithm. 382 // When a double is given to DecimalQuantityBCD, it is converted to using a fast algorithm. The 383 // fast algorithm guarantees correctness to only the first ~12 digits of the double. The process 384 // of rounding the number ensures that the converted digits are correct, falling back to a slow- 385 // path algorithm if required. Therefore, if a DecimalQuantity is constructed from a double, it 386 // is *required* that roundToMagnitude(), roundToIncrement(), or roundToInfinity() is called. If 387 // you don't round, assertions will fail in certain other methods if you try calling them. 388 389 /** 390 * Whether the value in the BCD comes from the double fast path without having been rounded to 391 * ensure correctness 392 */ 393 UBool isApproximate; 394 395 /** 396 * The original number provided by the user and which is represented in BCD. Used when we need to 397 * re-compute the BCD for an exact double representation. 398 */ 399 double origDouble; 400 401 /** 402 * The change in magnitude relative to the original double. Used when we need to re-compute the 403 * BCD for an exact double representation. 404 */ 405 int32_t origDelta; 406 407 // Positions to keep track of leading and trailing zeros. 408 // lReqPos is the magnitude of the first required leading zero. 409 // rReqPos is the magnitude of the last required trailing zero. 410 int32_t lReqPos = 0; 411 int32_t rReqPos = 0; 412 413 // The value of the (suppressed) exponent after the number has been put into 414 // a notation with exponents (ex: compact, scientific). 415 int32_t exponent = 0; 416 417 /** 418 * The BCD of the 16 digits of the number represented by this object. Every 4 bits of the long map 419 * to one digit. For example, the number "12345" in BCD is "0x12345". 420 * 421 * <p>Whenever bcd changes internally, {@link #compact()} must be called, except in special cases 422 * like setting the digit to zero. 423 */ 424 union { 425 struct { 426 int8_t *ptr; 427 int32_t len; 428 } bcdBytes; 429 uint64_t bcdLong; 430 } fBCD; 431 432 bool usingBytes = false; 433 434 /** 435 * Whether this {@link DecimalQuantity} has been explicitly converted to an exact double. true if 436 * backed by a double that was explicitly converted via convertToAccurateDouble; false otherwise. 437 * Used for testing. 438 */ 439 bool explicitExactDouble = false; 440 441 void roundToMagnitude(int32_t magnitude, RoundingMode roundingMode, bool nickel, UErrorCode& status); 442 443 /** 444 * Returns a single digit from the BCD list. No internal state is changed by calling this method. 445 * 446 * @param position The position of the digit to pop, counted in BCD units from the least 447 * significant digit. If outside the range supported by the implementation, zero is returned. 448 * @return The digit at the specified location. 449 */ 450 int8_t getDigitPos(int32_t position) const; 451 452 /** 453 * Sets the digit in the BCD list. This method only sets the digit; it is the caller's 454 * responsibility to call {@link #compact} after setting the digit, and to ensure 455 * that the precision field is updated to reflect the correct number of digits if a 456 * nonzero digit is added to the decimal. 457 * 458 * @param position The position of the digit to pop, counted in BCD units from the least 459 * significant digit. If outside the range supported by the implementation, an AssertionError 460 * is thrown. 461 * @param value The digit to set at the specified location. 462 */ 463 void setDigitPos(int32_t position, int8_t value); 464 465 /** 466 * Adds zeros to the end of the BCD list. This will result in an invalid BCD representation; it is 467 * the caller's responsibility to do further manipulation and then call {@link #compact}. 468 * 469 * @param numDigits The number of zeros to add. 470 */ 471 void shiftLeft(int32_t numDigits); 472 473 /** 474 * Directly removes digits from the end of the BCD list. 475 * Updates the scale and precision. 476 * 477 * CAUTION: it is the caller's responsibility to call {@link #compact} after this method. 478 */ 479 void shiftRight(int32_t numDigits); 480 481 /** 482 * Directly removes digits from the front of the BCD list. 483 * Updates precision. 484 * 485 * CAUTION: it is the caller's responsibility to call {@link #compact} after this method. 486 */ 487 void popFromLeft(int32_t numDigits); 488 489 /** 490 * Sets the internal representation to zero. Clears any values stored in scale, precision, 491 * hasDouble, origDouble, origDelta, exponent, and BCD data. 492 */ 493 void setBcdToZero(); 494 495 /** 496 * Sets the internal BCD state to represent the value in the given int. The int is guaranteed to 497 * be either positive. The internal state is guaranteed to be empty when this method is called. 498 * 499 * @param n The value to consume. 500 */ 501 void readIntToBcd(int32_t n); 502 503 /** 504 * Sets the internal BCD state to represent the value in the given long. The long is guaranteed to 505 * be either positive. The internal state is guaranteed to be empty when this method is called. 506 * 507 * @param n The value to consume. 508 */ 509 void readLongToBcd(int64_t n); 510 511 void readDecNumberToBcd(const DecNum& dn); 512 513 void readDoubleConversionToBcd(const char* buffer, int32_t length, int32_t point); 514 515 void copyFieldsFrom(const DecimalQuantity& other); 516 517 void copyBcdFrom(const DecimalQuantity &other); 518 519 void moveBcdFrom(DecimalQuantity& src); 520 521 /** 522 * Removes trailing zeros from the BCD (adjusting the scale as required) and then computes the 523 * precision. The precision is the number of digits in the number up through the greatest nonzero 524 * digit. 525 * 526 * <p>This method must always be called when bcd changes in order for assumptions to be correct in 527 * methods like {@link #fractionCount()}. 528 */ 529 void compact(); 530 531 void _setToInt(int32_t n); 532 533 void _setToLong(int64_t n); 534 535 void _setToDoubleFast(double n); 536 537 void _setToDecNum(const DecNum& dn, UErrorCode& status); 538 539 static int32_t getVisibleFractionCount(UnicodeString value); 540 541 void convertToAccurateDouble(); 542 543 /** Ensure that a byte array of at least 40 digits is allocated. */ 544 void ensureCapacity(); 545 546 void ensureCapacity(int32_t capacity); 547 548 /** Switches the internal storage mechanism between the 64-bit long and the byte array. */ 549 void switchStorage(); 550 }; 551 552 } // namespace impl 553 } // namespace number 554 U_NAMESPACE_END 555 556 557 #endif //__NUMBER_DECIMALQUANTITY_H__ 558 559 #endif /* #if !UCONFIG_NO_FORMATTING */ 560