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