root/src/decNumber/decNumber.c

/* [previous][next][first][last][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. decNumberFromInt32
  2. decNumberFromUInt32
  3. decNumberToInt32
  4. decNumberToUInt32
  5. decNumberToString
  6. decNumberToEngString
  7. decNumberFromString
  8. decNumberAbs
  9. decNumberAdd
  10. decNumberAnd
  11. decNumberCompare
  12. decNumberCompareSignal
  13. decNumberCompareTotal
  14. decNumberCompareTotalMag
  15. decNumberDivide
  16. decNumberDivideInteger
  17. decNumberExp
  18. decNumberFMA
  19. decNumberInvert
  20. decNumberLn
  21. decNumberLogB
  22. decNumberLog10
  23. decNumberMax
  24. decNumberMaxMag
  25. decNumberMin
  26. decNumberMinMag
  27. decNumberMinus
  28. decNumberNextMinus
  29. decNumberNextPlus
  30. decNumberNextToward
  31. decNumberOr
  32. decNumberPlus
  33. decNumberMultiply
  34. decNumberPower
  35. decNumberQuantize
  36. decNumberNormalize
  37. decNumberReduce
  38. decNumberRescale
  39. decNumberRemainder
  40. decNumberRemainderNear
  41. decNumberRotate
  42. decNumberSameQuantum
  43. decNumberScaleB
  44. decNumberShift
  45. decNumberSquareRoot
  46. decNumberSubtract
  47. decNumberToIntegralExact
  48. decNumberToIntegralValue
  49. decNumberXor
  50. decNumberClass
  51. decNumberClassToString
  52. decNumberCopy
  53. decNumberCopyAbs
  54. decNumberCopyNegate
  55. decNumberCopySign
  56. decNumberGetBCD
  57. decNumberSetBCD
  58. decNumberIsNormal
  59. decNumberIsSubnormal
  60. decNumberTrim
  61. decNumberVersion
  62. decNumberZero
  63. decToString
  64. decAddOp
  65. decDivideOp
  66. decMultiplyOp
  67. decExpOp
  68. decLnOp
  69. decQuantizeOp
  70. decCompareOp
  71. decCompare
  72. decUnitCompare
  73. decUnitAddSub
  74. decTrim
  75. decReverse
  76. decShiftToMost
  77. decShiftToLeast
  78. decRoundOperand
  79. decCopyFit
  80. decSetCoeff
  81. decApplyRound
  82. decFinish
  83. decFinalize
  84. decSetOverflow
  85. decSetMaxValue
  86. decSetSubnormal
  87. decCheckMath
  88. decGetInt
  89. decDecap
  90. decBiStr
  91. decNaNs
  92. decStatus
  93. decGetDigits

   1 // vim: filetype=c:tabstop=4:ai:expandtab
   2 // SPDX-License-Identifier: ICU
   3 // scspell-id: c39f59d7-f62c-11ec-ba31-80ee73e9b8e7
   4 /* ------------------------------------------------------------------ */
   5 /* Decimal Number arithmetic module                                   */
   6 /* ------------------------------------------------------------------ */
   7 /* Copyright (c) IBM Corporation, 2000, 2009.  All rights reserved.   */
   8 /*                                                                    */
   9 /* This software is made available under the terms of the             */
  10 /* ICU License -- ICU 1.8.1 and later.                                */
  11 /*                                                                    */
  12 /* The description and User's Guide ("The decNumber C Library") for   */
  13 /* this software is called decNumber.pdf.  This document is           */
  14 /* available, together with arithmetic and format specifications,     */
  15 /* testcases, and Web links, on the General Decimal Arithmetic page.  */
  16 /*                                                                    */
  17 /* Please send comments, suggestions, and corrections to the author:  */
  18 /*   mfc@uk.ibm.com                                                   */
  19 /*   Mike Cowlishaw, IBM Fellow                                       */
  20 /*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */
  21 /* ------------------------------------------------------------------ */
  22 /* This module comprises the routines for arbitrary-precision General */
  23 /* Decimal Arithmetic as defined in the specification which may be    */
  24 /* found on the General Decimal Arithmetic pages.  It implements both */
  25 /* the full ('extended') arithmetic and the simpler ('subset')        */
  26 /* arithmetic.                                                        */
  27 /*                                                                    */
  28 /* Usage notes:                                                       */
  29 /*                                                                    */
  30 /* 1. This code is ANSI C89 except:                                   */
  31 /*                                                                    */
  32 /*    a) C99 line comments (double forward slash) are used.  (Most C  */
  33 /*       compilers accept these.  If yours does not, the "uncrustify" */
  34 /*       program can be used to convert them to ANSI C comments.)     */
  35 /*                                                                    */
  36 /*    b) Types from C99 stdint.h are used.  If you do not have this   */
  37 /*       header file, see the User's Guide section of the decNumber   */
  38 /*       documentation; this lists the necessary definitions.         */
  39 /*                                                                    */
  40 /*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
  41 /*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
  42 /*       and DECDPUN<=4 (see documentation).                          */
  43 /*                                                                    */
  44 /*    The code also conforms to C99 restrictions; in particular,      */
  45 /*    strict aliasing rules are observed.                             */
  46 /*                                                                    */
  47 /* 2. The decNumber format which this library uses is optimized for   */
  48 /*    efficient processing of relatively short numbers; in particular */
  49 /*    it allows the use of fixed sized structures and minimizes copy  */
  50 /*    and move operations.  It does, however, support arbitrary       */
  51 /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
  52 /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
  53 /*    range -999,999,999 through 0).  Mathematical functions (for     */
  54 /*    example decNumberExp) as identified below are restricted more   */
  55 /*    tightly: digits, emax, and -emin in the context must be <=      */
  56 /*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
  57 /*    these bounds.                                                   */
  58 /*                                                                    */
  59 /* 3. Logical functions are further restricted; their operands must   */
  60 /*    be finite, positive, have an exponent of zero, and all digits   */
  61 /*    must be either 0 or 1.  The result will only contain digits     */
  62 /*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
  63 /*                                                                    */
  64 /* 4. Operands to operator functions are never modified unless they   */
  65 /*    are also specified to be the result number (which is always     */
  66 /*    permitted).  Other than that case, operands must not overlap.   */
  67 /*                                                                    */
  68 /* 5. Error handling: the type of the error is ORed into the status   */
  69 /*    flags in the current context (decContext structure).  The       */
  70 /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
  71 /*    flag in the decContext is set (is 1).                           */
  72 /*                                                                    */
  73 /*    It is the responsibility of the caller to clear the status      */
  74 /*    flags as required.                                              */
  75 /*                                                                    */
  76 /*    The result of any routine which returns a number will always    */
  77 /*    be a valid number (which may be a special value, such as an     */
  78 /*    Infinity or NaN).                                               */
  79 /*                                                                    */
  80 /* 6. The decNumber format is not an exchangeable concrete            */
  81 /*    representation as it comprises fields which may be machine-     */
  82 /*    dependent (packed or unpacked, or special length, for example). */
  83 /*    Canonical conversions to and from strings are provided; other   */
  84 /*    conversions are available in separate modules.                  */
  85 /*                                                                    */
  86 /* 7. Subset arithmetic is available only if DECSUBSET is set to 1.   */
  87 /* ------------------------------------------------------------------ */
  88 /* Implementation notes for maintenance of this module:               */
  89 /*                                                                    */
  90 /* 1. Storage leak protection:  Routines which use malloc are not     */
  91 /*    permitted to use return for fastpath or error exits (i.e.,      */
  92 /*    they follow strict structured programming conventions).         */
  93 /*    Instead they have a do{}while(0); construct surrounding the     */
  94 /*    code which is protected -- break may be used to exit this.      */
  95 /*    Other routines can safely use the return statement inline.      */
  96 /*                                                                    */
  97 /* 2. All loops use the for(;;) construct.  Any do construct does     */
  98 /*    not loop; it is for allocation protection as just described.    */
  99 /*                                                                    */
 100 /* 3. Setting status in the context must always be the very last      */
 101 /*    action in a routine, as non-0 status may raise a trap and hence */
 102 /*    the call to set status may not return (if the handler uses long */
 103 /*    jump).  Therefore all cleanup must be done first.  In general,  */
 104 /*    to achieve this status is accumulated and is only applied just  */
 105 /*    before return by calling decContextSetStatus (via decStatus).   */
 106 /*                                                                    */
 107 /*    Routines which allocate storage cannot, in general, use the     */
 108 /*    'top level' routines which could cause a non-returning          */
 109 /*    transfer of control.  The decXxxxOp routines are safe (do not   */
 110 /*    call decStatus even if traps are set in the context) and should */
 111 /*    be used instead (they are also a little faster).                */
 112 /*                                                                    */
 113 /* 4. Exponent checking is minimized by allowing the exponent to      */
 114 /*    grow outside its limits during calculations, provided that      */
 115 /*    the decFinalize function is called later.  Multiplication and   */
 116 /*    division, and intermediate calculations in exponentiation,      */
 117 /*    require more careful checks because of the risk of 31-bit       */
 118 /*    overflow (the most negative valid exponent is -1999999997, for  */
 119 /*    a 999999999-digit number with adjusted exponent of -999999999). */
 120 /*                                                                    */
 121 /* 5. Rounding is deferred until finalization of results, with any    */
 122 /*    'off to the right' data being represented as a single digit     */
 123 /*    residue (in the range -1 through 9).  This avoids any double-   */
 124 /*    rounding when more than one shortening takes place (for         */
 125 /*    example, when a result is subnormal).                           */
 126 /*                                                                    */
 127 /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
 128 /*    during many operations, so whole Units are handled and exact    */
 129 /*    accounting of digits is not needed.  The correct digits value   */
 130 /*    is found by decGetDigits, which accounts for leading zeros.     */
 131 /*    This must be called before any rounding if the number of digits */
 132 /*    is not known exactly.                                           */
 133 /*                                                                    */
 134 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
 135 /*    numbers up to four digits, using appropriate constants.  This   */
 136 /*    is not useful for longer numbers because overflow of 32 bits    */
 137 /*    would lead to 4 multiplies, which is almost as expensive as     */
 138 /*    a divide (unless a floating-point or 64-bit multiply is         */
 139 /*    assumed to be available).                                       */
 140 /*                                                                    */
 141 /* 8. Unusual abbreviations that may be used in the commentary:       */
 142 /*      lhs -- left hand side (operand, of an operation)              */
 143 /*      lsd -- least significant digit (of coefficient)               */
 144 /*      lsu -- least significant Unit (of coefficient)                */
 145 /*      msd -- most significant digit (of coefficient)                */
 146 /*      msi -- most significant item (in an array)                    */
 147 /*      msu -- most significant Unit (of coefficient)                 */
 148 /*      rhs -- right hand side (operand, of an operation)             */
 149 /*      +ve -- positive                                               */
 150 /*      -ve -- negative                                               */
 151 /*      **  -- raise to the power                                     */
 152 /* ------------------------------------------------------------------ */
 153 
 154 #include <string.h>                // for strcpy
 155 #include <stdlib.h>                // for malloc, free, etc.
 156 #include <stdio.h>                 // for printf [if needed]
 157 #include <ctype.h>                 // for lower
 158 #include "decNumber.h"             // base number library
 159 #include "decNumberLocal.h"        // decNumber local types, etc.
 160 
 161 #undef FREE
 162 #ifdef TESTING
 163 # define FREE(p) free(p)
 164 #else
 165 # define FREE(p) do  \
 166   {                  \
 167     free((p));       \
 168     (p) = NULL;      \
 169   } while(0)
 170 #endif
 171 
 172 /* Constants */
 173 // Public lookup table used by the D2U macro
 174 const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
 175 
 176 #define powers      DECPOWERS      // old internal name
 177 
 178 // Local constants
 179 #define DIVIDE      0x80           // Divide operators
 180 #define REMAINDER   0x40           // ..
 181 #define DIVIDEINT   0x20           // ..
 182 #define REMNEAR     0x10           // ..
 183 #define COMPARE     0x01           // Compare operators
 184 #define COMPMAX     0x02           // ..
 185 #define COMPMIN     0x03           // ..
 186 #define COMPTOTAL   0x04           // ..
 187 #define COMPNAN     0x05           // .. [NaN processing]
 188 #define COMPSIG     0x06           // .. [signaling COMPARE]
 189 #define COMPMAXMAG  0x07           // ..
 190 #define COMPMINMAG  0x08           // ..
 191 
 192 #define DEC_sNaN     0x40000000    // local status: sNaN signal
 193 #define BADINT  (Int)0x80000000    // most-negative Int; error indicator
 194 // Next two indicate an integer >= 10**6, and its parity (bottom bit)
 195 #define BIGEVEN (Int)0x80000002
 196 #define BIGODD  (Int)0x80000003
 197 
 198 static Unit uarrone[1]={1};   // Unit array of 1, used for incrementing
 199 
 200 /* Granularity-dependent code */
 201 #if DECDPUN<=4
 202 # define eInt  Int           // extended integer
 203 # define ueInt uInt          // unsigned extended integer
 204   // Constant multipliers for divide-by-power-of five using reciprocal
 205   // multiply, after removing powers of 2 by shifting, and final shift
 206   // of 17 [we only need up to **4]
 207   static const uInt multies[]={131073, 26215, 5243, 1049, 210};
 208   // QUOT10 -- macro to return the quotient of unit u divided by 10**n
 209 # define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
 210 #else
 211   // For DECDPUN>4 non-ANSI-89 64-bit types are needed.
 212 # if !DECUSE64
 213 #  error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
 214 # endif
 215 # define eInt  Long          // extended integer
 216 # define ueInt uLong         // unsigned extended integer
 217 #endif
 218 
 219 /* Local routines */
 220 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
 221                               decContext *, uByte, uInt *);
 222 static Flag        decBiStr(const char *, const char *, const char *);
 223 static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
 224 static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
 225 static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
 226 static decNumber * decCompareOp(decNumber *, const decNumber *,
 227                               const decNumber *, decContext *,
 228                               Flag, uInt *);
 229 static void        decCopyFit(decNumber *, const decNumber *, decContext *,
 230                               Int *, uInt *);
 231 static decNumber * decDecap(decNumber *, Int);
 232 static decNumber * decDivideOp(decNumber *, const decNumber *,
 233                               const decNumber *, decContext *, Flag, uInt *);
 234 static decNumber * decExpOp(decNumber *, const decNumber *,
 235                               decContext *, uInt *);
 236 static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
 237 static Int         decGetDigits(Unit *, Int);
 238 static Int         decGetInt(const decNumber *);
 239 static decNumber * decLnOp(decNumber *, const decNumber *,
 240                               decContext *, uInt *);
 241 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
 242                               const decNumber *, decContext *,
 243                               uInt *);
 244 static decNumber * decNaNs(decNumber *, const decNumber *,
 245                               const decNumber *, decContext *, uInt *);
 246 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
 247                               const decNumber *, decContext *, Flag,
 248                               uInt *);
 249 static void        decReverse(Unit *, Unit *);
 250 static void        decSetCoeff(decNumber *, decContext *, const Unit *,
 251                               Int, Int *, uInt *);
 252 static void        decSetMaxValue(decNumber *, decContext *);
 253 static void        decSetOverflow(decNumber *, decContext *, uInt *);
 254 static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
 255 static Int         decShiftToLeast(Unit *, Int, Int);
 256 static Int         decShiftToMost(Unit *, Int, Int);
 257 static void        decStatus(decNumber *, uInt, decContext *);
 258 static void        decToString(const decNumber *, char[], Flag);
 259 static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
 260 static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
 261                               Unit *, Int);
 262 static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
 263 
 264 #if !DECSUBSET
 265 /* decFinish == decFinalize when no subset arithmetic needed */
 266 # define decFinish(a,b,c,d) decFinalize(a,b,c,d)
 267 #else
 268 static void        decFinish(decNumber *, decContext *, Int *, uInt *);
 269 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
 270 #endif
 271 
 272 /* Local macros */
 273 // masked special-values bits
 274 #define SPECIALARG  (rhs->bits & DECSPECIAL)
 275 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
 276 
 277 /* ================================================================== */
 278 /* Conversions                                                        */
 279 /* ================================================================== */
 280 
 281 /* ------------------------------------------------------------------ */
 282 /* from-int32 -- conversion from Int or uInt                          */
 283 /*                                                                    */
 284 /*  dn is the decNumber to receive the integer                        */
 285 /*  in or uin is the integer to be converted                          */
 286 /*  returns dn                                                        */
 287 /*                                                                    */
 288 /* No error is possible.                                              */
 289 /* ------------------------------------------------------------------ */
 290 decNumber * decNumberFromInt32(decNumber *dn, Int in) {
     /* [previous][next][first][last][top][bottom][index][help] */
 291   uInt unsig;
 292   if (in>=0) unsig=in;
 293    else {                               // negative (possibly BADINT)
 294     if (in==BADINT) unsig=(uInt)1073741824*2; // special case
 295      else unsig=-in;                    // invert
 296     }
 297   // in is now positive
 298   decNumberFromUInt32(dn, unsig);
 299   if (in<0) dn->bits=DECNEG;            // sign needed
 300   return dn;
 301   } // decNumberFromInt32
 302 
 303 decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
     /* [previous][next][first][last][top][bottom][index][help] */
 304   Unit *up;                             // work pointer
 305   decNumberZero(dn);                    // clean
 306   if (uin==0) return dn;                // [or decGetDigits bad call]
 307   for (up=dn->lsu; uin>0; up++) {
 308     *up=(Unit)(uin%(DECDPUNMAX+1));
 309     uin=uin/(DECDPUNMAX+1);
 310     }
 311   dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
 312   return dn;
 313   } // decNumberFromUInt32
 314 
 315 /* ------------------------------------------------------------------ */
 316 /* to-int32 -- conversion to Int or uInt                              */
 317 /*                                                                    */
 318 /*  dn is the decNumber to convert                                    */
 319 /*  set is the context for reporting errors                           */
 320 /*  returns the converted decNumber, or 0 if Invalid is set           */
 321 /*                                                                    */
 322 /* Invalid is set if the decNumber does not have exponent==0 or if    */
 323 /* it is a NaN, Infinite, or out-of-range.                            */
 324 /* ------------------------------------------------------------------ */
 325 Int decNumberToInt32(const decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
 326   // special or too many digits, or bad exponent
 327   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad
 328    else { // is a finite integer with 10 or fewer digits
 329     Int d;                         // work
 330     const Unit *up;                // ..
 331     uInt hi=0, lo;                 // ..
 332     up=dn->lsu;                    // -> lsu
 333     lo=*up;                        // get 1 to 9 digits
 334 #if DECDPUN>1                  // split to higher
 335       hi=lo/10;
 336       lo=lo%10;
 337 #endif
 338     up++;
 339     // collect remaining Units, if any, into hi
 340     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
 341     // now low has the lsd, hi the remainder
 342     if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
 343       // most-negative is a reprieve
 344       if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
 345       // bad -- drop through
 346       }
 347      else { // in-range always
 348       Int i=X10(hi)+lo;
 349       if (dn->bits&DECNEG) return -i;
 350       return i;
 351       }
 352     } // integer
 353   (void)decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
 354   return 0;
 355   } // decNumberToInt32
 356 
 357 uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
 358   // special or too many digits, or bad exponent, or negative (<0)
 359   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
 360     || (dn->bits&DECNEG && !ISZERO(dn)));                   // bad
 361    else { // is a finite integer with 10 or fewer digits
 362     Int d;                         // work
 363     const Unit *up;                // ..
 364     uInt hi=0, lo;                 // ..
 365     up=dn->lsu;                    // -> lsu
 366     lo=*up;                        // get 1 to 9 digits
 367 #if DECDPUN>1                  // split to higher
 368       hi=lo/10;
 369       lo=lo%10;
 370 #endif
 371     up++;
 372     // collect remaining Units, if any, into hi
 373     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
 374 
 375     // now low has the lsd, hi the remainder
 376     if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve
 377      else return X10(hi)+lo;
 378     } // integer
 379   (void)decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
 380   return 0;
 381   } // decNumberToUInt32
 382 
 383 /* ------------------------------------------------------------------ */
 384 /* to-scientific-string -- conversion to numeric string               */
 385 /* to-engineering-string -- conversion to numeric string              */
 386 /*                                                                    */
 387 /*   decNumberToString(dn, string);                                   */
 388 /*   decNumberToEngString(dn, string);                                */
 389 /*                                                                    */
 390 /*  dn is the decNumber to convert                                    */
 391 /*  string is the string where the result will be laid out            */
 392 /*                                                                    */
 393 /*  string must be at least dn->digits+14 characters long             */
 394 /*                                                                    */
 395 /*  No error is possible, and no status can be set.                   */
 396 /* ------------------------------------------------------------------ */
 397 char * decNumberToString(const decNumber *dn, char *string){
     /* [previous][next][first][last][top][bottom][index][help] */
 398   decToString(dn, string, 0);
 399   return string;
 400   } // DecNumberToString
 401 
 402 char * decNumberToEngString(const decNumber *dn, char *string){
     /* [previous][next][first][last][top][bottom][index][help] */
 403   decToString(dn, string, 1);
 404   return string;
 405   } // DecNumberToEngString
 406 
 407 /* ------------------------------------------------------------------ */
 408 /* to-number -- conversion from numeric string                        */
 409 /*                                                                    */
 410 /* decNumberFromString -- convert string to decNumber                 */
 411 /*   dn        -- the number structure to fill                        */
 412 /*   chars[]   -- the string to convert ('\0' terminated)             */
 413 /*   set       -- the context used for processing any error,          */
 414 /*                determining the maximum precision available         */
 415 /*                (set.digits), determining the maximum and minimum   */
 416 /*                exponent (set.emax and set.emin), determining if    */
 417 /*                extended values are allowed, and checking the       */
 418 /*                rounding mode if overflow occurs or rounding is     */
 419 /*                needed.                                             */
 420 /*                                                                    */
 421 /* The length of the coefficient and the size of the exponent are     */
 422 /* checked by this routine, so the correct error (Underflow or        */
 423 /* Overflow) can be reported or rounding applied, as necessary.       */
 424 /*                                                                    */
 425 /* If bad syntax is detected, the result will be a quiet NaN.         */
 426 /* ------------------------------------------------------------------ */
 427 decNumber * decNumberFromString(decNumber *dn, const char chars[],
     /* [previous][next][first][last][top][bottom][index][help] */
 428                                 decContext *set) {
 429   Int   exponent=0;                // working exponent [assume 0]
 430   uByte bits=0;                    // working flags [assume +ve]
 431   Unit  *res;                      // where result will be built
 432   Unit  resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
 433                                    // [+9 allows for ln() constants]
 434   Unit  *allocres=NULL;            // -> allocated result, iff allocated
 435   Int   d=0;                       // count of digits found in decimal part
 436   const char *dotchar=NULL;        // where dot was found
 437   const char *cfirst=chars;        // -> first character of decimal part
 438   const char *last=NULL;           // -> last digit of decimal part
 439   const char *c;                   // work
 440   Unit  *up;                       // ..
 441 #if DECDPUN>1
 442   Int   cut, out;                  // ..
 443 #endif
 444   Int   residue;                   // rounding residue
 445   uInt  status=0;                  // error code
 446 
 447   do {                             // status & malloc protection
 448     for (c=chars;; c++) {          // -> input character
 449       if (*c>='0' && *c<='9') {    // test for Arabic digit
 450         last=c;
 451         d++;                       // count of real digits
 452         continue;                  // still in decimal part
 453         }
 454       if (*c=='.' && dotchar==NULL) { // first '.'
 455         dotchar=c;                 // record offset into decimal part
 456         if (c==cfirst) cfirst++;   // first digit must follow
 457         continue;}
 458       if (c==chars) {              // first in string...
 459         if (*c=='-') {             // valid - sign
 460           cfirst++;
 461           bits=DECNEG;
 462           continue;}
 463         if (*c=='+') {             // valid + sign
 464           cfirst++;
 465           continue;}
 466         }
 467       // *c is not a digit, or a valid +, -, or '.'
 468       break;
 469       } // c
 470 
 471     if (last==NULL) {              // no digits yet
 472       status=DEC_Conversion_syntax;// assume the worst
 473       if (*c=='\0') break;         // and no more to come...
 474 #if DECSUBSET
 475       // if subset then infinities and NaNs are not allowed
 476       if (!set->extended) break;   // hopeless
 477 #endif
 478       // Infinities and NaNs are possible, here
 479       if (dotchar!=NULL) break;    // .. unless had a dot
 480       decNumberZero(dn);           // be optimistic
 481       if (decBiStr(c, "infinity", "INFINITY")
 482        || decBiStr(c, "inf", "INF")) {
 483         dn->bits=bits | DECINF;
 484         status=0;                  // is OK
 485         break; // all done
 486         }
 487       // a NaN expected
 488       // 2003.09.10 NaNs are now permitted to have a sign
 489       dn->bits=bits | DECNAN;      // assume simple NaN
 490       if (*c=='s' || *c=='S') {    // looks like an sNaN
 491         c++;
 492         dn->bits=bits | DECSNAN;
 493         }
 494       if (*c!='n' && *c!='N') break;    // check caseless "NaN"
 495       c++;
 496       if (*c!='a' && *c!='A') break;    // ..
 497       c++;
 498       if (*c!='n' && *c!='N') break;    // ..
 499       c++;
 500       // now either nothing, or nnnn payload, expected
 501       // -> start of integer and skip leading 0s [including plain 0]
 502       for (cfirst=c; *cfirst=='0';) cfirst++;
 503       if (*cfirst=='\0') {         // "NaN" or "sNaN", maybe with all 0s
 504         status=0;                  // it's good
 505         break;                     // ..
 506         }
 507       // something other than 0s; setup last and d as usual [no dots]
 508       for (c=cfirst;; c++, d++) {
 509         if (*c<'0' || *c>'9') break; // test for Arabic digit
 510         last=c;
 511         }
 512       if (*c!='\0') break;         // not all digits
 513       if (d>set->digits-1) {
 514         // [NB: payload in a decNumber can be full length unless
 515         // clamped, in which case can only be digits-1]
 516         if (set->clamp) break;
 517         if (d>set->digits) break;
 518         } // too many digits?
 519       // good; drop through to convert the integer to coefficient
 520       status=0;                    // syntax is OK
 521       bits=dn->bits;               // for copy-back
 522       } // last==NULL
 523 
 524      else if (*c!='\0') {          // more to process...
 525       // had some digits; exponent is only valid sequence now
 526       Flag nege;                   // 1=negative exponent
 527       const char *firstexp;        // -> first significant exponent digit
 528       status=DEC_Conversion_syntax;// assume the worst
 529       if (*c!='e' && *c!='E') break;
 530       /* Found 'e' or 'E' -- now process explicit exponent */
 531       // 1998.07.11: sign no longer required
 532       nege=0;
 533       c++;                         // to (possible) sign
 534       if (*c=='-') {nege=1; c++;}
 535        else if (*c=='+') c++;
 536       if (*c=='\0') break;
 537 
 538       for (; *c=='0' && *(c+1)!='\0';) c++;  // strip insignificant zeros
 539       firstexp=c;                            // save exponent digit place
 540       for (; ;c++) {
 541         if (*c<'0' || *c>'9') break;         // not a digit
 542         exponent=X10(exponent)+(Int)*c-(Int)'0';
 543         } // c
 544       // if not now on a '\0', *c must not be a digit
 545       if (*c!='\0') break;
 546 
 547       // (this next test must be after the syntax checks)
 548       // if it was too long the exponent may have wrapped, so check
 549       // carefully and set it to a certain overflow if wrap possible
 550       if (c>=firstexp+9+1) {
 551         if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
 552         // [up to 1999999999 is OK, for example 1E-1000000998]
 553         }
 554       if (nege) exponent=-exponent;     // was negative
 555       status=0;                         // is OK
 556       } // stuff after digits
 557 
 558     // Here when whole string has been inspected; syntax is good
 559     // cfirst->first digit (never dot), last->last digit (ditto)
 560 
 561     // strip leading zeros/dot [leave final 0 if all 0's]
 562     if (*cfirst=='0') {                 // [cfirst has stepped over .]
 563       for (c=cfirst; c<last; c++, cfirst++) {
 564         if (*c=='.') continue;          // ignore dots
 565         if (*c!='0') break;             // non-zero found
 566         d--;                            // 0 stripped
 567         } // c
 568 #if DECSUBSET
 569       // make a rapid exit for easy zeros if !extended
 570       if (*cfirst=='0' && !set->extended) {
 571         decNumberZero(dn);              // clean result
 572         break;                          // [could be return]
 573         }
 574 #endif
 575       } // at least one leading 0
 576 
 577     // Handle decimal point...
 578     if (dotchar!=NULL && dotchar<last)  // non-trailing '.' found?
 579       exponent-=(last-dotchar);         // adjust exponent
 580     // [we can now ignore the .]
 581 
 582     // OK, the digits string is good.  Assemble in the decNumber, or in
 583     // a temporary units array if rounding is needed
 584     if (d<=set->digits) res=dn->lsu;    // fits into supplied decNumber
 585      else {                             // rounding needed
 586       Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
 587       res=resbuff;                      // assume use local buffer
 588       if (needbytes>(Int)sizeof(resbuff)) { // too big for local
 589         allocres=(Unit *)malloc(needbytes);
 590         if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
 591         res=allocres;
 592         }
 593       }
 594     // res now -> number lsu, buffer, or allocated storage for Unit array
 595 
 596     // Place the coefficient into the selected Unit array
 597     // [this is often 70% of the cost of this function when DECDPUN>1]
 598 #if DECDPUN>1
 599     out=0;                         // accumulator
 600     up=res+D2U(d)-1;               // -> msu
 601     cut=d-(up-res)*DECDPUN;        // digits in top unit
 602     for (c=cfirst;; c++) {         // along the digits
 603       if (*c=='.') continue;       // ignore '.' [don't decrement cut]
 604       out=X10(out)+(Int)*c-(Int)'0';
 605       if (c==last) break;          // done [never get to trailing '.']
 606       cut--;
 607       if (cut>0) continue;         // more for this unit
 608       *up=(Unit)out;               // write unit
 609       up--;                        // prepare for unit below..
 610       cut=DECDPUN;                 // ..
 611       out=0;                       // ..
 612       } // c
 613     *up=(Unit)out;                 // write lsu
 614 
 615 #else
 616     // DECDPUN==1
 617     up=res;                        // -> lsu
 618     for (c=last; c>=cfirst; c--) { // over each character, from least
 619       if (*c=='.') continue;       // ignore . [don't step up]
 620       *up=(Unit)((Int)*c-(Int)'0');
 621       up++;
 622       } // c
 623 #endif
 624 
 625     dn->bits=bits;
 626     dn->exponent=exponent;
 627     dn->digits=d;
 628 
 629     // if not in number (too long) shorten into the number
 630     if (d>set->digits) {
 631       residue=0;
 632       decSetCoeff(dn, set, res, d, &residue, &status);
 633       // always check for overflow or subnormal and round as needed
 634       decFinalize(dn, set, &residue, &status);
 635       }
 636      else { // no rounding, but may still have overflow or subnormal
 637       // [these tests are just for performance; finalize repeats them]
 638       if ((dn->exponent-1<set->emin-dn->digits)
 639        || (dn->exponent-1>set->emax-set->digits)) {
 640         residue=0;
 641         decFinalize(dn, set, &residue, &status);
 642         }
 643       }
 644     // decNumberShow(dn);
 645     } while(0);                         // [for break]
 646 
 647   if (allocres!=NULL) FREE(allocres);   // drop any storage used
 648   if (status!=0) decStatus(dn, status, set);
 649   return dn;
 650   } /* decNumberFromString */
 651 
 652 /* ================================================================== */
 653 /* Operators                                                          */
 654 /* ================================================================== */
 655 
 656 /* ------------------------------------------------------------------ */
 657 /* decNumberAbs -- absolute value operator                            */
 658 /*                                                                    */
 659 /*   This computes C = abs(A)                                         */
 660 /*                                                                    */
 661 /*   res is C, the result.  C may be A                                */
 662 /*   rhs is A                                                         */
 663 /*   set is the context                                               */
 664 /*                                                                    */
 665 /* See also decNumberCopyAbs for a quiet bitwise version of this.     */
 666 /* C must have space for set->digits digits.                          */
 667 /* ------------------------------------------------------------------ */
 668 /* This has the same effect as decNumberPlus unless A is negative,    */
 669 /* in which case it has the same effect as decNumberMinus.            */
 670 /* ------------------------------------------------------------------ */
 671 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 672                          decContext *set) {
 673   decNumber dzero;                      // for 0
 674   uInt status=0;                        // accumulator
 675 
 676   decNumberZero(&dzero);                // set 0
 677   dzero.exponent=rhs->exponent;         // [no coefficient expansion]
 678   decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
 679   if (status!=0) decStatus(res, status, set);
 680   return res;
 681   } // decNumberAbs
 682 
 683 /* ------------------------------------------------------------------ */
 684 /* decNumberAdd -- add two Numbers                                    */
 685 /*                                                                    */
 686 /*   This computes C = A + B                                          */
 687 /*                                                                    */
 688 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
 689 /*   lhs is A                                                         */
 690 /*   rhs is B                                                         */
 691 /*   set is the context                                               */
 692 /*                                                                    */
 693 /* C must have space for set->digits digits.                          */
 694 /* ------------------------------------------------------------------ */
 695 /* This just calls the routine shared with Subtract                   */
 696 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 697                          const decNumber *rhs, decContext *set) {
 698   uInt status=0;                        // accumulator
 699   decAddOp(res, lhs, rhs, set, 0, &status);
 700   if (status!=0) decStatus(res, status, set);
 701   return res;
 702   } // decNumberAdd
 703 
 704 /* ------------------------------------------------------------------ */
 705 /* decNumberAnd -- AND two Numbers, digitwise                         */
 706 /*                                                                    */
 707 /*   This computes C = A & B                                          */
 708 /*                                                                    */
 709 /*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
 710 /*   lhs is A                                                         */
 711 /*   rhs is B                                                         */
 712 /*   set is the context (used for result length and error report)     */
 713 /*                                                                    */
 714 /* C must have space for set->digits digits.                          */
 715 /*                                                                    */
 716 /* Logical function restrictions apply (see above); a NaN is          */
 717 /* returned with Invalid_operation if a restriction is violated.      */
 718 /* ------------------------------------------------------------------ */
 719 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 720                          const decNumber *rhs, decContext *set) {
 721   const Unit *ua, *ub;                  // -> operands
 722   const Unit *msua, *msub;              // -> operand msus
 723   Unit *uc,  *msuc;                     // -> result and its msu
 724   Int   msudigs;                        // digits in res msu
 725 
 726   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
 727    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
 728     decStatus(res, DEC_Invalid_operation, set);
 729     return res;
 730     }
 731 
 732   // operands are valid
 733   ua=lhs->lsu;                          // bottom-up
 734   ub=rhs->lsu;                          // ..
 735   uc=res->lsu;                          // ..
 736   msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
 737   msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
 738   msuc=uc+D2U(set->digits)-1;           // -> msu of result
 739   msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
 740   for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
 741     Unit a, b;                          // extract units
 742     if (ua>msua) a=0;
 743      else a=*ua;
 744     if (ub>msub) b=0;
 745      else b=*ub;
 746     *uc=0;                              // can now write back
 747     if (a|b) {                          // maybe 1 bits to examine
 748       Int i, j;
 749       *uc=0;  //-V1048                  // can now write back
 750       // This loop could be unrolled and/or use BIN2BCD tables
 751       for (i=0; i<DECDPUN; i++) {
 752         if (a&b&1) *uc=*uc+(Unit)powers[i];  // effect AND
 753         j=a%10;
 754         a=a/10;
 755         j|=b%10;
 756         b=b/10;
 757         if (j>1) {
 758           decStatus(res, DEC_Invalid_operation, set);
 759           return res;
 760           }
 761         if (uc==msuc && i==msudigs-1) break; // just did final digit
 762         } // each digit
 763       } // both OK
 764     } // each unit
 765   // [here uc-1 is the msu of the result]
 766   res->digits=decGetDigits(res->lsu, uc-res->lsu);
 767   res->exponent=0;                      // integer
 768   res->bits=0;                          // sign=0
 769   return res;  // [no status to set]
 770   } // decNumberAnd
 771 
 772 /* ------------------------------------------------------------------ */
 773 /* decNumberCompare -- compare two Numbers                            */
 774 /*                                                                    */
 775 /*   This computes C = A ? B                                          */
 776 /*                                                                    */
 777 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
 778 /*   lhs is A                                                         */
 779 /*   rhs is B                                                         */
 780 /*   set is the context                                               */
 781 /*                                                                    */
 782 /* C must have space for one digit (or NaN).                          */
 783 /* ------------------------------------------------------------------ */
 784 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 785                              const decNumber *rhs, decContext *set) {
 786   uInt status=0;                        // accumulator
 787   decCompareOp(res, lhs, rhs, set, COMPARE, &status);
 788   if (status!=0) decStatus(res, status, set);
 789   return res;
 790   } // decNumberCompare
 791 
 792 /* ------------------------------------------------------------------ */
 793 /* decNumberCompareSignal -- compare, signalling on all NaNs          */
 794 /*                                                                    */
 795 /*   This computes C = A ? B                                          */
 796 /*                                                                    */
 797 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
 798 /*   lhs is A                                                         */
 799 /*   rhs is B                                                         */
 800 /*   set is the context                                               */
 801 /*                                                                    */
 802 /* C must have space for one digit (or NaN).                          */
 803 /* ------------------------------------------------------------------ */
 804 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 805                                    const decNumber *rhs, decContext *set) {
 806   uInt status=0;                        // accumulator
 807   decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
 808   if (status!=0) decStatus(res, status, set);
 809   return res;
 810   } // decNumberCompareSignal
 811 
 812 /* ------------------------------------------------------------------ */
 813 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
 814 /*                                                                    */
 815 /*   This computes C = A ? B, under total ordering                    */
 816 /*                                                                    */
 817 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
 818 /*   lhs is A                                                         */
 819 /*   rhs is B                                                         */
 820 /*   set is the context                                               */
 821 /*                                                                    */
 822 /* C must have space for one digit; the result will always be one of  */
 823 /* -1, 0, or 1.                                                       */
 824 /* ------------------------------------------------------------------ */
 825 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 826                                   const decNumber *rhs, decContext *set) {
 827   uInt status=0;                        // accumulator
 828   decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
 829   if (status!=0) decStatus(res, status, set);
 830   return res;
 831   } // decNumberCompareTotal
 832 
 833 /* ------------------------------------------------------------------ */
 834 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
 835 /*                                                                    */
 836 /*   This computes C = |A| ? |B|, under total ordering                */
 837 /*                                                                    */
 838 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
 839 /*   lhs is A                                                         */
 840 /*   rhs is B                                                         */
 841 /*   set is the context                                               */
 842 /*                                                                    */
 843 /* C must have space for one digit; the result will always be one of  */
 844 /* -1, 0, or 1.                                                       */
 845 /* ------------------------------------------------------------------ */
 846 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 847                                      const decNumber *rhs, decContext *set) {
 848   uInt status=0;                   // accumulator
 849   uInt needbytes;                  // for space calculations
 850   decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
 851   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
 852   decNumber bufb[D2N(DECBUFFER+1)];
 853   decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
 854   decNumber *a, *b;                // temporary pointers
 855 
 856   do {                                  // protect allocated storage
 857     // if either is negative, take a copy and absolute
 858     if (decNumberIsNegative(lhs)) {     // lhs<0
 859       a=bufa;
 860       needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
 861       if (needbytes>sizeof(bufa)) {     // need malloc space
 862         allocbufa=(decNumber *)malloc(needbytes);
 863         if (allocbufa==NULL) {          // hopeless -- abandon
 864           status|=DEC_Insufficient_storage;
 865           break;}
 866         a=allocbufa;                    // use the allocated space
 867         }
 868       decNumberCopy(a, lhs);            // copy content
 869       a->bits&=~DECNEG;                 // .. and clear the sign
 870       lhs=a;                            // use copy from here on
 871       }
 872     if (decNumberIsNegative(rhs)) {     // rhs<0
 873       b=bufb;
 874       needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
 875       if (needbytes>sizeof(bufb)) {     // need malloc space
 876         allocbufb=(decNumber *)malloc(needbytes);
 877         if (allocbufb==NULL) {          // hopeless -- abandon
 878           status|=DEC_Insufficient_storage;
 879           break;}
 880         b=allocbufb;                    // use the allocated space
 881         }
 882       decNumberCopy(b, rhs);            // copy content
 883       b->bits&=~DECNEG;                 // .. and clear the sign
 884       rhs=b;                            // use copy from here on
 885       }
 886     decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
 887     } while(0);                         // end protected
 888 
 889   if (allocbufa!=NULL) FREE(allocbufa); // drop any storage used
 890   if (allocbufb!=NULL) FREE(allocbufb); // ..
 891   if (status!=0) decStatus(res, status, set);
 892   return res;
 893   } // decNumberCompareTotalMag
 894 
 895 /* ------------------------------------------------------------------ */
 896 /* decNumberDivide -- divide one number by another                    */
 897 /*                                                                    */
 898 /*   This computes C = A / B                                          */
 899 /*                                                                    */
 900 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
 901 /*   lhs is A                                                         */
 902 /*   rhs is B                                                         */
 903 /*   set is the context                                               */
 904 /*                                                                    */
 905 /* C must have space for set->digits digits.                          */
 906 /* ------------------------------------------------------------------ */
 907 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 908                             const decNumber *rhs, decContext *set) {
 909   uInt status=0;                        // accumulator
 910   decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
 911   if (status!=0) decStatus(res, status, set);
 912   return res;
 913   } // decNumberDivide
 914 
 915 /* ------------------------------------------------------------------ */
 916 /* decNumberDivideInteger -- divide and return integer quotient       */
 917 /*                                                                    */
 918 /*   This computes C = A # B, where # is the integer divide operator  */
 919 /*                                                                    */
 920 /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
 921 /*   lhs is A                                                         */
 922 /*   rhs is B                                                         */
 923 /*   set is the context                                               */
 924 /*                                                                    */
 925 /* C must have space for set->digits digits.                          */
 926 /* ------------------------------------------------------------------ */
 927 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 928                                    const decNumber *rhs, decContext *set) {
 929   uInt status=0;                        // accumulator
 930   decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
 931   if (status!=0) decStatus(res, status, set);
 932   return res;
 933   } // decNumberDivideInteger
 934 
 935 /* ------------------------------------------------------------------ */
 936 /* decNumberExp -- exponentiation                                     */
 937 /*                                                                    */
 938 /*   This computes C = exp(A)                                         */
 939 /*                                                                    */
 940 /*   res is C, the result.  C may be A                                */
 941 /*   rhs is A                                                         */
 942 /*   set is the context; note that rounding mode has no effect        */
 943 /*                                                                    */
 944 /* C must have space for set->digits digits.                          */
 945 /*                                                                    */
 946 /* Mathematical function restrictions apply (see above); a NaN is     */
 947 /* returned with Invalid_operation if a restriction is violated.      */
 948 /*                                                                    */
 949 /* Finite results will always be full precision and Inexact, except   */
 950 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
 951 /*                                                                    */
 952 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
 953 /* almost always be correctly rounded, but may be up to 1 ulp in      */
 954 /* error in rare cases.                                               */
 955 /* ------------------------------------------------------------------ */
 956 /* This is a wrapper for decExpOp which can handle the slightly wider */
 957 /* (double) range needed by Ln (which has to be able to calculate     */
 958 /* exp(-a) where a can be the tiniest number (Ntiny).                 */
 959 /* ------------------------------------------------------------------ */
 960 decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
 961                          decContext *set) {
 962   uInt status=0;                        // accumulator
 963 #if DECSUBSET
 964   decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
 965 #endif
 966 
 967   // Check restrictions; these restrictions ensure that if h=8 (see
 968   // decExpOp) then the result will either overflow or underflow to 0.
 969   // Other math functions restrict the input range, too, for inverses.
 970   // If not violated then carry out the operation.
 971   if (!decCheckMath(rhs, set, &status)) do { // protect allocation
 972 #if DECSUBSET
 973     if (!set->extended) {
 974       // reduce operand and set lostDigits status, as needed
 975       if (rhs->digits>set->digits) {
 976         allocrhs=decRoundOperand(rhs, set, &status);
 977         if (allocrhs==NULL) break;
 978         rhs=allocrhs;
 979         }
 980       }
 981 #endif
 982     decExpOp(res, rhs, set, &status);
 983     } while(0);                         // end protected
 984 
 985 #if DECSUBSET
 986   if (allocrhs !=NULL) FREE(allocrhs);  // drop any storage used
 987 #endif
 988   // apply significant status
 989   if (status!=0) decStatus(res, status, set);
 990   return res;
 991   } // decNumberExp
 992 
 993 /* ------------------------------------------------------------------ */
 994 /* decNumberFMA -- fused multiply add                                 */
 995 /*                                                                    */
 996 /*   This computes D = (A * B) + C with only one rounding             */
 997 /*                                                                    */
 998 /*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
 999 /*   lhs is A                                                         */
1000 /*   rhs is B                                                         */
1001 /*   fhs is C [far hand side]                                         */
1002 /*   set is the context                                               */
1003 /*                                                                    */
1004 /* Mathematical function restrictions apply (see above); a NaN is     */
1005 /* returned with Invalid_operation if a restriction is violated.      */
1006 /*                                                                    */
1007 /* C must have space for set->digits digits.                          */
1008 /* ------------------------------------------------------------------ */
1009 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1010                          const decNumber *rhs, const decNumber *fhs,
1011                          decContext *set) {
1012   uInt status=0;                   // accumulator
1013   decContext dcmul;                // context for the multiplication
1014   uInt needbytes;                  // for space calculations
1015   decNumber bufa[D2N(DECBUFFER*2+1)];
1016   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1017   decNumber *acc;                  // accumulator pointer
1018   decNumber dzero;                 // work
1019 
1020   do {                                  // protect allocated storage
1021 #if DECSUBSET
1022     if (!set->extended) {               // [undefined if subset]
1023       status|=DEC_Invalid_operation;
1024       break;}
1025 #endif
1026     // Check math restrictions [these ensure no overflow or underflow]
1027     if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1028      || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1029      || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1030     // set up context for multiply
1031     dcmul=*set;
1032     dcmul.digits=lhs->digits+rhs->digits; // just enough
1033     // [The above may be an over-estimate for subset arithmetic, but that's OK]
1034     dcmul.emax=DEC_MAX_EMAX;            // effectively unbounded ..
1035     dcmul.emin=DEC_MIN_EMIN;            // [thanks to Math restrictions]
1036     // set up decNumber space to receive the result of the multiply
1037     acc=bufa;                           // may fit
1038     needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1039     if (needbytes>sizeof(bufa)) {       // need malloc space
1040       allocbufa=(decNumber *)malloc(needbytes);
1041       if (allocbufa==NULL) {            // hopeless -- abandon
1042         status|=DEC_Insufficient_storage;
1043         break;}
1044       acc=allocbufa;                    // use the allocated space
1045       }
1046     // multiply with extended range and necessary precision
1047     //printf("emin=%ld\n", dcmul.emin);
1048     decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1049     // Only Invalid operation (from sNaN or Inf * 0) is possible in
1050     // status; if either is seen than ignore fhs (in case it is
1051     // another sNaN) and set acc to NaN unless we had an sNaN
1052     // [decMultiplyOp leaves that to caller]
1053     // Note sNaN has to go through addOp to shorten payload if
1054     // necessary
1055     if ((status&DEC_Invalid_operation)!=0) {
1056       if (!(status&DEC_sNaN)) {         // but be true invalid
1057         decNumberZero(res);             // acc not yet set
1058         res->bits=DECNAN;
1059         break;
1060         }
1061       decNumberZero(&dzero);            // make 0 (any non-NaN would do)
1062       fhs=&dzero;                       // use that
1063       }
1064     // add the third operand and result -> res, and all is done
1065     decAddOp(res, acc, fhs, set, 0, &status);
1066     } while(0);                         // end protected
1067 
1068   if (allocbufa!=NULL) FREE(allocbufa); // drop any storage used
1069   if (status!=0) decStatus(res, status, set);
1070   return res;
1071   } // decNumberFMA
1072 
1073 /* ------------------------------------------------------------------ */
1074 /* decNumberInvert -- invert a Number, digitwise                      */
1075 /*                                                                    */
1076 /*   This computes C = ~A                                             */
1077 /*                                                                    */
1078 /*   res is C, the result.  C may be A (e.g., X=~X)                   */
1079 /*   rhs is A                                                         */
1080 /*   set is the context (used for result length and error report)     */
1081 /*                                                                    */
1082 /* C must have space for set->digits digits.                          */
1083 /*                                                                    */
1084 /* Logical function restrictions apply (see above); a NaN is          */
1085 /* returned with Invalid_operation if a restriction is violated.      */
1086 /* ------------------------------------------------------------------ */
1087 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1088                             decContext *set) {
1089   const Unit *ua, *msua;                // -> operand and its msu
1090   Unit  *uc, *msuc;                     // -> result and its msu
1091   Int   msudigs;                        // digits in res msu
1092 
1093   if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1094     decStatus(res, DEC_Invalid_operation, set);
1095     return res;
1096     }
1097   // operand is valid
1098   ua=rhs->lsu;                          // bottom-up
1099   uc=res->lsu;                          // ..
1100   msua=ua+D2U(rhs->digits)-1;           // -> msu of rhs
1101   msuc=uc+D2U(set->digits)-1;           // -> msu of result
1102   msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1103   for (; uc<=msuc; ua++, uc++) {        // Unit loop
1104     Unit a;                             // extract unit
1105     Int  i, j;                          // work
1106     if (ua>msua) a=0;
1107      else a=*ua;
1108     *uc=0;                              // can now write back
1109     // always need to examine all bits in rhs
1110     // This loop could be unrolled and/or use BIN2BCD tables
1111     for (i=0; i<DECDPUN; i++) {
1112       if ((~a)&1) *uc=*uc+(Unit)powers[i];   // effect INVERT
1113       j=a%10;
1114       a=a/10;
1115       if (j>1) {
1116         decStatus(res, DEC_Invalid_operation, set);
1117         return res;
1118         }
1119       if (uc==msuc && i==msudigs-1) break;   // just did final digit
1120       } // each digit
1121     } // each unit
1122   // [here uc-1 is the msu of the result]
1123   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1124   res->exponent=0;                      // integer
1125   res->bits=0;                          // sign=0
1126   return res;  // [no status to set]
1127   } // decNumberInvert
1128 
1129 /* ------------------------------------------------------------------ */
1130 /* decNumberLn -- natural logarithm                                   */
1131 /*                                                                    */
1132 /*   This computes C = ln(A)                                          */
1133 /*                                                                    */
1134 /*   res is C, the result.  C may be A                                */
1135 /*   rhs is A                                                         */
1136 /*   set is the context; note that rounding mode has no effect        */
1137 /*                                                                    */
1138 /* C must have space for set->digits digits.                          */
1139 /*                                                                    */
1140 /* Notable cases:                                                     */
1141 /*   A<0 -> Invalid                                                   */
1142 /*   A=0 -> -Infinity (Exact)                                         */
1143 /*   A=+Infinity -> +Infinity (Exact)                                 */
1144 /*   A=1 exactly -> 0 (Exact)                                         */
1145 /*                                                                    */
1146 /* Mathematical function restrictions apply (see above); a NaN is     */
1147 /* returned with Invalid_operation if a restriction is violated.      */
1148 /*                                                                    */
1149 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1150 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1151 /* error in rare cases.                                               */
1152 /* ------------------------------------------------------------------ */
1153 /* This is a wrapper for decLnOp which can handle the slightly wider  */
1154 /* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1155 /* to calculate at p+e+2).                                            */
1156 /* ------------------------------------------------------------------ */
1157 decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1158                         decContext *set) {
1159   uInt status=0;                   // accumulator
1160 #if DECSUBSET
1161   decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1162 #endif
1163 
1164   // Check restrictions; this is a math function; if not violated
1165   // then carry out the operation.
1166   if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1167 #if DECSUBSET
1168     if (!set->extended) {
1169       // reduce operand and set lostDigits status, as needed
1170       if (rhs->digits>set->digits) {
1171         allocrhs=decRoundOperand(rhs, set, &status);
1172         if (allocrhs==NULL) break;
1173         rhs=allocrhs;
1174         }
1175       // special check in subset for rhs=0
1176       if (ISZERO(rhs)) {                // +/- zeros -> error
1177         status|=DEC_Invalid_operation;
1178         break;}
1179       } // extended=0
1180 #endif
1181     decLnOp(res, rhs, set, &status);
1182     } while(0);                         // end protected
1183 
1184 #if DECSUBSET
1185   if (allocrhs !=NULL) FREE(allocrhs);  // drop any storage used
1186 #endif
1187   // apply significant status
1188   if (status!=0) decStatus(res, status, set);
1189   return res;
1190   } // decNumberLn
1191 
1192 /* ------------------------------------------------------------------ */
1193 /* decNumberLogB - get adjusted exponent, by 754 rules                */
1194 /*                                                                    */
1195 /*   This computes C = adjustedexponent(A)                            */
1196 /*                                                                    */
1197 /*   res is C, the result.  C may be A                                */
1198 /*   rhs is A                                                         */
1199 /*   set is the context, used only for digits and status              */
1200 /*                                                                    */
1201 /* For an unrounded result, digits may need to be 10 (A might have    */
1202 /* 10**9 digits and an exponent of +999999999, or one digit and an    */
1203 /* exponent of -1999999999).                                          */
1204 /*                                                                    */
1205 /* This returns the adjusted exponent of A after (in theory) padding  */
1206 /* with zeros on the right to set->digits digits while keeping the    */
1207 /* same value.  The exponent is not limited by emin/emax.             */
1208 /*                                                                    */
1209 /* Notable cases:                                                     */
1210 /*   A<0 -> Use |A|                                                   */
1211 /*   A=0 -> -Infinity (Division by zero)                              */
1212 /*   A=Infinite -> +Infinity (Exact)                                  */
1213 /*   A=1 exactly -> 0 (Exact)                                         */
1214 /*   NaNs are propagated as usual                                     */
1215 /* ------------------------------------------------------------------ */
1216 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1217                           decContext *set) {
1218   uInt status=0;                   // accumulator
1219 
1220   // NaNs as usual; Infinities return +Infinity; 0->oops
1221   if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1222    else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1223    else if (decNumberIsZero(rhs)) {
1224     decNumberZero(res);                 // prepare for Infinity
1225     res->bits=DECNEG|DECINF;            // -Infinity
1226     status|=DEC_Division_by_zero;       // as per 754
1227     }
1228    else { // finite non-zero
1229     Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
1230     if (set->digits>=10) decNumberFromInt32(res, ae);  // lay it out
1231      else {
1232       decNumber buft[D2N(10)];          // temporary number
1233       decNumber *t=buft;                // ..
1234       decNumberFromInt32(t, ae);        // lay it out
1235       decNumberPlus(res, t, set);       // round as necessary
1236       }
1237     }
1238 
1239   if (status!=0) decStatus(res, status, set);
1240   return res;
1241   } // decNumberLogB
1242 
1243 /* ------------------------------------------------------------------ */
1244 /* decNumberLog10 -- logarithm in base 10                             */
1245 /*                                                                    */
1246 /*   This computes C = log10(A)                                       */
1247 /*                                                                    */
1248 /*   res is C, the result.  C may be A                                */
1249 /*   rhs is A                                                         */
1250 /*   set is the context; note that rounding mode has no effect        */
1251 /*                                                                    */
1252 /* C must have space for set->digits digits.                          */
1253 /*                                                                    */
1254 /* Notable cases:                                                     */
1255 /*   A<0 -> Invalid                                                   */
1256 /*   A=0 -> -Infinity (Exact)                                         */
1257 /*   A=+Infinity -> +Infinity (Exact)                                 */
1258 /*   A=10**n (if n is an integer) -> n (Exact)                        */
1259 /*                                                                    */
1260 /* Mathematical function restrictions apply (see above); a NaN is     */
1261 /* returned with Invalid_operation if a restriction is violated.      */
1262 /*                                                                    */
1263 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1264 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1265 /* error in rare cases.                                               */
1266 /* ------------------------------------------------------------------ */
1267 /* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1268 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1269 /* requested digits and t is the number of digits in the exponent     */
1270 /* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1271 /* fastpath in decLnOp.  The final division is done to the requested  */
1272 /* precision.                                                         */
1273 /* ------------------------------------------------------------------ */
1274 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1275                           decContext *set) {
1276   uInt status=0, ignore=0;         // status accumulators
1277   uInt needbytes;                  // for space calculations
1278   Int p;                           // working precision
1279   Int t;                           // digits in exponent of A
1280 
1281   // buffers for a and b working decimals
1282   // (adjustment calculator, same size)
1283   decNumber bufa[D2N(DECBUFFER+2)];
1284   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1285   decNumber *a=bufa;               // temporary a
1286   decNumber bufb[D2N(DECBUFFER+2)];
1287   decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
1288   decNumber *b=bufb;               // temporary b
1289   decNumber bufw[D2N(10)];         // working 2-10 digit number
1290   decNumber *w=bufw;               // ..
1291 #if DECSUBSET
1292   decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1293 #endif
1294 
1295   decContext aset;                 // working context
1296 
1297   // Handle payloads that exceed the context precision.
1298   if (rhs->bits&(DECNAN|DECSNAN)) {
1299     decNumberPlus(res, rhs, set);
1300     return res;
1301     }
1302 
1303   // Check restrictions; this is a math function; if not violated
1304   // then carry out the operation.
1305   if (!decCheckMath(rhs, set, &status)) do { // protect malloc
1306 #if DECSUBSET
1307     if (!set->extended) {
1308       // reduce operand and set lostDigits status, as needed
1309       if (rhs->digits>set->digits) {
1310         allocrhs=decRoundOperand(rhs, set, &status);
1311         if (allocrhs==NULL) break;
1312         rhs=allocrhs;
1313         }
1314       // special check in subset for rhs=0
1315       if (ISZERO(rhs)) {                // +/- zeros -> error
1316         status|=DEC_Invalid_operation;
1317         break;}
1318       } // extended=0
1319 #endif
1320 
1321     decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
1322 
1323     // handle exact powers of 10; only check if +ve finite
1324     if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1325       Int residue=0;               // (no residue)
1326       uInt copystat=0;             // clean status
1327 
1328       // round to a single digit...
1329       aset.digits=1;
1330       decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten
1331       // if exact and the digit is 1, rhs is a power of 10
1332       if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1333         // the exponent, conveniently, is the power of 10; making
1334         // this the result needs a little care as it might not fit,
1335         // so first convert it into the working number, and then move
1336         // to res
1337         decNumberFromInt32(w, w->exponent);
1338         residue=0;
1339         decCopyFit(res, w, set, &residue, &status); // copy & round
1340         decFinish(res, set, &residue, &status);     // cleanup/set flags
1341         break;
1342         } // not a power of 10
1343       } // not a candidate for exact
1344 
1345     // simplify the information-content calculation to use 'total
1346     // number of digits in a, including exponent' as compared to the
1347     // requested digits, as increasing this will only rarely cost an
1348     // iteration in ln(a) anyway
1349     t=6;                                // it can never be >6
1350 
1351     // allocate space when needed...
1352     p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1353     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1354     if (needbytes>sizeof(bufa)) {       // need malloc space
1355       allocbufa=(decNumber *)malloc(needbytes);
1356       if (allocbufa==NULL) {            // hopeless -- abandon
1357         status|=DEC_Insufficient_storage;
1358         break;}
1359       a=allocbufa;                      // use the allocated space
1360       }
1361     aset.digits=p;                      // as calculated
1362     aset.emax=DEC_MAX_MATH;             // usual bounds
1363     aset.emin=-DEC_MAX_MATH;            // ..
1364     aset.clamp=0;                       // and no concrete format
1365     decLnOp(a, rhs, &aset, &status);    // a=ln(rhs)
1366 
1367     // skip the division if the result so far is infinite, NaN, or
1368     // zero, or there was an error; note NaN from sNaN needs copy
1369     if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1370     if (a->bits&DECSPECIAL || ISZERO(a)) {
1371       decNumberCopy(res, a);            // [will fit]
1372       break;}
1373 
1374     // for ln(10) an extra 3 digits of precision are needed
1375     p=set->digits+3;
1376     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1377     if (needbytes>sizeof(bufb)) {       // need malloc space
1378       allocbufb=(decNumber *)malloc(needbytes);
1379       if (allocbufb==NULL) {            // hopeless -- abandon
1380         status|=DEC_Insufficient_storage;
1381         break;}
1382       b=allocbufb;                      // use the allocated space
1383       }
1384     decNumberZero(w);                   // set up 10...
1385 #if DECDPUN==1
1386     w->lsu[1]=1; w->lsu[0]=0;           // ..
1387 #else
1388     w->lsu[0]=10;                       // ..
1389 #endif
1390     w->digits=2;                        // ..
1391 
1392     aset.digits=p;
1393     decLnOp(b, w, &aset, &ignore);      // b=ln(10)
1394 
1395     aset.digits=set->digits;            // for final divide
1396     decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
1397     } while(0);                         // [for break]
1398 
1399   if (allocbufa!=NULL) FREE(allocbufa); // drop any storage used
1400   if (allocbufb!=NULL) FREE(allocbufb); // ..
1401 #if DECSUBSET
1402   if (allocrhs !=NULL) FREE(allocrhs);  // ..
1403 #endif
1404   // apply significant status
1405   if (status!=0) decStatus(res, status, set);
1406   return res;
1407   } // decNumberLog10
1408 
1409 /* ------------------------------------------------------------------ */
1410 /* decNumberMax -- compare two Numbers and return the maximum         */
1411 /*                                                                    */
1412 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1413 /*                                                                    */
1414 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1415 /*   lhs is A                                                         */
1416 /*   rhs is B                                                         */
1417 /*   set is the context                                               */
1418 /*                                                                    */
1419 /* C must have space for set->digits digits.                          */
1420 /* ------------------------------------------------------------------ */
1421 decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1422                          const decNumber *rhs, decContext *set) {
1423   uInt status=0;                        // accumulator
1424   decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1425   if (status!=0) decStatus(res, status, set);
1426   return res;
1427   } // decNumberMax
1428 
1429 /* ------------------------------------------------------------------ */
1430 /* decNumberMaxMag -- compare and return the maximum by magnitude     */
1431 /*                                                                    */
1432 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1433 /*                                                                    */
1434 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1435 /*   lhs is A                                                         */
1436 /*   rhs is B                                                         */
1437 /*   set is the context                                               */
1438 /*                                                                    */
1439 /* C must have space for set->digits digits.                          */
1440 /* ------------------------------------------------------------------ */
1441 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1442                          const decNumber *rhs, decContext *set) {
1443   uInt status=0;                        // accumulator
1444   decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1445   if (status!=0) decStatus(res, status, set);
1446   return res;
1447   } // decNumberMaxMag
1448 
1449 /* ------------------------------------------------------------------ */
1450 /* decNumberMin -- compare two Numbers and return the minimum         */
1451 /*                                                                    */
1452 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1453 /*                                                                    */
1454 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1455 /*   lhs is A                                                         */
1456 /*   rhs is B                                                         */
1457 /*   set is the context                                               */
1458 /*                                                                    */
1459 /* C must have space for set->digits digits.                          */
1460 /* ------------------------------------------------------------------ */
1461 decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1462                          const decNumber *rhs, decContext *set) {
1463   uInt status=0;                        // accumulator
1464   decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1465   if (status!=0) decStatus(res, status, set);
1466   return res;
1467   } // decNumberMin
1468 
1469 /* ------------------------------------------------------------------ */
1470 /* decNumberMinMag -- compare and return the minimum by magnitude     */
1471 /*                                                                    */
1472 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1473 /*                                                                    */
1474 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1475 /*   lhs is A                                                         */
1476 /*   rhs is B                                                         */
1477 /*   set is the context                                               */
1478 /*                                                                    */
1479 /* C must have space for set->digits digits.                          */
1480 /* ------------------------------------------------------------------ */
1481 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1482                          const decNumber *rhs, decContext *set) {
1483   uInt status=0;                        // accumulator
1484   decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1485   if (status!=0) decStatus(res, status, set);
1486   return res;
1487   } // decNumberMinMag
1488 
1489 /* ------------------------------------------------------------------ */
1490 /* decNumberMinus -- prefix minus operator                            */
1491 /*                                                                    */
1492 /*   This computes C = 0 - A                                          */
1493 /*                                                                    */
1494 /*   res is C, the result.  C may be A                                */
1495 /*   rhs is A                                                         */
1496 /*   set is the context                                               */
1497 /*                                                                    */
1498 /* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1499 /* C must have space for set->digits digits.                          */
1500 /* ------------------------------------------------------------------ */
1501 /* Simply use AddOp for the subtract, which will do the necessary.    */
1502 /* ------------------------------------------------------------------ */
1503 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1504                            decContext *set) {
1505   decNumber dzero;
1506   uInt status=0;                        // accumulator
1507 
1508   decNumberZero(&dzero);                // make 0
1509   dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1510   decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1511   if (status!=0) decStatus(res, status, set);
1512   return res;
1513   } // decNumberMinus
1514 
1515 /* ------------------------------------------------------------------ */
1516 /* decNumberNextMinus -- next towards -Infinity                       */
1517 /*                                                                    */
1518 /*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1519 /*                                                                    */
1520 /*   res is C, the result.  C may be A                                */
1521 /*   rhs is A                                                         */
1522 /*   set is the context                                               */
1523 /*                                                                    */
1524 /* This is a generalization of 754 NextDown.                          */
1525 /* ------------------------------------------------------------------ */
1526 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1527                                decContext *set) {
1528   decNumber dtiny;                           // constant
1529   decContext workset=*set;                   // work
1530   uInt status=0;                             // accumulator
1531 
1532   // +Infinity is the special case
1533   if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1534     decSetMaxValue(res, set);                // is +ve
1535     // there is no status to set
1536     return res;
1537     }
1538   // Apply the context. If the result is inexact, we are done.
1539   workset.round=DEC_ROUND_FLOOR;
1540   workset.status=0;
1541   decNumberPlus(res, rhs, &workset);
1542   if (workset.status&(DEC_Inexact|DEC_NaNs)) {
1543     set->status |= (workset.status&DEC_NaNs);
1544     return res;
1545     }
1546   // Applying the context was exact. Subtract tiny quantity and round.
1547   decNumberZero(&dtiny); // start with 0
1548   dtiny.lsu[0]=1;
1549   dtiny.exponent=set->emin-set->digits;
1550   decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1551   status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1552   if (status!=0) decStatus(res, status, set);
1553   return res;
1554   } // decNumberNextMinus
1555 
1556 /* ------------------------------------------------------------------ */
1557 /* decNumberNextPlus -- next towards +Infinity                        */
1558 /*                                                                    */
1559 /*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1560 /*                                                                    */
1561 /*   res is C, the result.  C may be A                                */
1562 /*   rhs is A                                                         */
1563 /*   set is the context                                               */
1564 /*                                                                    */
1565 /* This is a generalization of 754 NextUp.                            */
1566 /* ------------------------------------------------------------------ */
1567 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1568                               decContext *set) {
1569   decNumber dtiny;                           // constant
1570   decContext workset=*set;                   // work
1571   uInt status=0;                             // accumulator
1572 
1573   // -Infinity is the special case
1574   if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1575     decSetMaxValue(res, set);
1576     res->bits=DECNEG;                        // negative
1577     // there is no status to set
1578     return res;
1579     }
1580   // Apply the context. If the result is inexact, we are done.
1581   workset.round=DEC_ROUND_CEILING;
1582   workset.status=0;
1583   decNumberPlus(res, rhs, &workset);
1584   if (workset.status&(DEC_Inexact|DEC_NaNs)) {
1585     set->status |= (workset.status&DEC_NaNs);
1586     return res;
1587     }
1588   // Applying the context was exact. Add tiny quantity and round.
1589   decNumberZero(&dtiny); // start with 0
1590   dtiny.lsu[0]=1;
1591   dtiny.exponent=set->emin-set->digits;
1592   decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1593   status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1594   if (status!=0) decStatus(res, status, set);
1595   return res;
1596   } // decNumberNextPlus
1597 
1598 /* ------------------------------------------------------------------ */
1599 /* decNumberNextToward -- next towards rhs                            */
1600 /*                                                                    */
1601 /*   This computes C = A +/- infinitesimal, rounded towards           */
1602 /*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1603 /*   modified during revision but dropped from 754-2008.              */
1604 /*                                                                    */
1605 /*   res is C, the result.  C may be A or B.                          */
1606 /*   lhs is A                                                         */
1607 /*   rhs is B                                                         */
1608 /*   set is the context                                               */
1609 /*                                                                    */
1610 /* This is a generalization of 754-1985 NextAfter.                    */
1611 /* ------------------------------------------------------------------ */
1612 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1613                                 const decNumber *rhs, decContext *set) {
1614   decNumber dtiny;                           // constant
1615   decContext workset=*set;                   // work
1616   Int result;                                // ..
1617   uInt status=0;                             // accumulator
1618 
1619   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1620     decNaNs(res, lhs, rhs, set, &status);
1621     }
1622    else { // Is numeric, so no chance of sNaN Invalid, etc.
1623     result=decCompare(lhs, rhs, 0);     // sign matters
1624     if (result==BADINT) status|=DEC_Insufficient_storage; // rare
1625      else { // valid compare
1626       if (result==0) decNumberCopySign(res, lhs, rhs); // easy
1627        else { // differ: need NextPlus or NextMinus
1628         uByte sub;                      // add or subtract
1629         if (result<0) {                 // lhs<rhs, do nextplus
1630           // -Infinity is the special case
1631           if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1632             decSetMaxValue(res, set);
1633             res->bits=DECNEG;           // negative
1634             return res;                 // there is no status to set
1635             }
1636           workset.round=DEC_ROUND_CEILING;
1637           sub=0;                        // add, please
1638           } // plus
1639          else {                         // lhs>rhs, do nextminus
1640           // +Infinity is the special case
1641           if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1642             decSetMaxValue(res, set);
1643             return res;                 // there is no status to set
1644             }
1645           workset.round=DEC_ROUND_FLOOR;
1646           sub=DECNEG;                   // subtract, please
1647           } // minus
1648         decNumberZero(&dtiny);          // start with 0
1649         dtiny.lsu[0]=1;                 // make number that is ..
1650         dtiny.exponent=DEC_MIN_EMIN-1;  // .. smaller than tiniest
1651         decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
1652         // turn off exceptions if the result is a normal number
1653         // (including Nmin), otherwise let all status through
1654         if (decNumberIsNormal(res, set)) status=0;
1655         } // unequal
1656       } // compare OK
1657     } // numeric
1658   if (status!=0) decStatus(res, status, set);
1659   return res;
1660   } // decNumberNextToward
1661 
1662 /* ------------------------------------------------------------------ */
1663 /* decNumberOr -- OR two Numbers, digitwise                           */
1664 /*                                                                    */
1665 /*   This computes C = A | B                                          */
1666 /*                                                                    */
1667 /*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1668 /*   lhs is A                                                         */
1669 /*   rhs is B                                                         */
1670 /*   set is the context (used for result length and error report)     */
1671 /*                                                                    */
1672 /* C must have space for set->digits digits.                          */
1673 /*                                                                    */
1674 /* Logical function restrictions apply (see above); a NaN is          */
1675 /* returned with Invalid_operation if a restriction is violated.      */
1676 /* ------------------------------------------------------------------ */
1677 decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1678                         const decNumber *rhs, decContext *set) {
1679   const Unit *ua, *ub;                  // -> operands
1680   const Unit *msua, *msub;              // -> operand msus
1681   Unit  *uc, *msuc;                     // -> result and its msu
1682   Int   msudigs;                        // digits in res msu
1683 
1684   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1685    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1686     decStatus(res, DEC_Invalid_operation, set);
1687     return res;
1688     }
1689   // operands are valid
1690   ua=lhs->lsu;                          // bottom-up
1691   ub=rhs->lsu;                          // ..
1692   uc=res->lsu;                          // ..
1693   msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
1694   msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
1695   msuc=uc+D2U(set->digits)-1;           // -> msu of result
1696   msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1697   for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
1698     Unit a, b;                          // extract units
1699     if (ua>msua) a=0;
1700      else a=*ua;
1701     if (ub>msub) b=0;
1702      else b=*ub;
1703     *uc=0;                              // can now write back
1704     if (a|b) {                          // maybe 1 bits to examine
1705       Int i, j;
1706       // This loop could be unrolled and/or use BIN2BCD tables
1707       for (i=0; i<DECDPUN; i++) {
1708         if ((a|b)&1) *uc=*uc+(Unit)powers[i];     // effect OR
1709         j=a%10;
1710         a=a/10;
1711         j|=b%10;
1712         b=b/10;
1713         if (j>1) {
1714           decStatus(res, DEC_Invalid_operation, set);
1715           return res;
1716           }
1717         if (uc==msuc && i==msudigs-1) break;      // just did final digit
1718         } // each digit
1719       } // non-zero
1720     } // each unit
1721   // [here uc-1 is the msu of the result]
1722   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1723   res->exponent=0;                      // integer
1724   res->bits=0;                          // sign=0
1725   return res;  // [no status to set]
1726   } // decNumberOr
1727 
1728 /* ------------------------------------------------------------------ */
1729 /* decNumberPlus -- prefix plus operator                              */
1730 /*                                                                    */
1731 /*   This computes C = 0 + A                                          */
1732 /*                                                                    */
1733 /*   res is C, the result.  C may be A                                */
1734 /*   rhs is A                                                         */
1735 /*   set is the context                                               */
1736 /*                                                                    */
1737 /* See also decNumberCopy for a quiet bitwise version of this.        */
1738 /* C must have space for set->digits digits.                          */
1739 /* ------------------------------------------------------------------ */
1740 /* This simply uses AddOp; Add will take fast path after preparing A. */
1741 /* Performance is a concern here, as this routine is often used to    */
1742 /* check operands and apply rounding and overflow/underflow testing.  */
1743 /* ------------------------------------------------------------------ */
1744 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1745                           decContext *set) {
1746   decNumber dzero;
1747   uInt status=0;                        // accumulator
1748 
1749   decNumberZero(&dzero);                // make 0
1750   dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1751   decAddOp(res, &dzero, rhs, set, 0, &status);
1752   if (status!=0) decStatus(res, status, set);
1753   return res;
1754   } // decNumberPlus
1755 
1756 /* ------------------------------------------------------------------ */
1757 /* decNumberMultiply -- multiply two Numbers                          */
1758 /*                                                                    */
1759 /*   This computes C = A x B                                          */
1760 /*                                                                    */
1761 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1762 /*   lhs is A                                                         */
1763 /*   rhs is B                                                         */
1764 /*   set is the context                                               */
1765 /*                                                                    */
1766 /* C must have space for set->digits digits.                          */
1767 /* ------------------------------------------------------------------ */
1768 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1769                               const decNumber *rhs, decContext *set) {
1770   uInt status=0;                   // accumulator
1771   decMultiplyOp(res, lhs, rhs, set, &status);
1772   if (status!=0) decStatus(res, status, set);
1773   return res;
1774   } // decNumberMultiply
1775 
1776 /* ------------------------------------------------------------------ */
1777 /* decNumberPower -- raise a number to a power                        */
1778 /*                                                                    */
1779 /*   This computes C = A ** B                                         */
1780 /*                                                                    */
1781 /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1782 /*   lhs is A                                                         */
1783 /*   rhs is B                                                         */
1784 /*   set is the context                                               */
1785 /*                                                                    */
1786 /* C must have space for set->digits digits.                          */
1787 /*                                                                    */
1788 /* Mathematical function restrictions apply (see above); a NaN is     */
1789 /* returned with Invalid_operation if a restriction is violated.      */
1790 /*                                                                    */
1791 /* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1792 /* restrictions on A and the context are relaxed to the usual bounds, */
1793 /* for compatibility with the earlier (integer power only) version    */
1794 /* of this function.                                                  */
1795 /*                                                                    */
1796 /* When B is an integer, the result may be exact, even if rounded.    */
1797 /*                                                                    */
1798 /* The final result is rounded according to the context; it will      */
1799 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1800 /* error in rare cases.                                               */
1801 /* ------------------------------------------------------------------ */
1802 decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
1803                            const decNumber *rhs, decContext *set) {
1804 #if DECSUBSET
1805   decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
1806   decNumber *allocrhs=NULL;        // .., rhs
1807 #endif
1808   decNumber *allocdac=NULL;        // -> allocated acc buffer, iff used
1809   decNumber *allocinv=NULL;        // -> allocated 1/x buffer, iff used
1810   Int   reqdigits=set->digits;     // requested DIGITS
1811   Int   n;                         // rhs in binary
1812   Flag  rhsint=0;                  // 1 if rhs is an integer
1813   Flag  useint=0;                  // 1 if can use integer calculation
1814   Flag  isoddint=0;                // 1 if rhs is an integer and odd
1815   Int   i;                         // work
1816 #if DECSUBSET
1817   Int   dropped;                   // ..
1818 #endif
1819   uInt  needbytes;                 // buffer size needed
1820   Flag  seenbit;                   // seen a bit while powering
1821   Int   residue=0;                 // rounding residue
1822   uInt  status=0;                  // accumulators
1823   uByte bits=0;                    // result sign if errors
1824   decContext aset;                 // working context
1825   decNumber dnOne;                 // work value 1...
1826   // local accumulator buffer [a decNumber, with digits+elength+1 digits]
1827   decNumber dacbuff[D2N(DECBUFFER+9)];
1828   decNumber *dac=dacbuff;          // -> result accumulator
1829   // same again for possible 1/lhs calculation
1830   decNumber invbuff[D2N(DECBUFFER+9)];
1831 
1832   do {                             // protect allocated storage
1833 #if DECSUBSET
1834     if (!set->extended) { // reduce operands and set status, as needed
1835       if (lhs->digits>reqdigits) {
1836         alloclhs=decRoundOperand(lhs, set, &status);
1837         if (alloclhs==NULL) break;
1838         lhs=alloclhs;
1839         }
1840       if (rhs->digits>reqdigits) {
1841         allocrhs=decRoundOperand(rhs, set, &status);
1842         if (allocrhs==NULL) break;
1843         rhs=allocrhs;
1844         }
1845       }
1846 #endif
1847     // [following code does not require input rounding]
1848 
1849     // handle NaNs and rhs Infinity (lhs infinity is harder)
1850     if (SPECIALARGS) {
1851       if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
1852         decNaNs(res, lhs, rhs, set, &status);
1853         break;}
1854       if (decNumberIsInfinite(rhs)) {   // rhs Infinity
1855         Flag rhsneg=rhs->bits&DECNEG;   // save rhs sign
1856         if (decNumberIsNegative(lhs)    // lhs<0
1857          && !decNumberIsZero(lhs))      // ..
1858           status|=DEC_Invalid_operation;
1859          else {                         // lhs >=0
1860           decNumberZero(&dnOne);        // set up 1
1861           dnOne.lsu[0]=1;
1862           decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1
1863           decNumberZero(res);           // prepare for 0/1/Infinity
1864           if (decNumberIsNegative(dac)) {    // lhs<1
1865             if (rhsneg) res->bits|=DECINF;   // +Infinity [else is +0]
1866             }
1867            else if (dac->lsu[0]==0) {        // lhs=1
1868             // 1**Infinity is inexact, so return fully-padded 1.0000
1869             Int shift=set->digits-1;
1870             *res->lsu=1;                     // was 0, make int 1
1871             res->digits=decShiftToMost(res->lsu, 1, shift);
1872             res->exponent=-shift;            // make 1.0000...
1873             status|=DEC_Inexact|DEC_Rounded; // deemed inexact
1874             }
1875            else {                            // lhs>1
1876             if (!rhsneg) res->bits|=DECINF;  // +Infinity [else is +0]
1877             }
1878           } // lhs>=0
1879         break;}
1880       // [lhs infinity drops through]
1881       } // specials
1882 
1883     // Original rhs may be an integer that fits and is in range
1884     n=decGetInt(rhs);
1885     if (n!=BADINT) {                    // it is an integer
1886       rhsint=1;                         // record the fact for 1**n
1887       isoddint=(Flag)n&1;               // [works even if big]
1888       if (n!=BIGEVEN && n!=BIGODD)      // can use integer path?
1889         useint=1;                       // looks good
1890       }
1891 
1892     if (decNumberIsNegative(lhs)        // -x ..
1893       && isoddint) bits=DECNEG;         // .. to an odd power
1894 
1895     // handle LHS infinity
1896     if (decNumberIsInfinite(lhs)) {     // [NaNs already handled]
1897       uByte rbits=rhs->bits;            // save
1898       decNumberZero(res);               // prepare
1899       if (n==0) *res->lsu=1;            // [-]Inf**0 => 1
1900        else {
1901         // -Inf**nonint -> error
1902         if (!rhsint && decNumberIsNegative(lhs)) {
1903           status|=DEC_Invalid_operation;     // -Inf**nonint is error
1904           break;}
1905         if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n
1906         // [otherwise will be 0 or -0]
1907         res->bits=bits;
1908         }
1909       break;}
1910 
1911     // similarly handle LHS zero
1912     if (decNumberIsZero(lhs)) {
1913       if (n==0) {                            // 0**0 => Error
1914 #if DECSUBSET
1915         if (!set->extended) {                // [unless subset]
1916           decNumberZero(res);
1917           *res->lsu=1;                       // return 1
1918           break;}
1919 #endif
1920         status|=DEC_Invalid_operation;
1921         }
1922        else {                                // 0**x
1923         uByte rbits=rhs->bits;               // save
1924         if (rbits & DECNEG) {                // was a 0**(-n)
1925 #if DECSUBSET
1926           if (!set->extended) {              // [bad if subset]
1927             status|=DEC_Invalid_operation;
1928             break;}
1929 #endif
1930           bits|=DECINF;
1931           }
1932         decNumberZero(res);                  // prepare
1933         // [otherwise will be 0 or -0]
1934         res->bits=bits;
1935         }
1936       break;}
1937 
1938     // here both lhs and rhs are finite; rhs==0 is handled in the
1939     // integer path.  Next handle the non-integer cases
1940     if (!useint) {                      // non-integral rhs
1941       // any -ve lhs is bad, as is either operand or context out of
1942       // bounds
1943       if (decNumberIsNegative(lhs)) {
1944         status|=DEC_Invalid_operation;
1945         break;}
1946       if (decCheckMath(lhs, set, &status)
1947        || decCheckMath(rhs, set, &status)) break; // variable status
1948 
1949       decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
1950       aset.emax=DEC_MAX_MATH;           // usual bounds
1951       aset.emin=-DEC_MAX_MATH;          // ..
1952       aset.clamp=0;                     // and no concrete format
1953 
1954       // calculate the result using exp(ln(lhs)*rhs), which can
1955       // all be done into the accumulator, dac.  The precision needed
1956       // is enough to contain the full information in the lhs (which
1957       // is the total digits, including exponent), or the requested
1958       // precision, if larger, + 4; 6 is used for the exponent
1959       // maximum length, and this is also used when it is shorter
1960       // than the requested digits as it greatly reduces the >0.5 ulp
1961       // cases at little cost (because Ln doubles digits each
1962       // iteration so a few extra digits rarely causes an extra
1963       // iteration)
1964       aset.digits=MAXI(lhs->digits, set->digits)+6+4;
1965       } // non-integer rhs
1966 
1967      else { // rhs is in-range integer
1968       if (n==0) {                       // x**0 = 1
1969         // (0**0 was handled above)
1970         decNumberZero(res);             // result=1
1971         *res->lsu=1;                    // ..
1972         break;}
1973       // rhs is a non-zero integer
1974       if (n<0) n=-n;                    // use abs(n)
1975 
1976       aset=*set;                        // clone the context
1977       aset.round=DEC_ROUND_HALF_EVEN;   // internally use balanced
1978       // calculate the working DIGITS
1979       aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
1980       aset.emax=DEC_MAX_EMAX;           // usual bounds
1981       aset.emin=DEC_MIN_EMIN;           // ..
1982       aset.clamp=0;                     // and no concrete format
1983 #if DECSUBSET
1984       if (!set->extended) aset.digits--;     // use classic precision
1985 #endif
1986       // it's an error if this is more than can be handled
1987       if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
1988       } // integer path
1989 
1990     // aset.digits is the count of digits for the accumulator needed
1991     // if accumulator is too long for local storage, then allocate
1992     needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
1993     // [needbytes also used below if 1/lhs needed]
1994     if (needbytes>sizeof(dacbuff)) {
1995       allocdac=(decNumber *)malloc(needbytes);
1996       if (allocdac==NULL) {   // hopeless -- abandon
1997         status|=DEC_Insufficient_storage;
1998         break;}
1999       dac=allocdac;           // use the allocated space
2000       }
2001     // here, aset is set up and accumulator is ready for use
2002 
2003     if (!useint) {                           // non-integral rhs
2004       // x ** y; special-case x=1 here as it will otherwise always
2005       // reduce to integer 1; decLnOp has a fastpath which detects
2006       // the case of x=1
2007       decLnOp(dac, lhs, &aset, &status);     // dac=ln(lhs)
2008       // [no error possible, as lhs 0 already handled]
2009       if (ISZERO(dac)) {                     // x==1, 1.0, etc.
2010         // need to return fully-padded 1.0000 etc., but rhsint->1
2011         *dac->lsu=1;                         // was 0, make int 1
2012         if (!rhsint) {                       // add padding
2013           Int shift=set->digits-1;
2014           dac->digits=decShiftToMost(dac->lsu, 1, shift);
2015           dac->exponent=-shift;              // make 1.0000...
2016           status|=DEC_Inexact|DEC_Rounded;   // deemed inexact
2017           }
2018         }
2019        else {
2020         decMultiplyOp(dac, dac, rhs, &aset, &status);  // dac=dac*rhs
2021         decExpOp(dac, dac, &aset, &status);            // dac=exp(dac)
2022         }
2023       // and drop through for final rounding
2024       } // non-integer rhs
2025 
2026      else {                             // carry on with integer
2027       decNumberZero(dac);               // acc=1
2028       *dac->lsu=1;                      // ..
2029 
2030       // if a negative power the constant 1 is needed, and if not subset
2031       // invert the lhs now rather than inverting the result later
2032       if (decNumberIsNegative(rhs)) {   // was a **-n [hence digits>0]
2033         decNumber *inv=invbuff;         // assume use fixed buffer
2034         decNumberCopy(&dnOne, dac);     // dnOne=1;  [needed now or later]
2035 #if DECSUBSET
2036         if (set->extended) {            // need to calculate 1/lhs
2037 #endif
2038           // divide lhs into 1, putting result in dac [dac=1/dac]
2039           decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2040           // now locate or allocate space for the inverted lhs
2041           if (needbytes>sizeof(invbuff)) {
2042             allocinv=(decNumber *)malloc(needbytes);
2043             if (allocinv==NULL) {       // hopeless -- abandon
2044               status|=DEC_Insufficient_storage;
2045               break;}
2046             inv=allocinv;               // use the allocated space
2047             }
2048           // [inv now points to big-enough buffer or allocated storage]
2049           decNumberCopy(inv, dac);      // copy the 1/lhs
2050 #if defined(__GNUC__) && \
2051  ( !defined(__clang__) || !defined(__llvm__) )
2052           if (dnOne.digits > 1) __builtin_unreachable ();
2053 #endif /* if defined(__GNUC__) &&
2054           ( !defined(__clang__) || !defined(__llvm__) ) */
2055           decNumberCopy(dac, &dnOne);   // restore acc=1
2056           lhs=inv;                      // .. and go forward with new lhs
2057 #if DECSUBSET
2058           }
2059 #endif
2060         }
2061 
2062       // Raise-to-the-power loop...
2063       seenbit=0;                   // set once a 1-bit is encountered
2064       for (i=1;;i++){              // for each bit [top bit ignored]
2065         // abandon if had overflow or terminal underflow
2066         if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?
2067           if (status&DEC_Overflow || ISZERO(dac)) break;
2068           }
2069         // [the following two lines revealed an optimizer bug in a C++
2070         // compiler, with symptom: 5**3 -> 25, when n=n+n was used]
2071         n=n<<1;                    // move next bit to testable position
2072         if (n<0) {                 // top bit is set
2073           seenbit=1;               // OK, significant bit seen
2074           decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x
2075           }
2076         if (i==31) break;          // that was the last bit
2077         if (!seenbit) continue;    // no need to square 1
2078         decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]
2079         } /*i*/ // 32 bits
2080 
2081       // complete internal overflow or underflow processing
2082       if (status & (DEC_Overflow|DEC_Underflow)) {
2083 #if DECSUBSET
2084         // If subset, and power was negative, reverse the kind of -erflow
2085         // [1/x not yet done]
2086         if (!set->extended && decNumberIsNegative(rhs)) {
2087           if (status & DEC_Overflow)
2088             status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2089            else { // trickier -- Underflow may or may not be set
2090             status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]
2091             status|=DEC_Overflow;
2092             }
2093           }
2094 #endif
2095         dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign
2096         // round subnormals [to set.digits rather than aset.digits]
2097         // or set overflow result similarly as required
2098         decFinalize(dac, set, &residue, &status);
2099         decNumberCopy(res, dac);   // copy to result (is now OK length)
2100         break;
2101         }
2102 
2103 #if DECSUBSET
2104       if (!set->extended &&                  // subset math
2105           decNumberIsNegative(rhs)) {        // was a **-n [hence digits>0]
2106         // so divide result into 1 [dac=1/dac]
2107         decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2108         }
2109 #endif
2110       } // rhs integer path
2111 
2112     // reduce result to the requested length and copy to result
2113     decCopyFit(res, dac, set, &residue, &status);
2114     decFinish(res, set, &residue, &status);  // final cleanup
2115 #if DECSUBSET
2116     if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros
2117 #endif
2118     } while(0);                         // end protected
2119 
2120   if (allocdac!=NULL) FREE(allocdac);   // drop any storage used
2121   if (allocinv!=NULL) FREE(allocinv);   // ..
2122 #if DECSUBSET
2123   if (alloclhs!=NULL) FREE(alloclhs);   // ..
2124   if (allocrhs!=NULL) FREE(allocrhs);   // ..
2125 #endif
2126   if (status!=0) decStatus(res, status, set);
2127   return res;
2128   } // decNumberPower
2129 
2130 /* ------------------------------------------------------------------ */
2131 /* decNumberQuantize -- force exponent to requested value             */
2132 /*                                                                    */
2133 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2134 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2135 /*   of C has exponent of B.  The numerical value of C will equal A,  */
2136 /*   except for the effects of any rounding that occurred.            */
2137 /*                                                                    */
2138 /*   res is C, the result.  C may be A or B                           */
2139 /*   lhs is A, the number to adjust                                   */
2140 /*   rhs is B, the number with exponent to match                      */
2141 /*   set is the context                                               */
2142 /*                                                                    */
2143 /* C must have space for set->digits digits.                          */
2144 /*                                                                    */
2145 /* Unless there is an error or the result is infinite, the exponent   */
2146 /* after the operation is guaranteed to be equal to that of B.        */
2147 /* ------------------------------------------------------------------ */
2148 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2149                               const decNumber *rhs, decContext *set) {
2150   uInt status=0;                        // accumulator
2151   decQuantizeOp(res, lhs, rhs, set, 1, &status);
2152   if (status!=0) decStatus(res, status, set);
2153   return res;
2154   } // decNumberQuantize
2155 
2156 /* ------------------------------------------------------------------ */
2157 /* decNumberReduce -- remove trailing zeros                           */
2158 /*                                                                    */
2159 /*   This computes C = 0 + A, and normalizes the result               */
2160 /*                                                                    */
2161 /*   res is C, the result.  C may be A                                */
2162 /*   rhs is A                                                         */
2163 /*   set is the context                                               */
2164 /*                                                                    */
2165 /* C must have space for set->digits digits.                          */
2166 /* ------------------------------------------------------------------ */
2167 // Previously known as Normalize
2168 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2169                                decContext *set) {
2170   return decNumberReduce(res, rhs, set);
2171   } // decNumberNormalize
2172 
2173 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2174                             decContext *set) {
2175 #if DECSUBSET
2176   decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2177 #endif
2178   uInt status=0;                   // as usual
2179   Int  residue=0;                  // as usual
2180   Int  dropped;                    // work
2181 
2182   do {                             // protect allocated storage
2183 #if DECSUBSET
2184     if (!set->extended) {
2185       // reduce operand and set lostDigits status, as needed
2186       if (rhs->digits>set->digits) {
2187         allocrhs=decRoundOperand(rhs, set, &status);
2188         if (allocrhs==NULL) break;
2189         rhs=allocrhs;
2190         }
2191       }
2192 #endif
2193     // [following code does not require input rounding]
2194 
2195     // Infinities copy through; NaNs need usual treatment
2196     if (decNumberIsNaN(rhs)) {
2197       decNaNs(res, rhs, NULL, set, &status);
2198       break;
2199       }
2200 
2201     // reduce result to the requested length and copy to result
2202     decCopyFit(res, rhs, set, &residue, &status); // copy & round
2203     decFinish(res, set, &residue, &status);       // cleanup/set flags
2204     decTrim(res, set, 1, 0, &dropped);            // normalize in place
2205                                                   // [may clamp]
2206     } while(0);                              // end protected
2207 
2208 #if DECSUBSET
2209   if (allocrhs !=NULL) FREE(allocrhs);       // ..
2210 #endif
2211   if (status!=0) decStatus(res, status, set);// then report status
2212   return res;
2213   } // decNumberReduce
2214 
2215 /* ------------------------------------------------------------------ */
2216 /* decNumberRescale -- force exponent to requested value              */
2217 /*                                                                    */
2218 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2219 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2220 /*   of C has the value B.  The numerical value of C will equal A,    */
2221 /*   except for the effects of any rounding that occurred.            */
2222 /*                                                                    */
2223 /*   res is C, the result.  C may be A or B                           */
2224 /*   lhs is A, the number to adjust                                   */
2225 /*   rhs is B, the requested exponent                                 */
2226 /*   set is the context                                               */
2227 /*                                                                    */
2228 /* C must have space for set->digits digits.                          */
2229 /*                                                                    */
2230 /* Unless there is an error or the result is infinite, the exponent   */
2231 /* after the operation is guaranteed to be equal to B.                */
2232 /* ------------------------------------------------------------------ */
2233 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2234                              const decNumber *rhs, decContext *set) {
2235   uInt status=0;                        // accumulator
2236   decQuantizeOp(res, lhs, rhs, set, 0, &status);
2237   if (status!=0) decStatus(res, status, set);
2238   return res;
2239   } // decNumberRescale
2240 
2241 /* ------------------------------------------------------------------ */
2242 /* decNumberRemainder -- divide and return remainder                  */
2243 /*                                                                    */
2244 /*   This computes C = A % B                                          */
2245 /*                                                                    */
2246 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2247 /*   lhs is A                                                         */
2248 /*   rhs is B                                                         */
2249 /*   set is the context                                               */
2250 /*                                                                    */
2251 /* C must have space for set->digits digits.                          */
2252 /* ------------------------------------------------------------------ */
2253 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2254                                const decNumber *rhs, decContext *set) {
2255   uInt status=0;                        // accumulator
2256   decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2257   if (status!=0) decStatus(res, status, set);
2258   return res;
2259   } // decNumberRemainder
2260 
2261 /* ------------------------------------------------------------------ */
2262 /* decNumberRemainderNear -- divide and return remainder from nearest */
2263 /*                                                                    */
2264 /*   This computes C = A % B, where % is the IEEE remainder operator  */
2265 /*                                                                    */
2266 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2267 /*   lhs is A                                                         */
2268 /*   rhs is B                                                         */
2269 /*   set is the context                                               */
2270 /*                                                                    */
2271 /* C must have space for set->digits digits.                          */
2272 /* ------------------------------------------------------------------ */
2273 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2274                                    const decNumber *rhs, decContext *set) {
2275   uInt status=0;                        // accumulator
2276   decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2277   if (status!=0) decStatus(res, status, set);
2278   return res;
2279   } // decNumberRemainderNear
2280 
2281 /* ------------------------------------------------------------------ */
2282 /* decNumberRotate -- rotate the coefficient of a Number left/right   */
2283 /*                                                                    */
2284 /*   This computes C = A rot B  (in base ten and rotating set->digits */
2285 /*   digits).                                                         */
2286 /*                                                                    */
2287 /*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2288 /*   lhs is A                                                         */
2289 /*   rhs is B, the number of digits to rotate (-ve to right)          */
2290 /*   set is the context                                               */
2291 /*                                                                    */
2292 /* The digits of the coefficient of A are rotated to the left (if B   */
2293 /* is positive) or to the right (if B is negative) without adjusting  */
2294 /* the exponent or the sign of A.  If lhs->digits is less than        */
2295 /* set->digits the coefficient is padded with zeros on the left       */
2296 /* before the rotate.  Any leading zeros in the result are removed    */
2297 /* as usual.                                                          */
2298 /*                                                                    */
2299 /* B must be an integer (q=0) and in the range -set->digits through   */
2300 /* +set->digits.                                                      */
2301 /* C must have space for set->digits digits.                          */
2302 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2303 /* B must be valid).  No status is set unless B is invalid or an      */
2304 /* operand is an sNaN.                                                */
2305 /* ------------------------------------------------------------------ */
2306 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2307                            const decNumber *rhs, decContext *set) {
2308   uInt status=0;              // accumulator
2309   Int  rotate;                // rhs as an Int
2310 
2311   // NaNs propagate as normal
2312   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2313     decNaNs(res, lhs, rhs, set, &status);
2314    // rhs must be an integer
2315    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2316     status=DEC_Invalid_operation;
2317    else { // both numeric, rhs is an integer
2318     rotate=decGetInt(rhs);                   // [cannot fail]
2319     if (rotate==BADINT                       // something bad ..
2320      || rotate==BIGODD || rotate==BIGEVEN    // .. very big ..
2321      || abs(rotate)>set->digits)             // .. or out of range
2322       status=DEC_Invalid_operation;
2323      else {                                  // rhs is OK
2324       decNumberCopy(res, lhs);
2325       if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
2326       // convert -ve rotate to equivalent positive rotation
2327       if (rotate<0) rotate=set->digits+rotate;
2328       if (rotate!=0 && rotate!=set->digits   // zero or full rotation
2329        && !decNumberIsInfinite(res)) {       // lhs was infinite
2330         // left-rotate to do; 0 < rotate < set->digits
2331         uInt units, shift;                   // work
2332         uInt msudigits;                      // digits in result msu
2333         Unit *msu=res->lsu+D2U(res->digits)-1;    // current msu
2334         Unit *msumax=res->lsu+D2U(set->digits)-1; //-V778 // rotation msu
2335         for (msu++; msu<=msumax; msu++) *msu=0;   // ensure high units=0
2336         res->digits=set->digits;                  // now full-length
2337         msudigits=MSUDIGITS(res->digits);         // actual digits in msu
2338 
2339         // rotation here is done in-place, in three steps
2340         // 1. shift all to least up to one unit to unit-align final
2341         //    lsd [any digits shifted out are rotated to the left,
2342         //    abutted to the original msd (which may require split)]
2343         //
2344         //    [if there are no whole units left to rotate, the
2345         //    rotation is now complete]
2346         //
2347         // 2. shift to least, from below the split point only, so that
2348         //    the final msd is in the right place in its Unit [any
2349         //    digits shifted out will fit exactly in the current msu,
2350         //    left aligned, no split required]
2351         //
2352         // 3. rotate all the units by reversing left part, right
2353         //    part, and then whole
2354         //
2355         // example: rotate right 8 digits (2 units + 2), DECDPUN=3.
2356         //
2357         //   start: 00a bcd efg hij klm npq
2358         //
2359         //      1a  000 0ab cde fgh|ijk lmn [pq saved]
2360         //      1b  00p qab cde fgh|ijk lmn
2361         //
2362         //      2a  00p qab cde fgh|00i jkl [mn saved]
2363         //      2b  mnp qab cde fgh|00i jkl
2364         //
2365         //      3a  fgh cde qab mnp|00i jkl
2366         //      3b  fgh cde qab mnp|jkl 00i
2367         //      3c  00i jkl mnp qab cde fgh
2368 
2369         // Step 1: amount to shift is the partial right-rotate count
2370         rotate=set->digits-rotate;      // make it right-rotate
2371         units=rotate/DECDPUN;           // whole units to rotate
2372         shift=rotate%DECDPUN;           // left-over digits count
2373         if (shift>0) {                  // not an exact number of units
2374           uInt save=res->lsu[0]%powers[shift]; //-V557 // save low digit(s)
2375           decShiftToLeast(res->lsu, D2U(res->digits), shift);
2376           if (shift>msudigits) {        // msumax-1 needs >0 digits
2377             uInt rem=save%powers[shift-msudigits];// split save
2378             *msumax=(Unit)(save/powers[shift-msudigits]); // and insert
2379             *(msumax-1)=*(msumax-1)
2380                        +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..
2381             }
2382            else { // all fits in msumax
2383             *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]
2384             }
2385           } // digits shift needed
2386 
2387         // If whole units to rotate...
2388         if (units>0) {                  // some to do
2389           // Step 2: the units to touch are the whole ones in rotate,
2390           //   if any, and the shift is DECDPUN-msudigits (which may be
2391           //   0, again)
2392           shift=DECDPUN-msudigits;
2393           if (shift>0) {                // not an exact number of units
2394             uInt save=res->lsu[0]%powers[shift];  // save low digit(s)
2395             decShiftToLeast(res->lsu, units, shift);
2396             *msumax=*msumax+(Unit)(save*powers[msudigits]);
2397             } // partial shift needed
2398 
2399           // Step 3: rotate the units array using triple reverse
2400           // (reversing is easy and fast)
2401           decReverse(res->lsu+units, msumax);     // left part
2402           decReverse(res->lsu, res->lsu+units-1); // right part
2403           decReverse(res->lsu, msumax);           // whole
2404           } // whole units to rotate
2405         // the rotation may have left an undetermined number of zeros
2406         // on the left, so true length needs to be calculated
2407         res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2408         } // rotate needed
2409       } // rhs OK
2410     } // numerics
2411   if (status!=0) decStatus(res, status, set);
2412   return res;
2413   } // decNumberRotate
2414 
2415 /* ------------------------------------------------------------------ */
2416 /* decNumberSameQuantum -- test for equal exponents                   */
2417 /*                                                                    */
2418 /*   res is the result number, which will contain either 0 or 1       */
2419 /*   lhs is a number to test                                          */
2420 /*   rhs is the second (usually a pattern)                            */
2421 /*                                                                    */
2422 /* No errors are possible and no context is needed.                   */
2423 /* ------------------------------------------------------------------ */
2424 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2425                                  const decNumber *rhs) {
2426   Unit ret=0;                      // return value
2427 
2428   if (SPECIALARGS) {
2429     if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2430      else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2431      // [anything else with a special gives 0]
2432     }
2433    else if (lhs->exponent==rhs->exponent) ret=1;
2434 
2435   decNumberZero(res);              // OK to overwrite an operand now
2436   *res->lsu=ret;
2437   return res;
2438   } // decNumberSameQuantum
2439 
2440 /* ------------------------------------------------------------------ */
2441 /* decNumberScaleB -- multiply by a power of 10                       */
2442 /*                                                                    */
2443 /* This computes C = A x 10**B where B is an integer (q=0) with       */
2444 /* maximum magnitude 2*(emax+digits)                                  */
2445 /*                                                                    */
2446 /*   res is C, the result.  C may be A or B                           */
2447 /*   lhs is A, the number to adjust                                   */
2448 /*   rhs is B, the requested power of ten to use                      */
2449 /*   set is the context                                               */
2450 /*                                                                    */
2451 /* C must have space for set->digits digits.                          */
2452 /*                                                                    */
2453 /* The result may underflow or overflow.                              */
2454 /* ------------------------------------------------------------------ */
2455 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2456                             const decNumber *rhs, decContext *set) {
2457   Int  reqexp;                // requested exponent change [B]
2458   uInt status=0;              // accumulator
2459   Int  residue;               // work
2460 
2461   // Handle special values except lhs infinite
2462   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2463     decNaNs(res, lhs, rhs, set, &status);
2464     // rhs must be an integer
2465    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2466     status=DEC_Invalid_operation;
2467    else {
2468     // lhs is a number; rhs is a finite with q==0
2469     reqexp=decGetInt(rhs);                   // [cannot fail]
2470     // maximum range is larger than getInt can handle, so this is
2471     // more restrictive than the specification
2472     if (reqexp==BADINT                       // something bad ..
2473      || reqexp==BIGODD || reqexp==BIGEVEN    // it was huge
2474      || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range
2475       status=DEC_Invalid_operation;
2476      else {                                  // rhs is OK
2477       decNumberCopy(res, lhs);               // all done if infinite lhs
2478       if (!decNumberIsInfinite(res)) {       // prepare to scale
2479         Int exp=res->exponent;               // save for overflow test
2480         res->exponent+=reqexp;               // adjust the exponent
2481         if (((exp^reqexp)>=0)                // same sign ...
2482          && ((exp^res->exponent)<0)) {       // .. but result had different
2483           // the calculation overflowed, so force right treatment
2484           if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;
2485            else      res->exponent=DEC_MAX_EMAX+1;
2486           }
2487         residue=0;
2488         decCopyFit(res, res, set, &residue, &status);
2489         decFinalize(res, set, &residue, &status); // final check
2490         } // finite LHS
2491       } // rhs OK
2492     } // rhs finite
2493   if (status!=0) decStatus(res, status, set);
2494   return res;
2495   } // decNumberScaleB
2496 
2497 /* ------------------------------------------------------------------ */
2498 /* decNumberShift -- shift the coefficient of a Number left or right  */
2499 /*                                                                    */
2500 /*   This computes C = A << B or C = A >> -B  (in base ten).          */
2501 /*                                                                    */
2502 /*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2503 /*   lhs is A                                                         */
2504 /*   rhs is B, the number of digits to shift (-ve to right)           */
2505 /*   set is the context                                               */
2506 /*                                                                    */
2507 /* The digits of the coefficient of A are shifted to the left (if B   */
2508 /* is positive) or to the right (if B is negative) without adjusting  */
2509 /* the exponent or the sign of A.                                     */
2510 /*                                                                    */
2511 /* B must be an integer (q=0) and in the range -set->digits through   */
2512 /* +set->digits.                                                      */
2513 /* C must have space for set->digits digits.                          */
2514 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2515 /* B must be valid).  No status is set unless B is invalid or an      */
2516 /* operand is an sNaN.                                                */
2517 /* ------------------------------------------------------------------ */
2518 decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2519                            const decNumber *rhs, decContext *set) {
2520   uInt status=0;              // accumulator
2521   Int  shift;                 // rhs as an Int
2522 
2523   // NaNs propagate as normal
2524   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2525     decNaNs(res, lhs, rhs, set, &status);
2526    // rhs must be an integer
2527    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2528     status=DEC_Invalid_operation;
2529    else { // both numeric, rhs is an integer
2530     shift=decGetInt(rhs);                    // [cannot fail]
2531     if (shift==BADINT                        // something bad ..
2532      || shift==BIGODD || shift==BIGEVEN      // .. very big ..
2533      || abs(shift)>set->digits)              // .. or out of range
2534       status=DEC_Invalid_operation;
2535      else {                                  // rhs is OK
2536       decNumberCopy(res, lhs);
2537       if (shift!=0 && !decNumberIsInfinite(res)) { // something to do
2538         if (shift>0) {                       // to left
2539           if (shift==set->digits) {          // removing all
2540             *res->lsu=0;                     // so place 0
2541             res->digits=1;                   // ..
2542             }
2543            else {                            //
2544             // first remove leading digits if necessary
2545             if (res->digits+shift>set->digits) {
2546               decDecap(res, res->digits+shift-set->digits);
2547               // that updated res->digits; may have gone to 1 (for a
2548               // single digit or for zero
2549               }
2550             if (res->digits>1 || *res->lsu)  // if non-zero..
2551               res->digits=decShiftToMost(res->lsu, res->digits, shift);
2552             } // partial left
2553           } // left
2554          else { // to right
2555           if (-shift>=res->digits) {         // discarding all
2556             *res->lsu=0;                     // so place 0
2557             res->digits=1;                   // ..
2558             }
2559            else {
2560             decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2561             res->digits-=(-shift);
2562             }
2563           } // to right
2564         } // non-0 non-Inf shift
2565       } // rhs OK
2566     } // numerics
2567   if (status!=0) decStatus(res, status, set);
2568   return res;
2569   } // decNumberShift
2570 
2571 /* ------------------------------------------------------------------ */
2572 /* decNumberSquareRoot -- square root operator                        */
2573 /*                                                                    */
2574 /*   This computes C = squareroot(A)                                  */
2575 /*                                                                    */
2576 /*   res is C, the result.  C may be A                                */
2577 /*   rhs is A                                                         */
2578 /*   set is the context; note that rounding mode has no effect        */
2579 /*                                                                    */
2580 /* C must have space for set->digits digits.                          */
2581 /* ------------------------------------------------------------------ */
2582 /* This uses the following varying-precision algorithm in:            */
2583 /*                                                                    */
2584 /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2585 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2586 /*   pp229-237, ACM, September 1985.                                  */
2587 /*                                                                    */
2588 /* The square-root is calculated using Newton's method, after which   */
2589 /* a check is made to ensure the result is correctly rounded.         */
2590 /*                                                                    */
2591 /* % [Reformatted original Numerical Turing source code follows.]     */
2592 /* function sqrt(x : real) : real                                     */
2593 /* % sqrt(x) returns the properly rounded approximation to the square */
2594 /* % root of x, in the precision of the calling environment, or it    */
2595 /* % fails if x < 0.                                                  */
2596 /* % t e hull and a abrham, august, 1984                              */
2597 /* if x <= 0 then                                                     */
2598 /*   if x < 0 then                                                    */
2599 /*     assert false                                                   */
2600 /*   else                                                             */
2601 /*     result 0                                                       */
2602 /*   end if                                                           */
2603 /* end if                                                             */
2604 /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2605 /* var e := getexp(x)     % exponent part of x                        */
2606 /* var approx : real                                                  */
2607 /* if e mod 2 = 0  then                                               */
2608 /*   approx := .259 + .819 * f   % approx to root of f                */
2609 /* else                                                               */
2610 /*   f := f/l0                   % adjustments                        */
2611 /*   e := e + 1                  %   for odd                          */
2612 /*   approx := .0819 + 2.59 * f  %   exponent                         */
2613 /* end if                                                             */
2614 /*                                                                    */
2615 /* var p:= 3                                                          */
2616 /* const maxp := currentprecision + 2                                 */
2617 /* loop                                                               */
2618 /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2619 /*   precision p                                                      */
2620 /*   approx := .5 * (approx + f/approx)                               */
2621 /*   exit when p = maxp                                               */
2622 /* end loop                                                           */
2623 /*                                                                    */
2624 /* % approx is now within 1 ulp of the properly rounded square root   */
2625 /* % of f; to ensure proper rounding, compare squares of (approx -    */
2626 /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2627 /* p := currentprecision                                              */
2628 /* begin                                                              */
2629 /*   precision p + 2                                                  */
2630 /*   const approxsubhalf := approx - setexp(.5, -p)                   */
2631 /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2632 /*     approx := approx - setexp(.l, -p + 1)                          */
2633 /*   else                                                             */
2634 /*     const approxaddhalf := approx + setexp(.5, -p)                 */
2635 /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2636 /*       approx := approx + setexp(.l, -p + 1)                        */
2637 /*     end if                                                         */
2638 /*   end if                                                           */
2639 /* end                                                                */
2640 /* result setexp(approx, e div 2)  % fix exponent                     */
2641 /* end sqrt                                                           */
2642 /* ------------------------------------------------------------------ */
2643 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2644                                 decContext *set) {
2645   decContext workset, approxset;   // work contexts
2646   decNumber dzero;                 // used for constant zero
2647   Int  maxp;                       // largest working precision
2648   Int  workp;                      // working precision
2649   Int  residue=0;                  // rounding residue
2650   uInt status=0, ignore=0;         // status accumulators
2651   uInt rstatus;                    // ..
2652   Int  exp;                        // working exponent
2653   Int  ideal;                      // ideal (preferred) exponent
2654   Int  needbytes;                  // work
2655   Int  dropped;                    // ..
2656 
2657 #if DECSUBSET
2658   decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2659 #endif
2660   // buffer for f [needs +1 in case DECBUFFER 0]
2661   decNumber buff[D2N(DECBUFFER+1)];
2662   // buffer for a [needs +2 to match likely maxp]
2663   decNumber bufa[D2N(DECBUFFER+2)];
2664   // buffer for temporary, b [must be same size as a]
2665   decNumber bufb[D2N(DECBUFFER+2)];
2666   decNumber *allocbuff=NULL;       // -> allocated buff, iff allocated
2667   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
2668   decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
2669   decNumber *f=buff;               // reduced fraction
2670   decNumber *a=bufa;               // approximation to result
2671   decNumber *b=bufb;               // intermediate result
2672   // buffer for temporary variable, up to 3 digits
2673   decNumber buft[D2N(3)];
2674   decNumber *t=buft;               // up-to-3-digit constant or work
2675 
2676   do {                             // protect allocated storage
2677 #if DECSUBSET
2678     if (!set->extended) {
2679       // reduce operand and set lostDigits status, as needed
2680       if (rhs->digits>set->digits) {
2681         allocrhs=decRoundOperand(rhs, set, &status);
2682         if (allocrhs==NULL) break;
2683         // [Note: 'f' allocation below could reuse this buffer if
2684         // used, but as this is rare they are kept separate for clarity.]
2685         rhs=allocrhs;
2686         }
2687       }
2688 #endif
2689     // [following code does not require input rounding]
2690 
2691     // handle infinities and NaNs
2692     if (SPECIALARG) {
2693       if (decNumberIsInfinite(rhs)) {         // an infinity
2694         if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2695          else decNumberCopy(res, rhs);        // +Infinity
2696         }
2697        else decNaNs(res, rhs, NULL, set, &status); // a NaN
2698       break;
2699       }
2700 
2701     // calculate the ideal (preferred) exponent [floor(exp/2)]
2702     // [It would be nicer to write: ideal=rhs->exponent>>1, but this
2703     // generates a compiler warning.  Generated code is the same.]
2704     ideal=(rhs->exponent&~1)/2;         // target
2705 
2706     // handle zeros
2707     if (ISZERO(rhs)) {
2708       decNumberCopy(res, rhs);          // could be 0 or -0
2709       res->exponent=ideal;              // use the ideal [safe]
2710       // use decFinish to clamp any out-of-range exponent, etc.
2711       decFinish(res, set, &residue, &status);
2712       break;
2713       }
2714 
2715     // any other -x is an oops
2716     if (decNumberIsNegative(rhs)) {
2717       status|=DEC_Invalid_operation;
2718       break;
2719       }
2720 
2721     // space is needed for three working variables
2722     //   f -- the same precision as the RHS, reduced to 0.01->0.99...
2723     //   a -- Hull's approximation -- precision, when assigned, is
2724     //        currentprecision+1 or the input argument precision,
2725     //        whichever is larger (+2 for use as temporary)
2726     //   b -- intermediate temporary result (same size as a)
2727     // if any is too long for local storage, then allocate
2728     workp=MAXI(set->digits+1, rhs->digits);  // actual rounding precision
2729     workp=MAXI(workp, 7);                    // at least 7 for low cases
2730     maxp=workp+2;                            // largest working precision
2731 
2732     needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2733     if (needbytes>(Int)sizeof(buff)) {
2734       allocbuff=(decNumber *)malloc(needbytes);
2735       if (allocbuff==NULL) {  // hopeless -- abandon
2736         status|=DEC_Insufficient_storage;
2737         break;}
2738       f=allocbuff;            // use the allocated space
2739       }
2740     // a and b both need to be able to hold a maxp-length number
2741     needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2742     if (needbytes>(Int)sizeof(bufa)) {            // [same applies to b]
2743       allocbufa=(decNumber *)malloc(needbytes);
2744       allocbufb=(decNumber *)malloc(needbytes);
2745       if (allocbufa==NULL || allocbufb==NULL) {   // hopeless
2746         status|=DEC_Insufficient_storage;
2747         break;}
2748       a=allocbufa;            // use the allocated spaces
2749       b=allocbufb;            // ..
2750       }
2751 
2752     // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1
2753     decNumberCopy(f, rhs);
2754     exp=f->exponent+f->digits;               // adjusted to Hull rules
2755     f->exponent=-(f->digits);                // to range
2756 
2757     // set up working context
2758     decContextDefault(&workset, DEC_INIT_DECIMAL64);
2759     workset.emax=DEC_MAX_EMAX;
2760     workset.emin=DEC_MIN_EMIN;
2761 
2762     // [Until further notice, no error is possible and status bits
2763     // (Rounded, etc.) should be ignored, not accumulated.]
2764 
2765     // Calculate initial approximation, and allow for odd exponent
2766     workset.digits=workp;                    // p for initial calculation
2767     t->bits=0; t->digits=3;
2768     a->bits=0; a->digits=3;
2769     if ((exp & 1)==0) {                      // even exponent
2770       // Set t=0.259, a=0.819
2771       t->exponent=-3;
2772       a->exponent=-3;
2773 #if DECDPUN>=3
2774         t->lsu[0]=259;
2775         a->lsu[0]=819;
2776 #elif DECDPUN==2
2777         t->lsu[0]=59; t->lsu[1]=2;
2778         a->lsu[0]=19; a->lsu[1]=8;
2779 #else
2780         t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2781         a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2782 #endif
2783       }
2784      else {                                  // odd exponent
2785       // Set t=0.0819, a=2.59
2786       f->exponent--;                         // f=f/10
2787       exp++;                                 // e=e+1
2788       t->exponent=-4;
2789       a->exponent=-2;
2790 #if DECDPUN>=3
2791         t->lsu[0]=819;
2792         a->lsu[0]=259;
2793 #elif DECDPUN==2
2794         t->lsu[0]=19; t->lsu[1]=8;
2795         a->lsu[0]=59; a->lsu[1]=2;
2796 #else
2797         t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2798         a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2799 #endif
2800       }
2801 
2802     decMultiplyOp(a, a, f, &workset, &ignore);    // a=a*f
2803     decAddOp(a, a, t, &workset, 0, &ignore);      // ..+t
2804     // [a is now the initial approximation for sqrt(f), calculated with
2805     // currentprecision, which is also a's precision.]
2806 
2807     // the main calculation loop
2808     decNumberZero(&dzero);                   // make 0
2809     decNumberZero(t);                        // set t = 0.5
2810     t->lsu[0]=5;                             // ..
2811     t->exponent=-1;                          // ..
2812     workset.digits=3;                        // initial p
2813     for (; workset.digits<maxp;) {
2814       // set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]
2815       workset.digits=MINI(workset.digits*2-2, maxp);
2816       // a = 0.5 * (a + f/a)
2817       // [calculated at p then rounded to currentprecision]
2818       decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a
2819       decAddOp(b, b, a, &workset, 0, &ignore);         // b=b+a
2820       decMultiplyOp(a, b, t, &workset, &ignore);       // a=b*0.5
2821       } // loop
2822 
2823     // Here, 0.1 <= a < 1 [Hull], and a has maxp digits
2824     // now reduce to length, etc.; this needs to be done with a
2825     // having the correct exponent so as to handle subnormals
2826     // correctly
2827     approxset=*set;                          // get emin, emax, etc.
2828     approxset.round=DEC_ROUND_HALF_EVEN;
2829     a->exponent+=exp/2;                      // set correct exponent
2830     rstatus=0;                               // clear status
2831     residue=0;                               // .. and accumulator
2832     decCopyFit(a, a, &approxset, &residue, &rstatus);  // reduce (if needed)
2833     decFinish(a, &approxset, &residue, &rstatus);      // clean and finalize
2834 
2835     // Overflow was possible if the input exponent was out-of-range,
2836     // in which case quit
2837     if (rstatus&DEC_Overflow) {
2838       status=rstatus;                        // use the status as-is
2839       decNumberCopy(res, a);                 // copy to result
2840       break;
2841       }
2842 
2843     // Preserve status except Inexact/Rounded
2844     status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
2845 
2846     // Carry out the Hull correction
2847     a->exponent-=exp/2;                      // back to 0.1->1
2848 
2849     // a is now at final precision and within 1 ulp of the properly
2850     // rounded square root of f; to ensure proper rounding, compare
2851     // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.
2852     // Here workset.digits=maxp and t=0.5, and a->digits determines
2853     // the ulp
2854     workset.digits--;                             // maxp-1 is OK now
2855     t->exponent=-a->digits-1;                     // make 0.5 ulp
2856     decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp
2857     workset.round=DEC_ROUND_UP;
2858     decMultiplyOp(b, b, b, &workset, &ignore);    // b = mulru(b, b)
2859     decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed
2860     if (decNumberIsNegative(b)) {                 // f < b [i.e., b > f]
2861       // this is the more common adjustment, though both are rare
2862       t->exponent++;                              // make 1.0 ulp
2863       t->lsu[0]=1;                                // ..
2864       decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp
2865       // assign to approx [round to length]
2866       approxset.emin-=exp/2;                      // adjust to match a
2867       approxset.emax-=exp/2;
2868       decAddOp(a, &dzero, a, &approxset, 0, &ignore);
2869       }
2870      else {
2871       decAddOp(b, a, t, &workset, 0, &ignore);    // b = a + 0.5 ulp
2872       workset.round=DEC_ROUND_DOWN;
2873       decMultiplyOp(b, b, b, &workset, &ignore);  // b = mulrd(b, b)
2874       decCompareOp(b, b, f, &workset, COMPARE, &ignore);   // b ? f
2875       if (decNumberIsNegative(b)) {               // b < f
2876         t->exponent++;                            // make 1.0 ulp
2877         t->lsu[0]=1;                              // ..
2878         decAddOp(a, a, t, &workset, 0, &ignore);  // a = a + 1 ulp
2879         // assign to approx [round to length]
2880         approxset.emin-=exp/2;                    // adjust to match a
2881         approxset.emax-=exp/2;
2882         decAddOp(a, &dzero, a, &approxset, 0, &ignore);
2883         }
2884       }
2885     // [no errors are possible in the above, and rounding/inexact during
2886     // estimation are irrelevant, so status was not accumulated]
2887 
2888     // Here, 0.1 <= a < 1  (still), so adjust back
2889     a->exponent+=exp/2;                      // set correct exponent
2890 
2891     // count droppable zeros [after any subnormal rounding] by
2892     // trimming a copy
2893     decNumberCopy(b, a);
2894     decTrim(b, set, 1, 1, &dropped);         // [drops trailing zeros]
2895 
2896     // Set Inexact and Rounded.  The answer can only be exact if
2897     // it is short enough so that squaring it could fit in workp
2898     // digits, so this is the only (relatively rare) condition that
2899     // a careful check is needed
2900     if (b->digits*2-1 > workp) {             // cannot fit
2901       status|=DEC_Inexact|DEC_Rounded;
2902       }
2903      else {                                  // could be exact/unrounded
2904       uInt mstatus=0;                        // local status
2905       decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply
2906       if (mstatus&DEC_Overflow) {            // result just won't fit
2907         status|=DEC_Inexact|DEC_Rounded;
2908         }
2909        else {                                // plausible
2910         decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs
2911         if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal
2912          else {                              // is Exact
2913           // here, dropped is the count of trailing zeros in 'a'
2914           // use closest exponent to ideal...
2915           Int todrop=ideal-a->exponent;      // most that can be dropped
2916           if (todrop<0) status|=DEC_Rounded; // ideally would add 0s
2917            else {                            // unrounded
2918             // there are some to drop, but emax may not allow all
2919             Int maxexp=set->emax-set->digits+1;
2920             Int maxdrop=maxexp-a->exponent;
2921             if (todrop>maxdrop && set->clamp) { // apply clamping
2922               todrop=maxdrop;
2923               status|=DEC_Clamped;
2924               }
2925             if (dropped<todrop) {            // clamp to those available
2926               todrop=dropped;
2927               status|=DEC_Clamped;
2928               }
2929             if (todrop>0) {                  // have some to drop
2930               decShiftToLeast(a->lsu, D2U(a->digits), todrop);
2931               a->exponent+=todrop;           // maintain numerical value
2932               a->digits-=todrop;             // new length
2933               }
2934             }
2935           }
2936         }
2937       }
2938 
2939     // double-check Underflow, as perhaps the result could not have
2940     // been subnormal (initial argument too big), or it is now Exact
2941     if (status&DEC_Underflow) {
2942       Int ae=rhs->exponent+rhs->digits-1;    // adjusted exponent
2943       // check if truly subnormal
2944 #if DECEXTFLAG                         // DEC_Subnormal too
2945         if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
2946 #else
2947         if (ae>=set->emin*2) status&=~DEC_Underflow;
2948 #endif
2949       // check if truly inexact
2950       if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
2951       }
2952 
2953     decNumberCopy(res, a);                   // a is now the result
2954     } while(0);                              // end protected
2955 
2956   if (allocbuff!=NULL) FREE(allocbuff);      // drop any storage used
2957   if (allocbufa!=NULL) FREE(allocbufa);      // ..
2958   if (allocbufb!=NULL) FREE(allocbufb);      // ..
2959 #if DECSUBSET
2960   if (allocrhs !=NULL) FREE(allocrhs);       // ..
2961 #endif
2962   if (status!=0) decStatus(res, status, set);// then report status
2963   return res;
2964   } // decNumberSquareRoot
2965 
2966 /* ------------------------------------------------------------------ */
2967 /* decNumberSubtract -- subtract two Numbers                          */
2968 /*                                                                    */
2969 /*   This computes C = A - B                                          */
2970 /*                                                                    */
2971 /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
2972 /*   lhs is A                                                         */
2973 /*   rhs is B                                                         */
2974 /*   set is the context                                               */
2975 /*                                                                    */
2976 /* C must have space for set->digits digits.                          */
2977 /* ------------------------------------------------------------------ */
2978 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
2979                               const decNumber *rhs, decContext *set) {
2980   uInt status=0;                        // accumulator
2981 
2982   decAddOp(res, lhs, rhs, set, DECNEG, &status);
2983   if (status!=0) decStatus(res, status, set);
2984   return res;
2985   } // decNumberSubtract
2986 
2987 /* ------------------------------------------------------------------ */
2988 /* decNumberToIntegralExact -- round-to-integral-value with InExact   */
2989 /* decNumberToIntegralValue -- round-to-integral-value                */
2990 /*                                                                    */
2991 /*   res is the result                                                */
2992 /*   rhs is input number                                              */
2993 /*   set is the context                                               */
2994 /*                                                                    */
2995 /* res must have space for any value of rhs.                          */
2996 /*                                                                    */
2997 /* This implements the IEEE special operators and therefore treats    */
2998 /* special values as valid.  For finite numbers it returns            */
2999 /* rescale(rhs, 0) if rhs->exponent is <0.                            */
3000 /* Otherwise the result is rhs (so no error is possible, except for   */
3001 /* sNaN).                                                             */
3002 /*                                                                    */
3003 /* The context is used for rounding mode and status after sNaN, but   */
3004 /* the digits setting is ignored.  The Exact version will signal      */
3005 /* Inexact if the result differs numerically from rhs; the other      */
3006 /* never signals Inexact.                                             */
3007 /* ------------------------------------------------------------------ */
3008 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
3009                                      decContext *set) {
3010   decNumber dn;
3011   decContext workset;              // working context
3012   uInt status=0;                   // accumulator
3013 
3014   // handle infinities and NaNs
3015   if (SPECIALARG) {
3016     if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity
3017      else decNaNs(res, rhs, NULL, set, &status); // a NaN
3018     }
3019    else { // finite
3020     // have a finite number; no error possible (res must be big enough)
3021     if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3022     // that was easy, but if negative exponent there is work to do...
3023     workset=*set;                  // clone rounding, etc.
3024     workset.digits=rhs->digits;    // no length rounding
3025     workset.traps=0;               // no traps
3026     decNumberZero(&dn);            // make a number with exponent 0
3027     decNumberQuantize(res, rhs, &dn, &workset);
3028     status|=workset.status;
3029     }
3030   if (status!=0) decStatus(res, status, set);
3031   return res;
3032   } // decNumberToIntegralExact
3033 
3034 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
3035                                      decContext *set) {
3036   decContext workset=*set;         // working context
3037   workset.traps=0;                 // no traps
3038   decNumberToIntegralExact(res, rhs, &workset);
3039   // this never affects set, except for sNaNs; NaN will have been set
3040   // or propagated already, so no need to call decStatus
3041   set->status|=workset.status&DEC_Invalid_operation;
3042   return res;
3043   } // decNumberToIntegralValue
3044 
3045 /* ------------------------------------------------------------------ */
3046 /* decNumberXor -- XOR two Numbers, digitwise                         */
3047 /*                                                                    */
3048 /*   This computes C = A ^ B                                          */
3049 /*                                                                    */
3050 /*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3051 /*   lhs is A                                                         */
3052 /*   rhs is B                                                         */
3053 /*   set is the context (used for result length and error report)     */
3054 /*                                                                    */
3055 /* C must have space for set->digits digits.                          */
3056 /*                                                                    */
3057 /* Logical function restrictions apply (see above); a NaN is          */
3058 /* returned with Invalid_operation if a restriction is violated.      */
3059 /* ------------------------------------------------------------------ */
3060 decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
3061                          const decNumber *rhs, decContext *set) {
3062   const Unit *ua, *ub;                  // -> operands
3063   const Unit *msua, *msub;              // -> operand msus
3064   Unit  *uc, *msuc;                     // -> result and its msu
3065   Int   msudigs;                        // digits in res msu
3066 
3067   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3068    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3069     decStatus(res, DEC_Invalid_operation, set);
3070     return res;
3071     }
3072   // operands are valid
3073   ua=lhs->lsu;                          // bottom-up
3074   ub=rhs->lsu;                          // ..
3075   uc=res->lsu;                          // ..
3076   msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
3077   msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
3078   msuc=uc+D2U(set->digits)-1;           // -> msu of result
3079   msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
3080   for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
3081     Unit a, b;                          // extract units
3082     if (ua>msua) a=0;
3083      else a=*ua;
3084     if (ub>msub) b=0;
3085      else b=*ub;
3086     *uc=0;                              // can now write back
3087     if (a|b) {                          // maybe 1 bits to examine
3088       Int i, j;
3089       // This loop could be unrolled and/or use BIN2BCD tables
3090       for (i=0; i<DECDPUN; i++) {
3091         if ((a^b)&1) *uc=*uc+(Unit)powers[i];     // effect XOR
3092         j=a%10;
3093         a=a/10;
3094         j|=b%10;
3095         b=b/10;
3096         if (j>1) {
3097           decStatus(res, DEC_Invalid_operation, set);
3098           return res;
3099           }
3100         if (uc==msuc && i==msudigs-1) break;      // just did final digit
3101         } // each digit
3102       } // non-zero
3103     } // each unit
3104   // [here uc-1 is the msu of the result]
3105   res->digits=decGetDigits(res->lsu, uc-res->lsu);
3106   res->exponent=0;                      // integer
3107   res->bits=0;                          // sign=0
3108   return res;  // [no status to set]
3109   } // decNumberXor
3110 
3111 /* ================================================================== */
3112 /* Utility routines                                                   */
3113 /* ================================================================== */
3114 
3115 /* ------------------------------------------------------------------ */
3116 /* decNumberClass -- return the decClass of a decNumber               */
3117 /*   dn -- the decNumber to test                                      */
3118 /*   set -- the context to use for Emin                               */
3119 /*   returns the decClass enum                                        */
3120 /* ------------------------------------------------------------------ */
3121 enum decClass decNumberClass(const decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
3122   if (decNumberIsSpecial(dn)) {
3123     if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3124     if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3125     // must be an infinity
3126     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3127     return DEC_CLASS_POS_INF;
3128     }
3129   // is finite
3130   if (decNumberIsNormal(dn, set)) { // most common
3131     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3132     return DEC_CLASS_POS_NORMAL;
3133     }
3134   // is subnormal or zero
3135   if (decNumberIsZero(dn)) {    // most common
3136     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3137     return DEC_CLASS_POS_ZERO;
3138     }
3139   if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3140   return DEC_CLASS_POS_SUBNORMAL;
3141   } // decNumberClass
3142 
3143 /* ------------------------------------------------------------------ */
3144 /* decNumberClassToString -- convert decClass to a string             */
3145 /*                                                                    */
3146 /*  eclass is a valid decClass                                        */
3147 /*  returns a constant string describing the class (max 13+1 chars)   */
3148 /* ------------------------------------------------------------------ */
3149 const char *decNumberClassToString(enum decClass eclass) {
     /* [previous][next][first][last][top][bottom][index][help] */
3150   if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3151   if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3152   if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3153   if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3154   if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3155   if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3156   if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3157   if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3158   if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3159   if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3160   return DEC_ClassString_UN;           // Unknown
3161   } // decNumberClassToString
3162 
3163 /* ------------------------------------------------------------------ */
3164 /* decNumberCopy -- copy a number                                     */
3165 /*                                                                    */
3166 /*   dest is the target decNumber                                     */
3167 /*   src  is the source decNumber                                     */
3168 /*   returns dest                                                     */
3169 /*                                                                    */
3170 /* (dest==src is allowed and is a no-op)                              */
3171 /* All fields are updated as required.  This is a utility operation,  */
3172 /* so special values are unchanged and no error is possible.          */
3173 /* ------------------------------------------------------------------ */
3174 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
     /* [previous][next][first][last][top][bottom][index][help] */
3175 
3176   if (dest==src) return dest;                // no copy required
3177 
3178   // Use explicit assignments here as structure assignment could copy
3179   // more than just the lsu (for small DECDPUN).  This would not affect
3180   // the value of the results, but could disturb test harness spill
3181   // checking.
3182   dest->bits=src->bits;
3183   dest->exponent=src->exponent;
3184   dest->digits=src->digits;
3185   dest->lsu[0]=src->lsu[0];
3186   if (src->digits>DECDPUN) {                 // more Units to come
3187     const Unit *smsup, *s;                   // work
3188     Unit  *d;                                // ..
3189     // memcpy for the remaining Units would be safe as they cannot
3190     // overlap.  However, this explicit loop is faster in short cases.
3191     d=dest->lsu+1;                           // -> first destination
3192     smsup=src->lsu+D2U(src->digits);         // -> source msu+1
3193     for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3194     }
3195   return dest;
3196   } // decNumberCopy
3197 
3198 /* ------------------------------------------------------------------ */
3199 /* decNumberCopyAbs -- quiet absolute value operator                  */
3200 /*                                                                    */
3201 /*   This sets C = abs(A)                                             */
3202 /*                                                                    */
3203 /*   res is C, the result.  C may be A                                */
3204 /*   rhs is A                                                         */
3205 /*                                                                    */
3206 /* C must have space for set->digits digits.                          */
3207 /* No exception or error can occur; this is a quiet bitwise operation.*/
3208 /* See also decNumberAbs for a checking version of this.              */
3209 /* ------------------------------------------------------------------ */
3210 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
     /* [previous][next][first][last][top][bottom][index][help] */
3211   decNumberCopy(res, rhs);
3212   res->bits&=~DECNEG;                   // turn off sign
3213   return res;
3214   } // decNumberCopyAbs
3215 
3216 /* ------------------------------------------------------------------ */
3217 /* decNumberCopyNegate -- quiet negate value operator                 */
3218 /*                                                                    */
3219 /*   This sets C = negate(A)                                          */
3220 /*                                                                    */
3221 /*   res is C, the result.  C may be A                                */
3222 /*   rhs is A                                                         */
3223 /*                                                                    */
3224 /* C must have space for set->digits digits.                          */
3225 /* No exception or error can occur; this is a quiet bitwise operation.*/
3226 /* See also decNumberMinus for a checking version of this.            */
3227 /* ------------------------------------------------------------------ */
3228 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
     /* [previous][next][first][last][top][bottom][index][help] */
3229   decNumberCopy(res, rhs);
3230   res->bits^=DECNEG;                    // invert the sign
3231   return res;
3232   } // decNumberCopyNegate
3233 
3234 /* ------------------------------------------------------------------ */
3235 /* decNumberCopySign -- quiet copy and set sign operator              */
3236 /*                                                                    */
3237 /*   This sets C = A with the sign of B                               */
3238 /*                                                                    */
3239 /*   res is C, the result.  C may be A                                */
3240 /*   lhs is A                                                         */
3241 /*   rhs is B                                                         */
3242 /*                                                                    */
3243 /* C must have space for set->digits digits.                          */
3244 /* No exception or error can occur; this is a quiet bitwise operation.*/
3245 /* ------------------------------------------------------------------ */
3246 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
3247                               const decNumber *rhs) {
3248   uByte sign;                           // rhs sign
3249   sign=rhs->bits & DECNEG;              // save sign bit
3250   decNumberCopy(res, lhs);
3251   res->bits&=~DECNEG;                   // clear the sign
3252   res->bits|=sign;                      // set from rhs
3253   return res;
3254   } // decNumberCopySign
3255 
3256 /* ------------------------------------------------------------------ */
3257 /* decNumberGetBCD -- get the coefficient in BCD8                     */
3258 /*   dn is the source decNumber                                       */
3259 /*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3260 /*     most-significant at offset 0                                   */
3261 /*   returns bcd                                                      */
3262 /*                                                                    */
3263 /* bcd must have at least dn->digits bytes.  No error is possible; if */
3264 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3265 /* ------------------------------------------------------------------ */
3266 uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
     /* [previous][next][first][last][top][bottom][index][help] */
3267   uByte *ub=bcd+dn->digits-1;      // -> lsd
3268   const Unit *up=dn->lsu;          // Unit pointer, -> lsu
3269 
3270 #if DECDPUN==1                   // trivial simple copy
3271     for (; ub>=bcd; ub--, up++) *ub=*up;
3272 #else                            // chopping needed
3273     uInt u=*up;                    // work
3274     uInt cut=DECDPUN;              // downcounter through unit
3275     for (; ub>=bcd; ub--) {
3276       *ub=(uByte)(u%10);           // [*6554 trick inhibits, here]
3277       u=u/10;
3278       cut--;
3279       if (cut>0) continue;         // more in this unit
3280       up++;
3281       u=*up;
3282       cut=DECDPUN;
3283       }
3284 #endif
3285   return bcd;
3286   } // decNumberGetBCD
3287 
3288 /* ------------------------------------------------------------------ */
3289 /* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3290 /*   dn is the target decNumber                                       */
3291 /*   bcd is the uInt array that will source n BCD bytes, most-        */
3292 /*     significant at offset 0                                        */
3293 /*   n is the number of digits in the source BCD array (bcd)          */
3294 /*   returns dn                                                       */
3295 /*                                                                    */
3296 /* dn must have space for at least n digits.  No error is possible;   */
3297 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3298 /* and bcd[0] zero.                                                   */
3299 /* ------------------------------------------------------------------ */
3300 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
     /* [previous][next][first][last][top][bottom][index][help] */
3301   Unit *up=dn->lsu+D2U(dn->digits)-1;   // -> msu [target pointer]
3302   const uByte *ub=bcd;                  // -> source msd
3303 
3304 #if DECDPUN==1                        // trivial simple copy
3305     for (; ub<bcd+n; ub++, up--) *up=*ub;
3306 #else                                 // some assembly needed
3307     // calculate how many digits in msu, and hence first cut
3308     Int cut=MSUDIGITS(n);               // [faster than remainder]
3309     for (;up>=dn->lsu; up--) {          // each Unit from msu
3310       *up=0;                            // will take <=DECDPUN digits
3311       for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3312       cut=DECDPUN;                      // next Unit has all digits
3313       }
3314 #endif
3315   dn->digits=n;                         // set digit count
3316   return dn;
3317   } // decNumberSetBCD
3318 
3319 /* ------------------------------------------------------------------ */
3320 /* decNumberIsNormal -- test normality of a decNumber                 */
3321 /*   dn is the decNumber to test                                      */
3322 /*   set is the context to use for Emin                               */
3323 /*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3324 /* ------------------------------------------------------------------ */
3325 Int decNumberIsNormal(const decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
3326   Int ae;                               // adjusted exponent
3327 
3328   if (decNumberIsSpecial(dn)) return 0; // not finite
3329   if (decNumberIsZero(dn)) return 0;    // not non-zero
3330 
3331   ae=dn->exponent+dn->digits-1;         // adjusted exponent
3332   if (ae<set->emin) return 0;           // is subnormal
3333   return 1;
3334   } // decNumberIsNormal
3335 
3336 /* ------------------------------------------------------------------ */
3337 /* decNumberIsSubnormal -- test subnormality of a decNumber           */
3338 /*   dn is the decNumber to test                                      */
3339 /*   set is the context to use for Emin                               */
3340 /*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3341 /* ------------------------------------------------------------------ */
3342 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
3343   Int ae;                               // adjusted exponent
3344 
3345   if (decNumberIsSpecial(dn)) return 0; // not finite
3346   if (decNumberIsZero(dn)) return 0;    // not non-zero
3347 
3348   ae=dn->exponent+dn->digits-1;         // adjusted exponent
3349   if (ae<set->emin) return 1;           // is subnormal
3350   return 0;
3351   } // decNumberIsSubnormal
3352 
3353 /* ------------------------------------------------------------------ */
3354 /* decNumberTrim -- remove insignificant zeros                        */
3355 /*                                                                    */
3356 /*   dn is the number to trim                                         */
3357 /*   returns dn                                                       */
3358 /*                                                                    */
3359 /* All fields are updated as required.  This is a utility operation,  */
3360 /* so special values are unchanged and no error is possible.  The     */
3361 /* zeros are removed unconditionally.                                 */
3362 /* ------------------------------------------------------------------ */
3363 decNumber * decNumberTrim(decNumber *dn) {
     /* [previous][next][first][last][top][bottom][index][help] */
3364   Int  dropped;                    // work
3365   decContext set;                  // ..
3366   decContextDefault(&set, DEC_INIT_BASE);    // clamp=0
3367   return decTrim(dn, &set, 0, 1, &dropped);
3368   } // decNumberTrim
3369 
3370 /* ------------------------------------------------------------------ */
3371 /* decNumberVersion -- return the name and version of this module     */
3372 /*                                                                    */
3373 /* No error is possible.                                              */
3374 /* ------------------------------------------------------------------ */
3375 const char * decNumberVersion(void) {
     /* [previous][next][first][last][top][bottom][index][help] */
3376   return DECVERSION;
3377   } // decNumberVersion
3378 
3379 /* ------------------------------------------------------------------ */
3380 /* decNumberZero -- set a number to 0                                 */
3381 /*                                                                    */
3382 /*   dn is the number to set, with space for one digit                */
3383 /*   returns dn                                                       */
3384 /*                                                                    */
3385 /* No error is possible.                                              */
3386 /* ------------------------------------------------------------------ */
3387 // Memset is not used as it is much slower in some environments.
3388 decNumber * decNumberZero(decNumber *dn) {
     /* [previous][next][first][last][top][bottom][index][help] */
3389 
3390   dn->bits=0;
3391   dn->exponent=0;
3392   dn->digits=1;
3393   dn->lsu[0]=0;
3394   return dn;
3395   } // decNumberZero
3396 
3397 /* ================================================================== */
3398 /* Local routines                                                     */
3399 /* ================================================================== */
3400 
3401 /* ------------------------------------------------------------------ */
3402 /* decToString -- lay out a number into a string                      */
3403 /*                                                                    */
3404 /*   dn     is the number to lay out                                  */
3405 /*   string is where to lay out the number                            */
3406 /*   eng    is 1 if Engineering, 0 if Scientific                      */
3407 /*                                                                    */
3408 /* string must be at least dn->digits+14 characters long              */
3409 /* No error is possible.                                              */
3410 /*                                                                    */
3411 /* Note that this routine can generate a -0 or 0.000.  These are      */
3412 /* never generated in subset to-number or arithmetic, but can occur   */
3413 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3414 /* ------------------------------------------------------------------ */
3415 static void decToString(const decNumber *dn, char *string, Flag eng) {
     /* [previous][next][first][last][top][bottom][index][help] */
3416   Int exp=dn->exponent;       // local copy
3417   Int e;                      // E-part value
3418   Int pre;                    // digits before the '.'
3419   Int cut;                    // for counting digits in a Unit
3420   char *c=string;             // work [output pointer]
3421   const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]
3422   uInt u, pow;                // work
3423 
3424   if (decNumberIsNegative(dn)) {   // Negatives get a minus
3425     *c='-';
3426     c++;
3427     }
3428   if (dn->bits&DECSPECIAL) {       // Is a special value
3429     if (decNumberIsInfinite(dn)) {
3430       strcpy(c,   "Inf");
3431       strcpy(c+3, "inity");
3432       return;}
3433     // a NaN
3434     if (dn->bits&DECSNAN) {        // signalling NaN
3435       *c='s';
3436       c++;
3437       }
3438     strcpy(c, "NaN");
3439     c+=3;                          // step past
3440     // if not a clean non-zero coefficient, that's all there is in a
3441     // NaN string
3442     if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3443     // [drop through to add integer]
3444     }
3445 
3446   // calculate how many digits in msu, and hence first cut
3447   cut=MSUDIGITS(dn->digits);       // [faster than remainder]
3448   cut--;                           // power of ten for digit
3449 
3450   if (exp==0) {                    // simple integer [common fastpath]
3451     for (;up>=dn->lsu; up--) {     // each Unit from msu
3452       u=*up;                       // contains DECDPUN digits to lay out
3453       for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3454       cut=DECDPUN-1;               // next Unit has all digits
3455       }
3456     *c='\0';                       // terminate the string
3457     return;}
3458 
3459   /* non-0 exponent -- assume plain form */
3460   pre=dn->digits+exp;              // digits before '.'
3461   e=0;                             // no E
3462   if ((exp>0) || (pre<-5)) {       // need exponential form
3463     e=exp+dn->digits-1;            // calculate E value
3464     pre=1;                         // assume one digit before '.'
3465     if (eng && (e!=0)) {           // engineering: may need to adjust
3466       Int adj;                     // adjustment
3467       // The C remainder operator is undefined for negative numbers, so
3468       // a positive remainder calculation must be used here
3469       if (e<0) {
3470         adj=(-e)%3;
3471         if (adj!=0) adj=3-adj;
3472         }
3473        else { // e>0
3474         adj=e%3;
3475         }
3476       e=e-adj;
3477       // if dealing with zero still produce an exponent which is a
3478       // multiple of three, as expected, but there will only be the
3479       // one zero before the E, still.  Otherwise note the padding.
3480       if (!ISZERO(dn)) pre+=adj;
3481        else {  // is zero
3482         if (adj!=0) {              // 0.00Esnn needed
3483           e=e+3;
3484           pre=-(2-adj);
3485           }
3486         } // zero
3487       } // eng
3488     } // need exponent
3489 
3490   /* lay out the digits of the coefficient, adding 0s and . as needed */
3491   u=*up;
3492   if (pre>0) {                     // xxx.xxx or xx00 (engineering) form
3493     Int n=pre;
3494     for (; pre>0; pre--, c++, cut--) {
3495       if (cut<0) {                 // need new Unit
3496         if (up==dn->lsu) break;    // out of input digits (pre>digits)
3497         up--;
3498         cut=DECDPUN-1;
3499         u=*up;
3500         }
3501       TODIGIT(u, cut, c, pow);
3502       }
3503     if (n<dn->digits) {            // more to come, after '.'
3504       *c='.'; c++;
3505       for (;; c++, cut--) {
3506         if (cut<0) {               // need new Unit
3507           if (up==dn->lsu) break;  // out of input digits
3508           up--;
3509           cut=DECDPUN-1;
3510           u=*up;
3511           }
3512         TODIGIT(u, cut, c, pow);
3513         }
3514       }
3515      else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed
3516     }
3517    else {                          // 0.xxx or 0.000xxx form
3518     *c='0'; c++;
3519     *c='.'; c++;
3520     for (; pre<0; pre++, c++) *c='0';   // add any 0's after '.'
3521     for (; ; c++, cut--) {
3522       if (cut<0) {                 // need new Unit
3523         if (up==dn->lsu) break;    // out of input digits
3524         up--;
3525         cut=DECDPUN-1;
3526         u=*up;
3527         }
3528       TODIGIT(u, cut, c, pow);
3529       }
3530     }
3531 
3532   /* Finally add the E-part, if needed.  It will never be 0, has a
3533      base maximum and minimum of +999999999 through -999999999, but
3534      could range down to -1999999998 for anormal numbers */
3535   if (e!=0) {
3536     Flag had=0;               // 1=had non-zero
3537     *c='E'; c++;
3538     *c='+'; c++;              // assume positive
3539     u=e;                      // ..
3540     if (e<0) {
3541       *(c-1)='-';             // oops, need -
3542       u=-e;                   // uInt, please
3543       }
3544     // lay out the exponent [_itoa or equivalent is not ANSI C]
3545     for (cut=9; cut>=0; cut--) {
3546       TODIGIT(u, cut, c, pow);
3547       if (*c=='0' && !had) continue;    // skip leading zeros
3548       had=1;                            // had non-0
3549       c++;                              // step for next
3550       } // cut
3551     }
3552   *c='\0';          // terminate the string (all paths)
3553   return;
3554   } // decToString
3555 
3556 /* ------------------------------------------------------------------ */
3557 /* decAddOp -- add/subtract operation                                 */
3558 /*                                                                    */
3559 /*   This computes C = A + B                                          */
3560 /*                                                                    */
3561 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3562 /*   lhs is A                                                         */
3563 /*   rhs is B                                                         */
3564 /*   set is the context                                               */
3565 /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3566 /*   status accumulates status for the caller                         */
3567 /*                                                                    */
3568 /* C must have space for set->digits digits.                          */
3569 /* Inexact in status must be 0 for correct Exact zero sign in result  */
3570 /* ------------------------------------------------------------------ */
3571 /* If possible, the coefficient is calculated directly into C.        */
3572 /* However, if:                                                       */
3573 /*   -- a digits+1 calculation is needed because the numbers are      */
3574 /*      unaligned and span more than set->digits digits               */
3575 /*   -- a carry to digits+1 digits looks possible                     */
3576 /*   -- C is the same as A or B, and the result would destructively   */
3577 /*      overlap the A or B coefficient                                */
3578 /* then the result must be calculated into a temporary buffer.  In    */
3579 /* this case a local (stack) buffer is used if possible, and only if  */
3580 /* too long for that does malloc become the final resort.             */
3581 /*                                                                    */
3582 /* Misalignment is handled as follows:                                */
3583 /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3584 /*   BPad: Apply the padding by a combination of shifting (whole      */
3585 /*         units) and multiplication (part units).                    */
3586 /*                                                                    */
3587 /* Addition, especially x=x+1, is speed-critical.                     */
3588 /* The static buffer is larger than might be expected to allow for    */
3589 /* calls from higher-level functions (notable exp).                   */
3590 /* ------------------------------------------------------------------ */
3591 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
3592                             const decNumber *rhs, decContext *set,
3593                             uByte negate, uInt *status) {
3594 #if DECSUBSET
3595   decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
3596   decNumber *allocrhs=NULL;        // .., rhs
3597 #endif
3598   decNumber dtiny;                 // lhs, adjusted to avoid a huge shift
3599   Int   rhsshift;                  // working shift (in Units)
3600   Int   maxdigits;                 // longest logical length
3601   Int   mult;                      // multiplier
3602   Int   residue;                   // rounding accumulator
3603   uByte bits;                      // result bits
3604   Flag  diffsign;                  // non-0 if arguments have different sign
3605   Unit  *acc;                      // accumulator for result
3606   Unit  accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many
3607                                    // allocations when called from
3608                                    // other operations, notable exp]
3609   Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
3610   Int   reqdigits=set->digits;     // local copy; requested DIGITS
3611   Int   padding;                   // work
3612 
3613   do {                             // protect allocated storage
3614 #if DECSUBSET
3615     if (!set->extended) {
3616       // reduce operands and set lostDigits status, as needed
3617       if (lhs->digits>reqdigits) {
3618         alloclhs=decRoundOperand(lhs, set, status);
3619         if (alloclhs==NULL) break;
3620         lhs=alloclhs;
3621         }
3622       if (rhs->digits>reqdigits) {
3623         allocrhs=decRoundOperand(rhs, set, status);
3624         if (allocrhs==NULL) break;
3625         rhs=allocrhs;
3626         }
3627       }
3628 #endif
3629     // [following code does not require input rounding]
3630 
3631     // note whether signs differ [used all paths]
3632     diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3633 
3634     // handle infinities and NaNs
3635     if (SPECIALARGS) {                  // a special bit set
3636       if (SPECIALARGS & (DECSNAN | DECNAN))  // a NaN
3637         decNaNs(res, lhs, rhs, set, status);
3638        else { // one or two infinities
3639         if (decNumberIsInfinite(lhs)) { // LHS is infinity
3640           // two infinities with different signs is invalid
3641           if (decNumberIsInfinite(rhs) && diffsign) {
3642             *status|=DEC_Invalid_operation;
3643             break;
3644             }
3645           bits=lhs->bits & DECNEG;      // get sign from LHS
3646           }
3647          else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity
3648         bits|=DECINF;
3649         decNumberZero(res);
3650         res->bits=bits;                 // set +/- infinity
3651         } // an infinity
3652       break;
3653       }
3654 
3655     // Quick exit for add 0s; return the non-0, modified as need be
3656     if (ISZERO(lhs)) {
3657       Int adjust;                       // work
3658       Int lexp=lhs->exponent;           // save in case LHS==RES
3659       bits=lhs->bits;                   // ..
3660       (void)bits;
3661       residue=0;                        // clear accumulator
3662       decCopyFit(res, rhs, set, &residue, status); // copy (as needed)
3663       res->bits^=negate;                // flip if rhs was negated
3664 #if DECSUBSET
3665       if (set->extended) {              // exponents on zeros count
3666 #endif
3667         // exponent will be the lower of the two
3668         adjust=lexp-res->exponent;      // adjustment needed [if -ve]
3669         if (ISZERO(res)) {              // both 0: special IEEE 754 rules
3670           if (adjust<0) res->exponent=lexp;  // set exponent
3671           // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0
3672           if (diffsign) {
3673             if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3674              else res->bits=DECNEG;     // preserve 0 sign
3675             }
3676           }
3677          else { // non-0 res
3678           if (adjust<0) {     // 0-padding needed
3679             if ((res->digits-adjust)>set->digits) {
3680               adjust=res->digits-set->digits;     // to fit exactly
3681               *status|=DEC_Rounded;               // [but exact]
3682               }
3683             res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3684             res->exponent+=adjust;                // set the exponent.
3685             }
3686           } // non-0 res
3687 #if DECSUBSET
3688         } // extended
3689 #endif
3690       decFinish(res, set, &residue, status);      // clean and finalize
3691       break;}
3692 
3693     if (ISZERO(rhs)) {                  // [lhs is non-zero]
3694       Int adjust;                       // work
3695       Int rexp=rhs->exponent;           // save in case RHS==RES
3696       bits=rhs->bits;                   // be clean
3697       (void)bits;
3698       residue=0;                        // clear accumulator
3699       decCopyFit(res, lhs, set, &residue, status); // copy (as needed)
3700 #if DECSUBSET
3701       if (set->extended) {              // exponents on zeros count
3702 #endif
3703         // exponent will be the lower of the two
3704         // [0-0 case handled above]
3705         adjust=rexp-res->exponent;      // adjustment needed [if -ve]
3706         if (adjust<0) {     // 0-padding needed
3707           if ((res->digits-adjust)>set->digits) {
3708             adjust=res->digits-set->digits;     // to fit exactly
3709             *status|=DEC_Rounded;               // [but exact]
3710             }
3711           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3712           res->exponent+=adjust;                // set the exponent.
3713           }
3714 #if DECSUBSET
3715         } // extended
3716 #endif
3717       decFinish(res, set, &residue, status);      // clean and finalize
3718       break;}
3719 
3720     // [NB: both fastpath and mainpath code below assume these cases
3721     // (notably 0-0) have already been handled]
3722 
3723     // calculate the padding needed to align the operands
3724     padding=rhs->exponent-lhs->exponent;
3725 
3726     // Fastpath cases where the numbers are aligned and normal, the RHS
3727     // is all in one unit, no operand rounding is needed, and no carry,
3728     // lengthening, or borrow is needed
3729     if (padding==0
3730         && rhs->digits<=DECDPUN
3731         && rhs->exponent>=set->emin     // [some normals drop through]
3732         && rhs->exponent<=set->emax-set->digits+1 // [could clamp]
3733         && rhs->digits<=reqdigits
3734         && lhs->digits<=reqdigits) {
3735       Int partial=*lhs->lsu;
3736       if (!diffsign) {                  // adding
3737         partial+=*rhs->lsu;
3738         if ((partial<=DECDPUNMAX)       // result fits in unit
3739          && (lhs->digits>=DECDPUN ||    // .. and no digits-count change
3740              partial<(Int)powers[lhs->digits])) { // ..
3741           if (res!=lhs) decNumberCopy(res, lhs);  // not in place
3742           *res->lsu=(Unit)partial;      // [copy could have overwritten RHS]
3743           break;
3744           }
3745         // else drop out for careful add
3746         }
3747        else {                           // signs differ
3748         partial-=*rhs->lsu;
3749         if (partial>0) { // no borrow needed, and non-0 result
3750           if (res!=lhs) decNumberCopy(res, lhs);  // not in place
3751           *res->lsu=(Unit)partial;
3752           // this could have reduced digits [but result>0]
3753           res->digits=decGetDigits(res->lsu, D2U(res->digits));
3754           break;
3755           }
3756         // else drop out for careful subtract
3757         }
3758       }
3759 
3760     // Now align (pad) the lhs or rhs so they can be added or
3761     // subtracted, as necessary.
3762     rhsshift=0;               // rhs shift to left (padding) in Units
3763     bits=lhs->bits;           // assume sign is that of LHS
3764     mult=1;                   // likely multiplier
3765 
3766     // [if padding==0 the operands are aligned; no padding is needed]
3767     if (padding!=0) {
3768       // some padding needed; always pad the RHS, as any required
3769       // padding can then be effected by a simple combination of
3770       // shifts and a multiply
3771       Int exponent;                     // new exponent of LHS (if adjusted)
3772       if (padding<0) {                  // LHS needs the padding
3773         const decNumber *t;
3774         padding=-padding;               // will be +ve
3775         bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS
3776         t=lhs; lhs=rhs; rhs=t;
3777         }
3778 
3779       exponent = rhs->exponent-1;
3780       exponent += (rhs->digits>reqdigits) ? 0 : rhs->digits-reqdigits-1;
3781       if (lhs->digits+lhs->exponent-1 < exponent) {
3782         // Adjust lhs and padding to avoid huge shifts.
3783         dtiny.bits=lhs->bits;
3784         dtiny.exponent=exponent;
3785         dtiny.digits=1;
3786         dtiny.lsu[0]=1;
3787         lhs=&dtiny;
3788         padding=rhs->exponent-exponent;
3789         // Fall through to add/subtract the modified lhs.
3790         }
3791 
3792       // LHS digits may affect result
3793       rhsshift=D2U(padding+1)-1;        // this much by Unit shift ..
3794       mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication
3795       } // padding needed
3796 
3797     if (diffsign) mult=-mult;           // signs differ
3798 
3799     // determine the longer operand
3800     maxdigits=rhs->digits+padding;      // virtual length of RHS
3801     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
3802 
3803     // Decide on the result buffer to use; if possible place directly
3804     // into result.
3805     acc=res->lsu;                       // assume add direct to result
3806     // If destructive overlap, or the number is too long, or a carry or
3807     // borrow to DIGITS+1 might be possible, a buffer must be used.
3808     // [Might be worth more sophisticated tests when maxdigits==reqdigits]
3809     if ((maxdigits>=reqdigits)          // is, or could be, too large
3810      || (res==rhs && rhsshift>0)) {     // destructive overlap
3811       // buffer needed, choose it; units for maxdigits digits will be
3812       // needed, +1 Unit for carry or borrow
3813       Int need=D2U(maxdigits)+1;
3814       acc=accbuff;                      // assume use local buffer
3815       if (need*sizeof(Unit)>sizeof(accbuff)) {
3816         // printf("malloc add %ld %ld\n", need, sizeof(accbuff));
3817         allocacc=(Unit *)malloc(need*sizeof(Unit));
3818         if (allocacc==NULL) {           // hopeless -- abandon
3819           *status|=DEC_Insufficient_storage;
3820           break;}
3821         acc=allocacc;
3822         }
3823       }
3824 
3825     res->bits=(uByte)(bits&DECNEG);     // it's now safe to overwrite..
3826     res->exponent=lhs->exponent;        // .. operands (even if aliased)
3827 
3828     // add [A+B*m] or subtract [A+B*(-m)]
3829     res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
3830                               rhs->lsu, D2U(rhs->digits),
3831                               rhsshift, acc, mult)
3832                *DECDPUN;           // [units -> digits]
3833     if (res->digits<0) {           // borrowed...
3834       res->digits=-res->digits;
3835       res->bits^=DECNEG;           // flip the sign
3836       }
3837 
3838     // If a buffer was used the result must be copied back, possibly
3839     // shortening.  (If no buffer was used then the result must have
3840     // fit, so can't need rounding and residue must be 0.)
3841     residue=0;                     // clear accumulator
3842     if (acc!=res->lsu) {
3843 #if DECSUBSET
3844       if (set->extended) {         // round from first significant digit
3845 #endif
3846         // remove leading zeros that were added due to rounding up to
3847         // integral Units -- before the test for rounding.
3848         if (res->digits>reqdigits)
3849           res->digits=decGetDigits(acc, D2U(res->digits));
3850         decSetCoeff(res, set, acc, res->digits, &residue, status);
3851 #if DECSUBSET
3852         }
3853        else { // subset arithmetic rounds from original significant digit
3854         // May have an underestimate.  This only occurs when both
3855         // numbers fit in DECDPUN digits and are padding with a
3856         // negative multiple (-10, -100...) and the top digit(s) become
3857         // 0.  (This only matters when using X3.274 rules where the
3858         // leading zero could be included in the rounding.)
3859         if (res->digits<maxdigits) {
3860           *(acc+D2U(res->digits))=0; // ensure leading 0 is there
3861           res->digits=maxdigits;
3862           }
3863          else {
3864           // remove leading zeros that added due to rounding up to
3865           // integral Units (but only those in excess of the original
3866           // maxdigits length, unless extended) before test for rounding.
3867           if (res->digits>reqdigits) {
3868             res->digits=decGetDigits(acc, D2U(res->digits));
3869             if (res->digits<maxdigits) res->digits=maxdigits;
3870             }
3871           }
3872         decSetCoeff(res, set, acc, res->digits, &residue, status);
3873         // Now apply rounding if needed before removing leading zeros.
3874         // This is safe because subnormals are not a possibility
3875         if (residue!=0) {
3876           decApplyRound(res, set, residue, status);
3877           residue=0;                 // did what needed to be done
3878           }
3879         } // subset
3880 #endif
3881       } // used buffer
3882 
3883     // strip leading zeros [these were left on in case of subset subtract]
3884     res->digits=decGetDigits(res->lsu, D2U(res->digits));
3885 
3886     // apply checks and rounding
3887     decFinish(res, set, &residue, status);
3888 
3889     // "When the sum of two operands with opposite signs is exactly
3890     // zero, the sign of that sum shall be '+' in all rounding modes
3891     // except round toward -Infinity, in which mode that sign shall be
3892     // '-'."  [Subset zeros also never have '-', set by decFinish.]
3893     if (ISZERO(res) && diffsign
3894 #if DECSUBSET
3895      && set->extended
3896 #endif
3897      && (*status&DEC_Inexact)==0) {
3898       if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   // sign -
3899                                   else res->bits&=~DECNEG;  // sign +
3900       }
3901     } while(0);                              // end protected
3902 
3903   if (allocacc!=NULL) FREE(allocacc);        // drop any storage used
3904 #if DECSUBSET
3905   if (allocrhs!=NULL) FREE(allocrhs);        // ..
3906   if (alloclhs!=NULL) FREE(alloclhs);        // ..
3907 #endif
3908   return res;
3909   } // decAddOp
3910 
3911 /* ------------------------------------------------------------------ */
3912 /* decDivideOp -- division operation                                  */
3913 /*                                                                    */
3914 /*  This routine performs the calculations for all four division      */
3915 /*  operators (divide, divideInteger, remainder, remainderNear).      */
3916 /*                                                                    */
3917 /*  C=A op B                                                          */
3918 /*                                                                    */
3919 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
3920 /*   lhs is A                                                         */
3921 /*   rhs is B                                                         */
3922 /*   set is the context                                               */
3923 /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
3924 /*   status is the usual accumulator                                  */
3925 /*                                                                    */
3926 /* C must have space for set->digits digits.                          */
3927 /*                                                                    */
3928 /* ------------------------------------------------------------------ */
3929 /*   The underlying algorithm of this routine is the same as in the   */
3930 /*   1981 S/370 implementation, that is, non-restoring long division  */
3931 /*   with bi-unit (rather than bi-digit) estimation for each unit     */
3932 /*   multiplier.  In this pseudocode overview, complications for the  */
3933 /*   Remainder operators and division residues for exact rounding are */
3934 /*   omitted for clarity.                                             */
3935 /*                                                                    */
3936 /*     Prepare operands and handle special values                     */
3937 /*     Test for x/0 and then 0/x                                      */
3938 /*     Exp =Exp1 - Exp2                                               */
3939 /*     Exp =Exp +len(var1) -len(var2)                                 */
3940 /*     Sign=Sign1 * Sign2                                             */
3941 /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
3942 /*     Pad Var2 to same length as Var1                                */
3943 /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
3944 /*     have=0                                                         */
3945 /*     Do until (have=digits+1 OR residue=0)                          */
3946 /*       if exp<0 then if integer divide/residue then leave           */
3947 /*       this_unit=0                                                  */
3948 /*       Do forever                                                   */
3949 /*          compare numbers                                           */
3950 /*          if <0 then leave inner_loop                               */
3951 /*          if =0 then (* quick exit without subtract *) do           */
3952 /*             this_unit=this_unit+1; output this_unit                */
3953 /*             leave outer_loop; end                                  */
3954 /*          Compare lengths of numbers (mantissa):                    */
3955 /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
3956 /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
3957 /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
3958 /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
3959 /*          if mult=0 then mult=1                                     */
3960 /*          this_unit=this_unit+mult                                  */
3961 /*          subtract                                                  */
3962 /*          end inner_loop                                            */
3963 /*        if have\=0 | this_unit\=0 then do                           */
3964 /*          output this_unit                                          */
3965 /*          have=have+1; end                                          */
3966 /*        var2=var2/10                                                */
3967 /*        exp=exp-1                                                   */
3968 /*        end outer_loop                                              */
3969 /*     exp=exp+1   -- set the proper exponent                         */
3970 /*     if have=0 then generate answer=0                               */
3971 /*     Return (Result is defined by Var1)                             */
3972 /*                                                                    */
3973 /* ------------------------------------------------------------------ */
3974 /* Two working buffers are needed during the division; one (digits+   */
3975 /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
3976 /* long subtractions.  These are acc and var1 respectively.           */
3977 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
3978 /* The static buffers may be larger than might be expected to allow   */
3979 /* for calls from higher-level funtions (notable exp).                */
3980 /* ------------------------------------------------------------------ */
3981 static decNumber * decDivideOp(decNumber *res,
     /* [previous][next][first][last][top][bottom][index][help] */
3982                                const decNumber *lhs, const decNumber *rhs,
3983                                decContext *set, Flag op, uInt *status) {
3984 #if DECSUBSET
3985   decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
3986   decNumber *allocrhs=NULL;        // .., rhs
3987 #endif
3988   Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer
3989   Unit  *acc=accbuff;              // -> accumulator array for result
3990   Unit  *allocacc=NULL;            // -> allocated buffer, iff allocated
3991   Unit  *accnext;                  // -> where next digit will go
3992   Int   acclength;                 // length of acc needed [Units]
3993   Int   accunits;                  // count of units accumulated
3994   Int   accdigits;                 // count of digits accumulated
3995 
3996   Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  // buffer for var1
3997   Unit  *var1=varbuff;             // -> var1 array for long subtraction
3998   Unit  *varalloc=NULL;            // -> allocated buffer, iff used
3999   Unit  *msu1;                     // -> msu of var1
4000 
4001   const Unit *var2;                // -> var2 array
4002   const Unit *msu2;                // -> msu of var2
4003   Int   msu2plus;                  // msu2 plus one [does not vary]
4004   eInt  msu2pair;                  // msu2 pair plus one [does not vary]
4005 
4006   Int   var1units, var2units;      // actual lengths
4007   Int   var2ulen;                  // logical length (units)
4008   Int   var1initpad=0;             // var1 initial padding (digits)
4009   Int   maxdigits;                 // longest LHS or required acc length
4010   Int   mult;                      // multiplier for subtraction
4011   Unit  thisunit;                  // current unit being accumulated
4012   Int   residue;                   // for rounding
4013   Int   reqdigits=set->digits;     // requested DIGITS
4014   Int   exponent;                  // working exponent
4015   Int   maxexponent=0;             // DIVIDE maximum exponent if unrounded
4016   uByte bits;                      // working sign
4017   Unit  *target;                   // work
4018   const Unit *source;              // ..
4019   uInt  const *pow;                // ..
4020   Int   shift, cut;                // ..
4021 #if DECSUBSET
4022   Int   dropped;                   // work
4023 #endif
4024 
4025   do {                             // protect allocated storage
4026 #if DECSUBSET
4027     if (!set->extended) {
4028       // reduce operands and set lostDigits status, as needed
4029       if (lhs->digits>reqdigits) {
4030         alloclhs=decRoundOperand(lhs, set, status);
4031         if (alloclhs==NULL) break;
4032         lhs=alloclhs;
4033         }
4034       if (rhs->digits>reqdigits) {
4035         allocrhs=decRoundOperand(rhs, set, status);
4036         if (allocrhs==NULL) break;
4037         rhs=allocrhs;
4038         }
4039       }
4040 #endif
4041     // [following code does not require input rounding]
4042 
4043     bits=(lhs->bits^rhs->bits)&DECNEG;  // assumed sign for divisions
4044     (void)bits;
4045     // handle infinities and NaNs
4046     if (SPECIALARGS) {                  // a special bit set
4047       if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
4048         decNaNs(res, lhs, rhs, set, status);
4049         break;
4050         }
4051       // one or two infinities
4052       if (decNumberIsInfinite(lhs)) {   // LHS (dividend) is infinite
4053         if (decNumberIsInfinite(rhs) || // two infinities are invalid ..
4054             op & (REMAINDER | REMNEAR)) { // as is remainder of infinity
4055           *status|=DEC_Invalid_operation;
4056           break;
4057           }
4058         // [Note that infinity/0 raises no exceptions]
4059         decNumberZero(res);
4060         res->bits=bits|DECINF;          // set +/- infinity
4061         break;
4062         }
4063        else {                           // RHS (divisor) is infinite
4064         residue=0;
4065         if (op&(REMAINDER|REMNEAR)) {
4066           // result is [finished clone of] lhs
4067           decCopyFit(res, lhs, set, &residue, status);
4068           }
4069          else {  // a division
4070           decNumberZero(res);
4071           res->bits=bits;               // set +/- zero
4072           // for DIVIDEINT the exponent is always 0.  For DIVIDE, result
4073           // is a 0 with infinitely negative exponent, clamped to minimum
4074           if (op&DIVIDE) {
4075             res->exponent=set->emin-set->digits+1;
4076             *status|=DEC_Clamped;
4077             }
4078           }
4079         decFinish(res, set, &residue, status);
4080         break;
4081         }
4082       }
4083 
4084     // handle 0 rhs (x/0)
4085     if (ISZERO(rhs)) {                  // x/0 is always exceptional
4086       if (ISZERO(lhs)) {
4087         decNumberZero(res);             // [after lhs test]
4088         *status|=DEC_Division_undefined;// 0/0 will become NaN
4089         }
4090        else {
4091         decNumberZero(res);
4092         if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4093          else {
4094           *status|=DEC_Division_by_zero; // x/0
4095           res->bits=bits|DECINF;         // .. is +/- Infinity
4096           }
4097         }
4098       break;}
4099 
4100     // handle 0 lhs (0/x)
4101     if (ISZERO(lhs)) {                  // 0/x [x!=0]
4102 #if DECSUBSET
4103       if (!set->extended) decNumberZero(res);
4104        else {
4105 #endif
4106         if (op&DIVIDE) {
4107           exponent=lhs->exponent-rhs->exponent; // ideal exponent
4108           decNumberCopy(res, lhs);      // [zeros always fit]
4109           res->bits=bits;               // sign as computed
4110           res->exponent=exponent;       // exponent, too
4111           }
4112          else if (op&DIVIDEINT) {
4113           decNumberZero(res);           // integer 0
4114           res->bits=bits;               // sign as computed
4115           }
4116          else {                         // a remainder
4117           exponent=rhs->exponent;       // [save in case overwrite]
4118           decNumberCopy(res, lhs);      // [zeros always fit]
4119           if (exponent<res->exponent) res->exponent=exponent; // use lower
4120           }
4121         residue=0;
4122         decFinalize(res, set, &residue, status);   // check exponent
4123 #if DECSUBSET
4124         }
4125 #endif
4126       break;}
4127 
4128     // Precalculate exponent.  This starts off adjusted (and hence fits
4129     // in 31 bits) and becomes the usual unadjusted exponent as the
4130     // division proceeds.  The order of evaluation is important, here,
4131     // to avoid wrap.
4132     exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4133 
4134     // If the working exponent is -ve, then some quick exits are
4135     // possible because the quotient is known to be <1
4136     // [for REMNEAR, it needs to be < -1, as -0.5 could need work]
4137     if (exponent<0 && !(op==DIVIDE)) {
4138       if (op&DIVIDEINT) {
4139         decNumberZero(res);                  // integer part is 0
4140 #if DECSUBSET
4141         if (set->extended)
4142 #endif
4143           res->bits=bits;                    // set +/- zero
4144         break;}
4145       // fastpath remainders so long as the lhs has the smaller
4146       // (or equal) exponent
4147       if (lhs->exponent<=rhs->exponent) {
4148         if (op&REMAINDER || exponent<-1) {
4149           // It is REMAINDER or safe REMNEAR; result is [finished
4150           // clone of] lhs  (r = x - 0*y)
4151           residue=0;
4152           decCopyFit(res, lhs, set, &residue, status);
4153           decFinish(res, set, &residue, status);
4154           break;
4155           }
4156         // [unsafe REMNEAR drops through]
4157         }
4158       } // fastpaths
4159 
4160     /* Long (slow) division is needed; roll up the sleeves... */
4161 
4162     // The accumulator will hold the quotient of the division.
4163     // If it needs to be too long for stack storage, then allocate.
4164     acclength=D2U(reqdigits+DECDPUN);   // in Units
4165     if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4166       // printf("malloc dvacc %ld units\n", acclength);
4167       allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4168       if (allocacc==NULL) {             // hopeless -- abandon
4169         *status|=DEC_Insufficient_storage;
4170         break;}
4171       acc=allocacc;                     // use the allocated space
4172       }
4173 
4174     // var1 is the padded LHS ready for subtractions.
4175     // If it needs to be too long for stack storage, then allocate.
4176     // The maximum units needed for var1 (long subtraction) is:
4177     // Enough for
4178     //     (rhs->digits+reqdigits-1) -- to allow full slide to right
4179     // or  (lhs->digits)             -- to allow for long lhs
4180     // whichever is larger
4181     //   +1                -- for rounding of slide to right
4182     //   +1                -- for leading 0s
4183     //   +1                -- for pre-adjust if a remainder or DIVIDEINT
4184     // [Note: unused units do not participate in decUnitAddSub data]
4185     maxdigits=rhs->digits+reqdigits-1;
4186     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4187     var1units=D2U(maxdigits)+2;
4188     // allocate a guard unit above msu1 for REMAINDERNEAR
4189     if (!(op&DIVIDE)) var1units++;
4190     if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4191       // printf("malloc dvvar %ld units\n", var1units+1);
4192       varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4193       if (varalloc==NULL) {             // hopeless -- abandon
4194         *status|=DEC_Insufficient_storage;
4195         break;}
4196       var1=varalloc;                    // use the allocated space
4197       }
4198 
4199     // Extend the lhs and rhs to full long subtraction length.  The lhs
4200     // is truly extended into the var1 buffer, with 0 padding, so a
4201     // subtract in place is always possible.  The rhs (var2) has
4202     // virtual padding (implemented by decUnitAddSub).
4203     // One guard unit was allocated above msu1 for rem=rem+rem in
4204     // REMAINDERNEAR.
4205     msu1=var1+var1units-1;              // msu of var1
4206     source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array
4207     for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4208     for (; target>=var1; target--) *target=0;
4209 
4210     // rhs (var2) is left-aligned with var1 at the start
4211     var2ulen=var1units;                 // rhs logical length (units)
4212     var2units=D2U(rhs->digits);         // rhs actual length (units)
4213     var2=rhs->lsu;                      // -> rhs array
4214     msu2=var2+var2units-1;              // -> msu of var2 [never changes]
4215     // now set up the variables which will be used for estimating the
4216     // multiplication factor.  If these variables are not exact, add
4217     // 1 to make sure that the multiplier is never overestimated.
4218     msu2plus=*msu2;                     // it's value ..
4219     if (var2units>1) msu2plus++;        // .. +1 if any more
4220     msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..
4221     if (var2units>1) {                  // .. [else treat 2nd as 0]
4222       msu2pair+=*(msu2-1);              // ..
4223       if (var2units>2) msu2pair++;      // .. +1 if any more
4224       }
4225 
4226     // The calculation is working in units, which may have leading zeros,
4227     // but the exponent was calculated on the assumption that they are
4228     // both left-aligned.  Adjust the exponent to compensate: add the
4229     // number of leading zeros in var1 msu and subtract those in var2 msu.
4230     // [This is actually done by counting the digits and negating, as
4231     // lead1=DECDPUN-digits1, and similarly for lead2.]
4232     for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4233     for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4234 
4235     // Now, if doing an integer divide or remainder, ensure that
4236     // the result will be Unit-aligned.  To do this, shift the var1
4237     // accumulator towards least if need be.  (It's much easier to
4238     // do this now than to reassemble the residue afterwards, if
4239     // doing a remainder.)  Also ensure the exponent is not negative.
4240     if (!(op&DIVIDE)) {
4241       Unit *u;                          // work
4242       // save the initial 'false' padding of var1, in digits
4243       var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4244       // Determine the shift to do.
4245       if (exponent<0) cut=-exponent;
4246        else cut=DECDPUN-exponent%DECDPUN;
4247       decShiftToLeast(var1, var1units, cut);
4248       exponent+=cut;                    // maintain numerical value
4249       var1initpad-=cut;                 // .. and reduce padding
4250       // clean any most-significant units which were just emptied
4251       for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4252       } // align
4253      else { // is DIVIDE
4254       maxexponent=lhs->exponent-rhs->exponent;    // save
4255       // optimization: if the first iteration will just produce 0,
4256       // preadjust to skip it [valid for DIVIDE only]
4257       if (*msu1<*msu2) {
4258         var2ulen--;                     // shift down
4259         exponent-=DECDPUN;              // update the exponent
4260         }
4261       }
4262 
4263     // ---- start the long-division loops ------------------------------
4264     accunits=0;                         // no units accumulated yet
4265     accdigits=0;                        // .. or digits
4266     accnext=acc+acclength-1;            // -> msu of acc [NB: allows digits+1]
4267     for (;;) {                          // outer forever loop
4268       thisunit=0;                       // current unit assumed 0
4269       // find the next unit
4270       for (;;) {                        // inner forever loop
4271         // strip leading zero units [from either pre-adjust or from
4272         // subtract last time around].  Leave at least one unit.
4273         for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4274 
4275         if (var1units<var2ulen) break;       // var1 too low for subtract
4276         if (var1units==var2ulen) {           // unit-by-unit compare needed
4277           // compare the two numbers, from msu
4278           const Unit *pv1, *pv2;
4279           Unit v2;                           // units to compare
4280           pv2=msu2;                          // -> msu
4281           for (pv1=msu1; ; pv1--, pv2--) {
4282             // v1=*pv1 -- always OK
4283             v2=0;                            // assume in padding
4284             if (pv2>=var2) v2=*pv2;          // in range
4285             if (*pv1!=v2) break;             // no longer the same
4286             if (pv1==var1) break;            // done; leave pv1 as is
4287             }
4288           // here when all inspected or a difference seen
4289           if (*pv1<v2) break;                // var1 too low to subtract
4290           if (*pv1==v2) {                    // var1 == var2
4291             // reach here if var1 and var2 are identical; subtraction
4292             // would increase digit by one, and the residue will be 0 so
4293             // the calculation is done; leave the loop with residue=0.
4294             thisunit++;                      // as though subtracted
4295             *var1=0;                         // set var1 to 0
4296             var1units=1;                     // ..
4297             break;  // from inner
4298             } // var1 == var2
4299           // *pv1>v2.  Prepare for real subtraction; the lengths are equal
4300           // Estimate the multiplier (there's always a msu1-1)...
4301           // Bring in two units of var2 to provide a good estimate.
4302           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4303           } // lengths the same
4304          else { // var1units > var2ulen, so subtraction is safe
4305           // The var2 msu is one unit towards the lsu of the var1 msu,
4306           // so only one unit for var2 can be used.
4307           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4308           }
4309         if (mult==0) mult=1;                 // must always be at least 1
4310         // subtraction needed; var1 is > var2
4311         thisunit=(Unit)(thisunit+mult);      // accumulate
4312         // subtract var1-var2, into var1; only the overlap needs
4313         // processing, as this is an in-place calculation
4314         shift=var2ulen-var2units;
4315         decUnitAddSub(&var1[shift], var1units-shift,
4316                       var2, var2units, 0,
4317                       &var1[shift], -mult);
4318         // var1 now probably has leading zeros; these are removed at the
4319         // top of the inner loop.
4320         } // inner loop
4321 
4322       // The next unit has been calculated in full; unless it's a
4323       // leading zero, add to acc
4324       if (accunits!=0 || thisunit!=0) {      // is first or non-zero
4325         *accnext=thisunit;                   // store in accumulator
4326         // account exactly for the new digits
4327         if (accunits==0) {
4328           accdigits++;                       // at least one
4329           for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4330           }
4331          else accdigits+=DECDPUN;
4332         accunits++;                          // update count
4333         accnext--;                           // ready for next
4334         if (accdigits>reqdigits) break;      // have enough digits
4335         }
4336 
4337       // if the residue is zero, the operation is done (unless divide
4338       // or divideInteger and still not enough digits yet)
4339 #ifdef __clang_analyzer__
4340       *var1=0;
4341 #endif /* ifdef __clang_analyzer__ */
4342       if (*var1==0 && var1units==1) {        // residue is 0
4343         if (op&(REMAINDER|REMNEAR)) break;
4344         if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4345         // [drop through if divideInteger]
4346         }
4347       // also done enough if calculating remainder or integer
4348       // divide and just did the last ('units') unit
4349       if (exponent==0 && !(op&DIVIDE)) break;
4350 
4351       // to get here, var1 is less than var2, so divide var2 by the per-
4352       // Unit power of ten and go for the next digit
4353       var2ulen--;                            // shift down
4354       exponent-=DECDPUN;                     // update the exponent
4355       } // outer loop
4356 
4357     // ---- division is complete ---------------------------------------
4358     // here: acc      has at least reqdigits+1 of good results (or fewer
4359     //                if early stop), starting at accnext+1 (its lsu)
4360     //       var1     has any residue at the stopping point
4361     //       accunits is the number of digits collected in acc
4362     if (accunits==0) {             // acc is 0
4363       accunits=1;                  // show have a unit ..
4364       accdigits=1;                 // ..
4365       *accnext=0;                  // .. whose value is 0
4366       }
4367      else accnext++;               // back to last placed
4368     // accnext now -> lowest unit of result
4369 
4370     residue=0;                     // assume no residue
4371     if (op&DIVIDE) {
4372       // record the presence of any residue, for rounding
4373       if (*var1!=0 || var1units>1) residue=1;
4374        else { // no residue
4375         // Had an exact division; clean up spurious trailing 0s.
4376         // There will be at most DECDPUN-1, from the final multiply,
4377         // and then only if the result is non-0 (and even) and the
4378         // exponent is 'loose'.
4379 #if DECDPUN>1
4380         Unit lsu=*accnext;
4381         if (!(lsu&0x01) && (lsu!=0)) {
4382           // count the trailing zeros
4383           Int drop=0;
4384           for (;; drop++) {    // [will terminate because lsu!=0]
4385             if (exponent>=maxexponent) break;     // don't chop real 0s
4386 # if DECDPUN<=4
4387               if ((lsu-QUOT10(lsu, drop+1)
4388                   *powers[drop+1])!=0) break;     // found non-0 digit
4389 # else
4390               if (lsu%powers[drop+1]!=0) break;   // found non-0 digit
4391 # endif
4392             exponent++;
4393             }
4394           if (drop>0) {
4395             accunits=decShiftToLeast(accnext, accunits, drop);
4396             accdigits=decGetDigits(accnext, accunits);
4397             accunits=D2U(accdigits);
4398             (void)accunits;
4399             // [exponent was adjusted in the loop]
4400             }
4401           } // neither odd nor 0
4402 #endif
4403         } // exact divide
4404       } // divide
4405      else /* op!=DIVIDE */ {
4406       // check for coefficient overflow
4407       if (accdigits+exponent>reqdigits) {
4408         *status|=DEC_Division_impossible;
4409         break;
4410         }
4411       if (op & (REMAINDER|REMNEAR)) {
4412         // [Here, the exponent will be 0, because var1 was adjusted
4413         // appropriately.]
4414         Int postshift;                       // work
4415         Flag wasodd=0;                       // integer was odd
4416         Unit *quotlsu;                       // for save
4417         Int  quotdigits;                     // ..
4418 
4419         bits=lhs->bits;                      // remainder sign is always as lhs
4420 
4421         // Fastpath when residue is truly 0 is worthwhile [and
4422         // simplifies the code below]
4423         if (*var1==0 && var1units==1) {      // residue is 0
4424           Int exp=lhs->exponent;             // save min(exponents)
4425           if (rhs->exponent<exp) exp=rhs->exponent;
4426           decNumberZero(res);                // 0 coefficient
4427 #if DECSUBSET
4428           if (set->extended)
4429 #endif
4430           res->exponent=exp;                 // .. with proper exponent
4431           res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4432           decFinish(res, set, &residue, status);   // might clamp
4433           break;
4434           }
4435         // note if the quotient was odd
4436         if (*accnext & 0x01) wasodd=1;       // acc is odd
4437         quotlsu=accnext;                     // save in case need to reinspect
4438         quotdigits=accdigits;                // ..
4439 
4440         // treat the residue, in var1, as the value to return, via acc
4441         // calculate the unused zero digits.  This is the smaller of:
4442         //   var1 initial padding (saved above)
4443         //   var2 residual padding, which happens to be given by:
4444         postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4445         // [the 'exponent' term accounts for the shifts during divide]
4446         if (var1initpad<postshift) postshift=var1initpad;
4447 
4448         // shift var1 the requested amount, and adjust its digits
4449         var1units=decShiftToLeast(var1, var1units, postshift);
4450         accnext=var1;
4451         accdigits=decGetDigits(var1, var1units);
4452         accunits=D2U(accdigits);
4453 
4454         exponent=lhs->exponent;         // exponent is smaller of lhs & rhs
4455         if (rhs->exponent<exponent) exponent=rhs->exponent;
4456 
4457         // Now correct the result if doing remainderNear; if it
4458         // (looking just at coefficients) is > rhs/2, or == rhs/2 and
4459         // the integer was odd then the result should be rem-rhs.
4460         if (op&REMNEAR) {
4461           Int compare, tarunits;        // work
4462           Unit *up;                     // ..
4463           // calculate remainder*2 into the var1 buffer (which has
4464           // 'headroom' of an extra unit and hence enough space)
4465           // [a dedicated 'double' loop would be faster, here]
4466           tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4467                                  0, accnext, 1);
4468           // decDumpAr('r', accnext, tarunits);
4469 
4470           // Here, accnext (var1) holds tarunits Units with twice the
4471           // remainder's coefficient, which must now be compared to the
4472           // RHS.  The remainder's exponent may be smaller than the RHS's.
4473           compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4474                                  rhs->exponent-exponent);
4475           if (compare==BADINT) {             // deep trouble
4476             *status|=DEC_Insufficient_storage;
4477             break;}
4478 
4479           // now restore the remainder by dividing by two; the lsu
4480           // is known to be even.
4481           for (up=accnext; up<accnext+tarunits; up++) {
4482             Int half;              // half to add to lower unit
4483             half=*up & 0x01;
4484             *up/=2;                // [shift]
4485             if (!half) continue;
4486             *(up-1)+=(DECDPUNMAX+1)/2;
4487             }
4488           // [accunits still describes the original remainder length]
4489 
4490           if (compare>0 || (compare==0 && wasodd)) { // adjustment needed
4491             Int exp, expunits, exprem;       // work
4492             // This is effectively causing round-up of the quotient,
4493             // so if it was the rare case where it was full and all
4494             // nines, it would overflow and hence division-impossible
4495             // should be raised
4496             Flag allnines=0;                 // 1 if quotient all nines
4497             if (quotdigits==reqdigits) {     // could be borderline
4498               for (up=quotlsu; ; up++) {
4499                 if (quotdigits>DECDPUN) {
4500                   if (*up!=DECDPUNMAX) break;// non-nines
4501                   }
4502                  else {                      // this is the last Unit
4503                   if (*up==powers[quotdigits]-1) allnines=1;
4504                   break;
4505                   }
4506                 quotdigits-=DECDPUN;         // checked those digits
4507                 } // up
4508               } // borderline check
4509             if (allnines) {
4510               *status|=DEC_Division_impossible;
4511               break;}
4512 
4513             // rem-rhs is needed; the sign will invert.  Again, var1
4514             // can safely be used for the working Units array.
4515             exp=rhs->exponent-exponent;      // RHS padding needed
4516             // Calculate units and remainder from exponent.
4517             expunits=exp/DECDPUN;
4518             exprem=exp%DECDPUN;
4519             // subtract [A+B*(-m)]; the result will always be negative
4520             accunits=-decUnitAddSub(accnext, accunits,
4521                                     rhs->lsu, D2U(rhs->digits),
4522                                     expunits, accnext, -(Int)powers[exprem]);
4523             accdigits=decGetDigits(accnext, accunits); // count digits exactly
4524             accunits=D2U(accdigits);    // and recalculate the units for copy
4525             (void)accunits;
4526             // [exponent is as for original remainder]
4527             bits^=DECNEG;               // flip the sign
4528             }
4529           } // REMNEAR
4530         } // REMAINDER or REMNEAR
4531       } // not DIVIDE
4532 
4533     // Set exponent and bits
4534     res->exponent=exponent;
4535     res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4536 
4537     // Now the coefficient.
4538     decSetCoeff(res, set, accnext, accdigits, &residue, status);
4539 
4540     decFinish(res, set, &residue, status);   // final cleanup
4541 
4542 #if DECSUBSET
4543     // If a divide then strip trailing zeros if subset [after round]
4544     if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4545 #endif
4546     } while(0);                              // end protected
4547 
4548   if (varalloc!=NULL) FREE(varalloc);   // drop any storage used
4549   if (allocacc!=NULL) FREE(allocacc);   // ..
4550 #if DECSUBSET
4551   if (allocrhs!=NULL) FREE(allocrhs);   // ..
4552   if (alloclhs!=NULL) FREE(alloclhs);   // ..
4553 #endif
4554   return res;
4555   } // decDivideOp
4556 
4557 /* ------------------------------------------------------------------ */
4558 /* decMultiplyOp -- multiplication operation                          */
4559 /*                                                                    */
4560 /*  This routine performs the multiplication C=A x B.                 */
4561 /*                                                                    */
4562 /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4563 /*   lhs is A                                                         */
4564 /*   rhs is B                                                         */
4565 /*   set is the context                                               */
4566 /*   status is the usual accumulator                                  */
4567 /*                                                                    */
4568 /* C must have space for set->digits digits.                          */
4569 /*                                                                    */
4570 /* ------------------------------------------------------------------ */
4571 /* 'Classic' multiplication is used rather than Karatsuba, as the     */
4572 /* latter would give only a minor improvement for the short numbers   */
4573 /* expected to be handled most (and uses much more memory).           */
4574 /*                                                                    */
4575 /* There are two major paths here: the general-purpose ('old code')   */
4576 /* path which handles all DECDPUN values, and a fastpath version      */
4577 /* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4578 /* than two calls to decUnitAddSub would be made.                     */
4579 /*                                                                    */
4580 /* The fastpath version lumps units together into 8-digit or 9-digit  */
4581 /* chunks, and also uses a lazy carry strategy to minimize expensive  */
4582 /* 64-bit divisions.  The chunks are then broken apart again into     */
4583 /* units for continuing processing.  Despite this overhead, the       */
4584 /* fastpath can speed up some 16-digit operations by 10x (and much    */
4585 /* more for higher-precision calculations).                           */
4586 /*                                                                    */
4587 /* A buffer always has to be used for the accumulator; in the         */
4588 /* fastpath, buffers are also always needed for the chunked copies of */
4589 /* of the operand coefficients.                                       */
4590 /* Static buffers are larger than needed just for multiply, to allow  */
4591 /* for calls from other operations (notably exp).                     */
4592 /* ------------------------------------------------------------------ */
4593 #define FASTMUL (DECUSE64 && DECDPUN<5)
4594 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
4595                                  const decNumber *rhs, decContext *set,
4596                                  uInt *status) {
4597   Int    accunits;                 // Units of accumulator in use
4598   Int    exponent;                 // work
4599   Int    residue=0;                // rounding residue
4600   uByte  bits;                     // result sign
4601   Unit  *acc;                      // -> accumulator Unit array
4602   Int    needbytes;                // size calculator
4603   void  *allocacc=NULL;            // -> allocated accumulator, iff allocated
4604   Unit  accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,
4605                                    // *4 for calls from other operations)
4606   const Unit *mer, *mermsup;       // work
4607   Int   madlength;                 // Units in multiplicand
4608   Int   shift;                     // Units to shift multiplicand by
4609 
4610 #if FASTMUL
4611     // if DECDPUN is 1 or 3 work in base 10**9, otherwise
4612     // (DECDPUN is 2 or 4) then work in base 10**8
4613 # if DECDPUN & 1                // odd
4614 #  define FASTBASE 1000000000  // base
4615 #  define FASTDIGS          9  // digits in base
4616 #  define FASTLAZY         18  // carry resolution point [1->18]
4617 # else
4618 #  define FASTBASE  100000000
4619 #  define FASTDIGS          8
4620 #  define FASTLAZY       1844  // carry resolution point [1->1844]
4621 # endif
4622     // three buffers are used, two for chunked copies of the operands
4623     // (base 10**8 or base 10**9) and one base 2**64 accumulator with
4624     // lazy carry evaluation
4625     uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4626     uInt  *zlhi=zlhibuff;                 // -> lhs array
4627     uInt  *alloclhi=NULL;                 // -> allocated buffer, iff allocated
4628     uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4629     uInt  *zrhi=zrhibuff;                 // -> rhs array
4630     uInt  *allocrhi=NULL;                 // -> allocated buffer, iff allocated
4631     uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)
4632     // [allocacc is shared for both paths, as only one will run]
4633     uLong *zacc=zaccbuff;          // -> accumulator array for exact result
4634 # if DECDPUN==1
4635     Int    zoff;                   // accumulator offset
4636 # endif
4637     uInt  *lip, *rip;              // item pointers
4638     uInt  *lmsi, *rmsi;            // most significant items
4639     Int    ilhs, irhs, iacc;       // item counts in the arrays
4640     Int    lazy;                   // lazy carry counter
4641     uLong  lcarry;                 // uLong carry
4642     uInt   carry;                  // carry (NB not uLong)
4643     Int    count;                  // work
4644     const  Unit *cup;              // ..
4645     Unit  *up;                     // ..
4646     uLong *lp;                     // ..
4647     Int    p;                      // ..
4648 #endif
4649 
4650 #if DECSUBSET
4651     decNumber *alloclhs=NULL;      // -> allocated buffer, iff allocated
4652     decNumber *allocrhs=NULL;      // -> allocated buffer, iff allocated
4653 #endif
4654 
4655   // precalculate result sign
4656   bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4657   (void)bits;
4658   // handle infinities and NaNs
4659   if (SPECIALARGS) {               // a special bit set
4660     if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
4661       decNaNs(res, lhs, rhs, set, status);
4662       return res;}
4663     // one or two infinities; Infinity * 0 is invalid
4664     if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4665       ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4666       *status|=DEC_Invalid_operation;
4667       return res;}
4668     decNumberZero(res);
4669     res->bits=bits|DECINF;         // infinity
4670     return res;}
4671 
4672   // For best speed, as in DMSRCN [the original Rexx numerics
4673   // module], use the shorter number as the multiplier (rhs) and
4674   // the longer as the multiplicand (lhs) to minimize the number of
4675   // adds (partial products)
4676   if (lhs->digits<rhs->digits) {   // swap...
4677     const decNumber *hold=lhs;
4678     lhs=rhs;
4679     rhs=hold;
4680     }
4681 
4682   do {                             // protect allocated storage
4683 #if DECSUBSET
4684     if (!set->extended) {
4685       // reduce operands and set lostDigits status, as needed
4686       if (lhs->digits>set->digits) {
4687         alloclhs=decRoundOperand(lhs, set, status);
4688         if (alloclhs==NULL) break;
4689         lhs=alloclhs;
4690         }
4691       if (rhs->digits>set->digits) {
4692         allocrhs=decRoundOperand(rhs, set, status);
4693         if (allocrhs==NULL) break;
4694         rhs=allocrhs;
4695         }
4696       }
4697 #endif
4698     // [following code does not require input rounding]
4699 
4700 #if FASTMUL                    // fastpath can be used
4701     // use the fast path if there are enough digits in the shorter
4702     // operand to make the setup and takedown worthwhile
4703 # define NEEDTWO (DECDPUN*2)    // within two decUnitAddSub calls
4704     if (rhs->digits>NEEDTWO) {     // use fastpath...
4705       // calculate the number of elements in each array
4706       ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]
4707       irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..
4708       iacc=ilhs+irhs;
4709 
4710       // allocate buffers if required, as usual
4711       needbytes=ilhs*sizeof(uInt);
4712       if (needbytes>(Int)sizeof(zlhibuff)) {
4713         alloclhi=(uInt *)malloc(needbytes);
4714         zlhi=alloclhi;}
4715       needbytes=irhs*sizeof(uInt);
4716       if (needbytes>(Int)sizeof(zrhibuff)) {
4717         allocrhi=(uInt *)malloc(needbytes);
4718         zrhi=allocrhi;}
4719 
4720       // Allocating the accumulator space needs a special case when
4721       // DECDPUN=1 because when converting the accumulator to Units
4722       // after the multiplication each 8-byte item becomes 9 1-byte
4723       // units.  Therefore iacc extra bytes are needed at the front
4724       // (rounded up to a multiple of 8 bytes), and the uLong
4725       // accumulator starts offset the appropriate number of units
4726       // to the right to avoid overwrite during the unchunking.
4727       needbytes=iacc*sizeof(uLong);
4728 # if DECDPUN==1
4729       zoff=(iacc+7)/8;        // items to offset by
4730       needbytes+=zoff*8;
4731 # endif
4732       if (needbytes>(Int)sizeof(zaccbuff)) {
4733         allocacc=(uLong *)malloc(needbytes);
4734         zacc=(uLong *)allocacc;}
4735       if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4736         *status|=DEC_Insufficient_storage;
4737         break;}
4738 
4739       acc=(Unit *)zacc;       // -> target Unit array
4740 # if DECDPUN==1
4741       zacc+=zoff;             // start uLong accumulator to right
4742 # endif
4743 
4744       // assemble the chunked copies of the left and right sides
4745       for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4746         for (p=0, *lip=0; p<FASTDIGS && count>0;
4747              p+=DECDPUN, cup++, count-=DECDPUN)
4748           *lip+=*cup*powers[p];
4749       lmsi=lip-1;     // save -> msi
4750       for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
4751         for (p=0, *rip=0; p<FASTDIGS && count>0;
4752              p+=DECDPUN, cup++, count-=DECDPUN)
4753           *rip+=*cup*powers[p];
4754       rmsi=rip-1;     // save -> msi
4755 
4756       // zero the accumulator
4757       for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
4758 
4759       /* Start the multiplication */
4760       // Resolving carries can dominate the cost of accumulating the
4761       // partial products, so this is only done when necessary.
4762       // Each uLong item in the accumulator can hold values up to
4763       // 2**64-1, and each partial product can be as large as
4764       // (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to
4765       // itself 18.4 times in a uLong without overflowing, so during
4766       // the main calculation resolution is carried out every 18th
4767       // add -- every 162 digits.  Similarly, when FASTDIGS=8, the
4768       // partial products can be added to themselves 1844.6 times in
4769       // a uLong without overflowing, so intermediate carry
4770       // resolution occurs only every 14752 digits.  Hence for common
4771       // short numbers usually only the one final carry resolution
4772       // occurs.
4773       // (The count is set via FASTLAZY to simplify experiments to
4774       // measure the value of this approach: a 35% improvement on a
4775       // [34x34] multiply.)
4776       lazy=FASTLAZY;                         // carry delay count
4777       for (rip=zrhi; rip<=rmsi; rip++) {     // over each item in rhs
4778         lp=zacc+(rip-zrhi);                  // where to add the lhs
4779         for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs
4780           *lp+=(uLong)(*lip)*(*rip);         // [this should in-line]
4781           } // lip loop
4782         lazy--;
4783         if (lazy>0 && rip!=rmsi) continue;
4784         lazy=FASTLAZY;                       // reset delay count
4785         // spin up the accumulator resolving overflows
4786         for (lp=zacc; lp<zacc+iacc; lp++) {
4787           if (*lp<FASTBASE) continue;        // it fits
4788           lcarry=*lp/FASTBASE;               // top part [slow divide]
4789           // lcarry can exceed 2**32-1, so check again; this check
4790           // and occasional extra divide (slow) is well worth it, as
4791           // it allows FASTLAZY to be increased to 18 rather than 4
4792           // in the FASTDIGS=9 case
4793           if (lcarry<FASTBASE) carry=(uInt)lcarry;  // [usual]
4794            else { // two-place carry [fairly rare]
4795             uInt carry2=(uInt)(lcarry/FASTBASE);    // top top part
4796             *(lp+2)+=carry2;                        // add to item+2
4797             *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]
4798             carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]
4799             }
4800           *(lp+1)+=carry;                    // add to item above [inline]
4801           *lp-=((uLong)FASTBASE*carry);      // [inline]
4802           } // carry resolution
4803         } // rip loop
4804 
4805       // The multiplication is complete; time to convert back into
4806       // units.  This can be done in-place in the accumulator and in
4807       // 32-bit operations, because carries were resolved after the
4808       // final add.  This needs N-1 divides and multiplies for
4809       // each item in the accumulator (which will become up to N
4810       // units, where 2<=N<=9).
4811       for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
4812         uInt item=(uInt)*lp;                 // decapitate to uInt
4813         for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
4814           uInt part=item/(DECDPUNMAX+1);
4815           *up=(Unit)(item-(part*(DECDPUNMAX+1)));
4816           item=part;
4817           } // p
4818         *up=(Unit)item; up++;                // [final needs no division]
4819         } // lp
4820       accunits=up-acc;                       // count of units
4821       }
4822      else { // here to use units directly, without chunking ['old code']
4823 #endif
4824 
4825       // if accumulator will be too long for local storage, then allocate
4826       acc=accbuff;                 // -> assume buffer for accumulator
4827       needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
4828       if (needbytes>(Int)sizeof(accbuff)) {
4829         allocacc=(Unit *)malloc(needbytes);
4830         if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
4831         acc=(Unit *)allocacc;                // use the allocated space
4832         }
4833 
4834       /* Now the main long multiplication loop */
4835       // Unlike the equivalent in the IBM Java implementation, there
4836       // is no advantage in calculating from msu to lsu.  So, do it
4837       // by the book, as it were.
4838       // Each iteration calculates ACC=ACC+MULTAND*MULT
4839       accunits=1;                  // accumulator starts at '0'
4840       *acc=0;                      // .. (lsu=0)
4841       shift=0;                     // no multiplicand shift at first
4842       madlength=D2U(lhs->digits);  // this won't change
4843       mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier
4844 
4845       for (mer=rhs->lsu; mer<mermsup; mer++) {
4846         // Here, *mer is the next Unit in the multiplier to use
4847         // If non-zero [optimization] add it...
4848         if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
4849                                             lhs->lsu, madlength, 0,
4850                                             &acc[shift], *mer)
4851                                             + shift;
4852          else { // extend acc with a 0; it will be used shortly
4853           *(acc+accunits)=0;       // [this avoids length of <=0 later]
4854           accunits++;
4855           }
4856         // multiply multiplicand by 10**DECDPUN for next Unit to left
4857         shift++;                   // add this for 'logical length'
4858         } // n
4859 #if FASTMUL
4860       } // unchunked units
4861 #endif
4862     // common end-path
4863 
4864     // acc now contains the exact result of the multiplication,
4865     // possibly with a leading zero unit; build the decNumber from
4866     // it, noting if any residue
4867     res->bits=bits;                          // set sign
4868     res->digits=decGetDigits(acc, accunits); // count digits exactly
4869 
4870     // There can be a 31-bit wrap in calculating the exponent.
4871     // This can only happen if both input exponents are negative and
4872     // both their magnitudes are large.  If there was a wrap, set a
4873     // safe very negative exponent, from which decFinalize() will
4874     // raise a hard underflow shortly.
4875     exponent=lhs->exponent+rhs->exponent;    // calculate exponent
4876     if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
4877       exponent=-2*DECNUMMAXE;                // force underflow
4878     res->exponent=exponent;                  // OK to overwrite now
4879 
4880     // Set the coefficient.  If any rounding, residue records
4881     decSetCoeff(res, set, acc, res->digits, &residue, status);
4882     decFinish(res, set, &residue, status);   // final cleanup
4883     } while(0);                         // end protected
4884 
4885   if (allocacc!=NULL) FREE(allocacc);   // drop any storage used
4886 #if DECSUBSET
4887   if (allocrhs!=NULL) FREE(allocrhs);   // ..
4888   if (alloclhs!=NULL) FREE(alloclhs);   // ..
4889 #endif
4890 #if FASTMUL
4891   if (allocrhi!=NULL) FREE(allocrhi);   // ..
4892   if (alloclhi!=NULL) FREE(alloclhi);   // ..
4893 #endif
4894   return res;
4895   } // decMultiplyOp
4896 
4897 /* ------------------------------------------------------------------ */
4898 /* decExpOp -- effect exponentiation                                  */
4899 /*                                                                    */
4900 /*   This computes C = exp(A)                                         */
4901 /*                                                                    */
4902 /*   res is C, the result.  C may be A                                */
4903 /*   rhs is A                                                         */
4904 /*   set is the context; note that rounding mode has no effect        */
4905 /*                                                                    */
4906 /* C must have space for set->digits digits. status is updated but    */
4907 /* not set.                                                           */
4908 /*                                                                    */
4909 /* Restrictions:                                                      */
4910 /*                                                                    */
4911 /*   digits, emax, and -emin in the context must be less than         */
4912 /*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
4913 /*   bounds or a zero.  This is an internal routine, so these         */
4914 /*   restrictions are contractual and not enforced.                   */
4915 /*                                                                    */
4916 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
4917 /* almost always be correctly rounded, but may be up to 1 ulp in      */
4918 /* error in rare cases.                                               */
4919 /*                                                                    */
4920 /* Finite results will always be full precision and Inexact, except   */
4921 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
4922 /* ------------------------------------------------------------------ */
4923 /* This approach used here is similar to the algorithm described in   */
4924 /*                                                                    */
4925 /*   Variable Precision Exponential Function, T. E. Hull and          */
4926 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
4927 /*   pp79-91, ACM, June 1986.                                         */
4928 /*                                                                    */
4929 /* with the main difference being that the iterations in the series   */
4930 /* evaluation are terminated dynamically (which does not require the  */
4931 /* extra variable-precision variables which are expensive in this     */
4932 /* context).                                                          */
4933 /*                                                                    */
4934 /* The error analysis in Hull & Abrham's paper applies except for the */
4935 /* round-off error accumulation during the series evaluation.  This   */
4936 /* code does not precalculate the number of iterations and so cannot  */
4937 /* use Horner's scheme.  Instead, the accumulation is done at double- */
4938 /* precision, which ensures that the additions of the terms are exact */
4939 /* and do not accumulate round-off (and any round-off errors in the   */
4940 /* terms themselves move 'to the right' faster than they can          */
4941 /* accumulate).  This code also extends the calculation by allowing,  */
4942 /* in the spirit of other decNumber operators, the input to be more   */
4943 /* precise than the result (the precision used is based on the more   */
4944 /* precise of the input or requested result).                         */
4945 /*                                                                    */
4946 /* Implementation notes:                                              */
4947 /*                                                                    */
4948 /* 1. This is separated out as decExpOp so it can be called from      */
4949 /*    other Mathematical functions (notably Ln) with a wider range    */
4950 /*    than normal.  In particular, it can handle the slightly wider   */
4951 /*    (double) range needed by Ln (which has to be able to calculate  */
4952 /*    exp(-x) where x can be the tiniest number (Ntiny).              */
4953 /*                                                                    */
4954 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
4955 /*    iterations by appoximately a third with additional (although    */
4956 /*    diminishing) returns as the range is reduced to even smaller    */
4957 /*    fractions.  However, h (the power of 10 used to correct the     */
4958 /*    result at the end, see below) must be kept <=8 as otherwise     */
4959 /*    the final result cannot be computed.  Hence the leverage is a   */
4960 /*    sliding value (8-h), where potentially the range is reduced     */
4961 /*    more for smaller values.                                        */
4962 /*                                                                    */
4963 /*    The leverage that can be applied in this way is severely        */
4964 /*    limited by the cost of the raise-to-the power at the end,       */
4965 /*    which dominates when the number of iterations is small (less    */
4966 /*    than ten) or when rhs is short.  As an example, the adjustment  */
4967 /*    x**10,000,000 needs 31 multiplications, all but one full-width. */
4968 /*                                                                    */
4969 /* 3. The restrictions (especially precision) could be raised with    */
4970 /*    care, but the full decNumber range seems very hard within the   */
4971 /*    32-bit limits.                                                  */
4972 /*                                                                    */
4973 /* 4. The working precisions for the static buffers are twice the     */
4974 /*    obvious size to allow for calls from decNumberPower.            */
4975 /* ------------------------------------------------------------------ */
4976 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
4977                          decContext *set, uInt *status) {
4978   uInt ignore=0;                   // working status
4979   Int h;                           // adjusted exponent for 0.xxxx
4980   Int p;                           // working precision
4981   Int residue;                     // rounding residue
4982   uInt needbytes;                  // for space calculations
4983   const decNumber *x=rhs;          // (may point to safe copy later)
4984   decContext aset, tset, dset;     // working contexts
4985   Int comp;                        // work
4986 
4987   // the argument is often copied to normalize it, so (unusually) it
4988   // is treated like other buffers, using DECBUFFER, +1 in case
4989   // DECBUFFER is 0
4990   decNumber bufr[D2N(DECBUFFER*2+1)];
4991   decNumber *allocrhs=NULL;        // non-NULL if rhs buffer allocated
4992 
4993   // the working precision will be no more than set->digits+8+1
4994   // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER
4995   // is 0 (and twice that for the accumulator)
4996 
4997   // buffer for t, term (working precision plus)
4998   decNumber buft[D2N(DECBUFFER*2+9+1)];
4999   decNumber *allocbuft=NULL;       // -> allocated buft, iff allocated
5000   decNumber *t=buft;               // term
5001   // buffer for a, accumulator (working precision * 2), at least 9
5002   decNumber bufa[D2N(DECBUFFER*4+18+1)];
5003   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5004   decNumber *a=bufa;               // accumulator
5005   // decNumber for the divisor term; this needs at most 9 digits
5006   // and so can be fixed size [16 so can use standard context]
5007   decNumber bufd[D2N(16)];
5008   decNumber *d=bufd;               // divisor
5009   decNumber numone;                // constant 1
5010 
5011   do {                                  // protect allocated storage
5012     if (SPECIALARG) {                   // handle infinities and NaNs
5013       if (decNumberIsInfinite(rhs)) {   // an infinity
5014         if (decNumberIsNegative(rhs))   // -Infinity -> +0
5015           decNumberZero(res);
5016          else decNumberCopy(res, rhs);  // +Infinity -> self
5017         }
5018        else decNaNs(res, rhs, NULL, set, status); // a NaN
5019       break;}
5020 
5021     if (ISZERO(rhs)) {                  // zeros -> exact 1
5022       decNumberZero(res);               // make clean 1
5023       *res->lsu=1;                      // ..
5024       break;}                           // [no status to set]
5025 
5026     // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path
5027     // positive and negative tiny cases which will result in inexact
5028     // 1.  This also allows the later add-accumulate to always be
5029     // exact (because its length will never be more than twice the
5030     // working precision).
5031     // The comparator (tiny) needs just one digit, so use the
5032     // decNumber d for it (reused as the divisor, etc., below); its
5033     // exponent is such that if x is positive it will have
5034     // set->digits-1 zeros between the decimal point and the digit,
5035     // which is 4, and if x is negative one more zero there as the
5036     // more precise result will be of the form 0.9999999 rather than
5037     // 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0
5038     // or 0.00000004 if digits=7 and x<0.  If RHS not larger than
5039     // this then the result will be 1.000000
5040     decNumberZero(d);                   // clean
5041     *d->lsu=4;                          // set 4 ..
5042     d->exponent=-set->digits;           // * 10**(-d)
5043     if (decNumberIsNegative(rhs)) d->exponent--;  // negative case
5044     comp=decCompare(d, rhs, 1);         // signless compare
5045     if (comp==BADINT) {
5046       *status|=DEC_Insufficient_storage;
5047       break;}
5048     if (comp>=0) {                      // rhs < d
5049       Int shift=set->digits-1;
5050       decNumberZero(res);               // set 1
5051       *res->lsu=1;                      // ..
5052       res->digits=decShiftToMost(res->lsu, 1, shift);
5053       res->exponent=-shift;                  // make 1.0000...
5054       *status|=DEC_Inexact | DEC_Rounded;    // .. inexactly
5055       break;} // tiny
5056 
5057     // set up the context to be used for calculating a, as this is
5058     // used on both paths below
5059     decContextDefault(&aset, DEC_INIT_DECIMAL64);
5060     // accumulator bounds are as requested (could underflow)
5061     aset.emax=set->emax;                // usual bounds
5062     aset.emin=set->emin;                // ..
5063     aset.clamp=0;                       // and no concrete format
5064 
5065     // calculate the adjusted (Hull & Abrham) exponent (where the
5066     // decimal point is just to the left of the coefficient msd)
5067     h=rhs->exponent+rhs->digits;
5068     // if h>8 then 10**h cannot be calculated safely; however, when
5069     // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at
5070     // least 6.59E+4342944, so (due to the restriction on Emax/Emin)
5071     // overflow (or underflow to 0) is guaranteed -- so this case can
5072     // be handled by simply forcing the appropriate excess
5073     if (h>8) {                          // overflow/underflow
5074       // set up here so Power call below will over or underflow to
5075       // zero; set accumulator to either 2 or 0.02
5076       // [stack buffer for a is always big enough for this]
5077       decNumberZero(a);
5078       *a->lsu=2;                        // not 1 but < exp(1)
5079       if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02
5080       h=8;                              // clamp so 10**h computable
5081       p=9;                              // set a working precision
5082       }
5083      else {                             // h<=8
5084       Int maxlever=(rhs->digits>8?1:0);
5085       // [could/should increase this for precisions >40 or so, too]
5086 
5087       // if h is 8, cannot normalize to a lower upper limit because
5088       // the final result will not be computable (see notes above),
5089       // but leverage can be applied whenever h is less than 8.
5090       // Apply as much as possible, up to a MAXLEVER digits, which
5091       // sets the tradeoff against the cost of the later a**(10**h).
5092       // As h is increased, the working precision below also
5093       // increases to compensate for the "constant digits at the
5094       // front" effect.
5095       Int lever=MINI(8-h, maxlever);    // leverage attainable
5096       Int use=-rhs->digits-lever;       // exponent to use for RHS
5097       h+=lever;                         // apply leverage selected
5098       if (h<0) {                        // clamp
5099         use+=h;                         // [may end up subnormal]
5100         h=0;
5101         }
5102       // Take a copy of RHS if it needs normalization (true whenever x>=1)
5103       if (rhs->exponent!=use) {
5104         decNumber *newrhs=bufr;         // assume will fit on stack
5105         needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5106         if (needbytes>sizeof(bufr)) {   // need malloc space
5107           allocrhs=(decNumber *)malloc(needbytes);
5108           if (allocrhs==NULL) {         // hopeless -- abandon
5109             *status|=DEC_Insufficient_storage;
5110             break;}
5111           newrhs=allocrhs;              // use the allocated space
5112           }
5113         decNumberCopy(newrhs, rhs);     // copy to safe space
5114         newrhs->exponent=use;           // normalize; now <1
5115         x=newrhs;                       // ready for use
5116         // decNumberShow(x);
5117         }
5118 
5119       // Now use the usual power series to evaluate exp(x).  The
5120       // series starts as 1 + x + x^2/2 ... so prime ready for the
5121       // third term by setting the term variable t=x, the accumulator
5122       // a=1, and the divisor d=2.
5123 
5124       // First determine the working precision.  From Hull & Abrham
5125       // this is set->digits+h+2.  However, if x is 'over-precise' we
5126       // need to allow for all its digits to potentially participate
5127       // (consider an x where all the excess digits are 9s) so in
5128       // this case use x->digits+h+2
5129       p=MAXI(x->digits, set->digits)+h+2;    // [h<=8]
5130 
5131       // a and t are variable precision, and depend on p, so space
5132       // must be allocated for them if necessary
5133 
5134       // the accumulator needs to be able to hold 2p digits so that
5135       // the additions on the second and subsequent iterations are
5136       // sufficiently exact.
5137       needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5138       if (needbytes>sizeof(bufa)) {     // need malloc space
5139         allocbufa=(decNumber *)malloc(needbytes);
5140         if (allocbufa==NULL) {          // hopeless -- abandon
5141           *status|=DEC_Insufficient_storage;
5142           break;}
5143         a=allocbufa;                    // use the allocated space
5144         }
5145       // the term needs to be able to hold p digits (which is
5146       // guaranteed to be larger than x->digits, so the initial copy
5147       // is safe); it may also be used for the raise-to-power
5148       // calculation below, which needs an extra two digits
5149       needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5150       if (needbytes>sizeof(buft)) {     // need malloc space
5151         allocbuft=(decNumber *)malloc(needbytes);
5152         if (allocbuft==NULL) {          // hopeless -- abandon
5153           *status|=DEC_Insufficient_storage;
5154           break;}
5155         t=allocbuft;                    // use the allocated space
5156         }
5157 
5158       decNumberCopy(t, x);              // term=x
5159       decNumberZero(a); *a->lsu=1;      // accumulator=1
5160       decNumberZero(d); *d->lsu=2;      // divisor=2
5161       decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment
5162 
5163       // set up the contexts for calculating a, t, and d
5164       decContextDefault(&tset, DEC_INIT_DECIMAL64);
5165       dset=tset;
5166       // accumulator bounds are set above, set precision now
5167       aset.digits=p*2;                  // double
5168       // term bounds avoid any underflow or overflow
5169       tset.digits=p;
5170       tset.emin=DEC_MIN_EMIN;           // [emax is plenty]
5171       // [dset.digits=16, etc., are sufficient]
5172 
5173       // finally ready to roll
5174       for (;;) {
5175         // only the status from the accumulation is interesting
5176         // [but it should remain unchanged after first add]
5177         decAddOp(a, a, t, &aset, 0, status);           // a=a+t
5178         decMultiplyOp(t, t, x, &tset, &ignore);        // t=t*x
5179         decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  // t=t/d
5180         // the iteration ends when the term cannot affect the result,
5181         // if rounded to p digits, which is when its value is smaller
5182         // than the accumulator by p+1 digits.  There must also be
5183         // full precision in a.
5184         if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5185             && (a->digits>=p)) break;
5186         decAddOp(d, d, &numone, &dset, 0, &ignore);    // d=d+1
5187         } // iterate
5188       } // h<=8
5189 
5190     // apply postconditioning: a=a**(10**h) -- this is calculated
5191     // at a slightly higher precision than Hull & Abrham suggest
5192     if (h>0) {
5193       Int seenbit=0;               // set once a 1-bit is seen
5194       Int i;                       // counter
5195       Int n=powers[h];             // always positive
5196       aset.digits=p+2;             // sufficient precision
5197       // avoid the overhead and many extra digits of decNumberPower
5198       // as all that is needed is the short 'multipliers' loop; here
5199       // accumulate the answer into t
5200       decNumberZero(t); *t->lsu=1; // acc=1
5201       for (i=1;;i++){              // for each bit [top bit ignored]
5202         // abandon if have had overflow or terminal underflow
5203         if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?
5204           if (*status&DEC_Overflow || ISZERO(t)) break;}
5205         n=n<<1;                    // move next bit to testable position
5206         if (n<0) {                 // top bit is set
5207           seenbit=1;               // OK, have a significant bit
5208           decMultiplyOp(t, t, a, &aset, status); // acc=acc*x
5209           }
5210         if (i==31) break;          // that was the last bit
5211         if (!seenbit) continue;    // no need to square 1
5212         decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]
5213         } /*i*/ // 32 bits
5214       // decNumberShow(t);
5215       a=t;                         // and carry on using t instead of a
5216       }
5217 
5218     // Copy and round the result to res
5219     residue=1;                          // indicate dirt to right ..
5220     if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5221     aset.digits=set->digits;            // [use default rounding]
5222     decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5223     decFinish(res, set, &residue, status);       // cleanup/set flags
5224     } while(0);                         // end protected
5225 
5226   if (allocrhs !=NULL) FREE(allocrhs);  // drop any storage used
5227   if (allocbufa!=NULL) FREE(allocbufa); // ..
5228   if (allocbuft!=NULL) FREE(allocbuft); // ..
5229   // [status is handled by caller]
5230   return res;
5231   } // decExpOp
5232 
5233 /* ------------------------------------------------------------------ */
5234 /* Initial-estimate natural logarithm table                           */
5235 /*                                                                    */
5236 /*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5237 /*           The result is a 4-digit encode of the coefficient (c=the */
5238 /*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5239 /*           exponent (e=the bottom 2 bits encoding 0-3)              */
5240 /*                                                                    */
5241 /*           The resulting value is given by:                         */
5242 /*                                                                    */
5243 /*             v = -c * 10**(-e-3)                                    */
5244 /*                                                                    */
5245 /*           where e and c are extracted from entry k = LNnn[x-10]    */
5246 /*           where x is truncated (NB) into the range 10 through 99,  */
5247 /*           and then c = k>>2 and e = k&3.                           */
5248 /* ------------------------------------------------------------------ */
5249 const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5250   6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5251   5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5252  39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5253  29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5254  22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5255  15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5256  10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5257   5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5258  10130,  6046, 20055};
5259 
5260 /* ------------------------------------------------------------------ */
5261 /* decLnOp -- effect natural logarithm                                */
5262 /*                                                                    */
5263 /*   This computes C = ln(A)                                          */
5264 /*                                                                    */
5265 /*   res is C, the result.  C may be A                                */
5266 /*   rhs is A                                                         */
5267 /*   set is the context; note that rounding mode has no effect        */
5268 /*                                                                    */
5269 /* C must have space for set->digits digits.                          */
5270 /*                                                                    */
5271 /* Notable cases:                                                     */
5272 /*   A<0 -> Invalid                                                   */
5273 /*   A=0 -> -Infinity (Exact)                                         */
5274 /*   A=+Infinity -> +Infinity (Exact)                                 */
5275 /*   A=1 exactly -> 0 (Exact)                                         */
5276 /*                                                                    */
5277 /* Restrictions (as for Exp):                                         */
5278 /*                                                                    */
5279 /*   digits, emax, and -emin in the context must be less than         */
5280 /*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5281 /*   bounds or a zero.  This is an internal routine, so these         */
5282 /*   restrictions are contractual and not enforced.                   */
5283 /*                                                                    */
5284 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5285 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5286 /* error in rare cases.                                               */
5287 /* ------------------------------------------------------------------ */
5288 /* The result is calculated using Newton's method, with each          */
5289 /* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5290 /* Epperson 1989.                                                     */
5291 /*                                                                    */
5292 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5293 /* This has to be calculated at the sum of the precision of x and the */
5294 /* working precision.                                                 */
5295 /*                                                                    */
5296 /* Implementation notes:                                              */
5297 /*                                                                    */
5298 /* 1. This is separated out as decLnOp so it can be called from       */
5299 /*    other Mathematical functions (e.g., Log 10) with a wider range  */
5300 /*    than normal.  In particular, it can handle the slightly wider   */
5301 /*    (+9+2) range needed by a power function.                        */
5302 /*                                                                    */
5303 /* 2. The speed of this function is about 10x slower than exp, as     */
5304 /*    it typically needs 4-6 iterations for short numbers, and the    */
5305 /*    extra precision needed adds a squaring effect, twice.           */
5306 /*                                                                    */
5307 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5308 /*    as these are common requests.  ln(10) is used by log10(x).      */
5309 /*                                                                    */
5310 /* 4. An iteration might be saved by widening the LNnn table, and     */
5311 /*    would certainly save at least one if it were made ten times     */
5312 /*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5313 /*    However, for most practical evaluations, at least four or five  */
5314 /*    iterations will be neede -- so this would only speed up by      */
5315 /*    20-25% and that probably does not justify increasing the table  */
5316 /*    size.                                                           */
5317 /*                                                                    */
5318 /* 5. The static buffers are larger than might be expected to allow   */
5319 /*    for calls from decNumberPower.                                  */
5320 /* ------------------------------------------------------------------ */
5321 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
5322                     decContext *set, uInt *status) {
5323   uInt ignore=0;                   // working status accumulator
5324   uInt needbytes;                  // for space calculations
5325   Int residue;                     // rounding residue
5326   Int r;                           // rhs=f*10**r [see below]
5327   Int p;                           // working precision
5328   Int pp;                          // precision for iteration
5329   Int t;                           // work
5330 
5331   // buffers for a (accumulator, typically precision+2) and b
5332   // (adjustment calculator, same size)
5333   decNumber bufa[D2N(DECBUFFER+12)];
5334   decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5335   decNumber *a=bufa;               // accumulator/work
5336   decNumber bufb[D2N(DECBUFFER*2+2)];
5337   decNumber *allocbufb=NULL;       // -> allocated bufa, iff allocated
5338   decNumber *b=bufb;               // adjustment/work
5339 
5340   decNumber  numone;               // constant 1
5341   decNumber  cmp;                  // work
5342   decContext aset, bset;           // working contexts
5343 
5344   do {                                  // protect allocated storage
5345     if (SPECIALARG) {                   // handle infinities and NaNs
5346       if (decNumberIsInfinite(rhs)) {   // an infinity
5347         if (decNumberIsNegative(rhs))   // -Infinity -> error
5348           *status|=DEC_Invalid_operation;
5349          else decNumberCopy(res, rhs);  // +Infinity -> self
5350         }
5351        else decNaNs(res, rhs, NULL, set, status); // a NaN
5352       break;}
5353 
5354     if (ISZERO(rhs)) {                  // +/- zeros -> -Infinity
5355       decNumberZero(res);               // make clean
5356       res->bits=DECINF|DECNEG;          // set - infinity
5357       break;}                           // [no status to set]
5358 
5359     // Non-zero negatives are bad...
5360     if (decNumberIsNegative(rhs)) {     // -x -> error
5361       *status|=DEC_Invalid_operation;
5362       break;}
5363 
5364     // Here, rhs is positive, finite, and in range
5365 
5366     // lookaside fastpath code for ln(2) and ln(10) at common lengths
5367     if (rhs->exponent==0 && set->digits<=40) {
5368 #if DECDPUN==1
5369       if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)
5370 #else
5371       if (rhs->lsu[0]==10 && rhs->digits==2) {                  // ln(10)
5372 #endif
5373         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5374 #define LN10 "2.302585092994045684017991454684364207601"
5375         decNumberFromString(res, LN10, &aset);
5376         *status|=(DEC_Inexact | DEC_Rounded); // is inexact
5377         break;}
5378       if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)
5379         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5380 #define LN2 "0.6931471805599453094172321214581765680755"
5381         decNumberFromString(res, LN2, &aset);
5382         *status|=(DEC_Inexact | DEC_Rounded);
5383         break;}
5384       } // integer and short
5385 
5386     // Determine the working precision.  This is normally the
5387     // requested precision + 2, with a minimum of 9.  However, if
5388     // the rhs is 'over-precise' then allow for all its digits to
5389     // potentially participate (consider an rhs where all the excess
5390     // digits are 9s) so in this case use rhs->digits+2.
5391     p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5392 
5393     // Allocate space for the accumulator and the high-precision
5394     // adjustment calculator, if necessary.  The accumulator must
5395     // be able to hold p digits, and the adjustment up to
5396     // rhs->digits+p digits.  They are also made big enough for 16
5397     // digits so that they can be used for calculating the initial
5398     // estimate.
5399     needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5400     if (needbytes>sizeof(bufa)) {     // need malloc space
5401       allocbufa=(decNumber *)malloc(needbytes);
5402       if (allocbufa==NULL) {          // hopeless -- abandon
5403         *status|=DEC_Insufficient_storage;
5404         break;}
5405       a=allocbufa;                    // use the allocated space
5406       }
5407     pp=p+rhs->digits;
5408     needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5409     if (needbytes>sizeof(bufb)) {     // need malloc space
5410       allocbufb=(decNumber *)malloc(needbytes);
5411       if (allocbufb==NULL) {          // hopeless -- abandon
5412         *status|=DEC_Insufficient_storage;
5413         break;}
5414       b=allocbufb;                    // use the allocated space
5415       }
5416 
5417     // Prepare an initial estimate in acc. Calculate this by
5418     // considering the coefficient of x to be a normalized fraction,
5419     // f, with the decimal point at far left and multiplied by
5420     // 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and
5421     //   ln(x) = ln(f) + ln(10)*r
5422     // Get the initial estimate for ln(f) from a small lookup
5423     // table (see above) indexed by the first two digits of f,
5424     // truncated.
5425 
5426     decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended
5427     r=rhs->exponent+rhs->digits;        // 'normalised' exponent
5428     decNumberFromInt32(a, r);           // a=r
5429     decNumberFromInt32(b, 2302585);     // b=ln(10) (2.302585)
5430     b->exponent=-6;                     //  ..
5431     decMultiplyOp(a, a, b, &aset, &ignore);  // a=a*b
5432     // now get top two digits of rhs into b by simple truncate and
5433     // force to integer
5434     residue=0;                          // (no residue)
5435     aset.digits=2; aset.round=DEC_ROUND_DOWN;
5436     decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten
5437     b->exponent=0;                      // make integer
5438     t=decGetInt(b);                     // [cannot fail]
5439 #ifdef __clang_analyzer__
5440     if (t<0) t=10;
5441 #endif /* ifdef __clang_analyzer__ */
5442     if (t<10) t=X10(t);                 // adjust single-digit b
5443 #ifndef __clang_analyzer__
5444     t=LNnn[t-10];                       // look up ln(b)
5445 #endif /* ifndef __clang_analyzer__ */
5446     decNumberFromInt32(b, t>>2);        // b=ln(b) coefficient
5447     b->exponent=-(t&3)-3;               // set exponent
5448     b->bits=DECNEG;                     // ln(0.10)->ln(0.99) always -ve
5449     aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore
5450     decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b
5451     // the initial estimate is now in a, with up to 4 digits correct.
5452     // When rhs is at or near Nmax the estimate will be low, so we
5453     // will approach it from below, avoiding overflow when calling exp.
5454 
5455     decNumberZero(&numone); *numone.lsu=1;   // constant 1 for adjustment
5456 
5457     // accumulator bounds are as requested (could underflow, but
5458     // cannot overflow)
5459     aset.emax=set->emax;
5460     aset.emin=set->emin;
5461     aset.clamp=0;                       // no concrete format
5462     if (rhs->digits > set->digits) {
5463       aset.emax=DEC_MAX_MATH*2;
5464       aset.emin=-DEC_MAX_MATH*2;
5465     }
5466     // set up a context to be used for the multiply and subtract
5467     bset=aset;
5468     bset.emax=DEC_MAX_MATH*2;           // use double bounds for the
5469     bset.emin=-DEC_MAX_MATH*2;          // adjustment calculation
5470                                         // [see decExpOp call below]
5471     // for each iteration double the number of digits to calculate,
5472     // up to a maximum of p
5473     pp=9;                               // initial precision
5474     // [initially 9 as then the sequence starts 7+2, 16+2, and
5475     // 34+2, which is ideal for standard-sized numbers]
5476     aset.digits=pp;                     // working context
5477     bset.digits=pp+rhs->digits;         // wider context
5478     for (;;) {                          // iterate
5479       // calculate the adjustment (exp(-a)*x-1) into b.  This is a
5480       // catastrophic subtraction but it really is the difference
5481       // from 1 that is of interest.
5482       // Use the internal entry point to Exp as it allows the double
5483       // range for calculating exp(-a) when a is the tiniest subnormal.
5484       a->bits^=DECNEG;                  // make -a
5485       decExpOp(b, a, &bset, &ignore);   // b=exp(-a)
5486       a->bits^=DECNEG;                  // restore sign of a
5487       // now multiply by rhs and subtract 1, at the wider precision
5488       decMultiplyOp(b, b, rhs, &bset, &ignore);        // b=b*rhs
5489       decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1
5490 
5491       // the iteration ends when the adjustment cannot affect the
5492       // result by >=0.5 ulp (at the requested digits), which
5493       // is when its value is smaller than the accumulator by
5494       // set->digits+1 digits (or it is zero) -- this is a looser
5495       // requirement than for Exp because all that happens to the
5496       // accumulator after this is the final rounding (but note that
5497       // there must also be full precision in a, or a=0).
5498 
5499       if (decNumberIsZero(b) ||
5500           (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5501         if (a->digits==p) break;
5502         if (decNumberIsZero(a)) {
5503           decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?
5504           if (cmp.lsu[0]==0) a->exponent=0;            // yes, exact 0
5505            else *status|=(DEC_Inexact | DEC_Rounded);  // no, inexact
5506           break;
5507           }
5508         // force padding if adjustment has gone to 0 before full length
5509         if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5510         }
5511 
5512       // not done yet ...
5513       decAddOp(a, a, b, &aset, 0, &ignore);  // a=a+b for next estimate
5514       if (pp==p) continue;                   // precision is at maximum
5515       // lengthen the next calculation
5516       pp=pp*2;                               // double precision
5517       if (pp>p) pp=p;                        // clamp to maximum
5518       aset.digits=pp;                        // working context
5519       bset.digits=pp+rhs->digits;            // wider context
5520       } // Newton's iteration
5521 
5522     // Copy and round the result to res
5523     residue=1;                          // indicate dirt to right
5524     if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5525     aset.digits=set->digits;            // [use default rounding]
5526     decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5527     decFinish(res, set, &residue, status);       // cleanup/set flags
5528     } while(0);                         // end protected
5529 
5530   if (allocbufa!=NULL) FREE(allocbufa); // drop any storage used
5531   if (allocbufb!=NULL) FREE(allocbufb); // ..
5532   // [status is handled by caller]
5533   return res;
5534   } // decLnOp
5535 
5536 /* ------------------------------------------------------------------ */
5537 /* decQuantizeOp  -- force exponent to requested value                */
5538 /*                                                                    */
5539 /*   This computes C = op(A, B), where op adjusts the coefficient     */
5540 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
5541 /*   of C has the value B or matches the exponent of B.               */
5542 /*   The numerical value of C will equal A, except for the effects of */
5543 /*   any rounding that occurred.                                      */
5544 /*                                                                    */
5545 /*   res is C, the result.  C may be A or B                           */
5546 /*   lhs is A, the number to adjust                                   */
5547 /*   rhs is B, the requested exponent                                 */
5548 /*   set is the context                                               */
5549 /*   quant is 1 for quantize or 0 for rescale                         */
5550 /*   status is the status accumulator (this can be called without     */
5551 /*          risk of control loss)                                     */
5552 /*                                                                    */
5553 /* C must have space for set->digits digits.                          */
5554 /*                                                                    */
5555 /* Unless there is an error or the result is infinite, the exponent   */
5556 /* after the operation is guaranteed to be that requested.            */
5557 /* ------------------------------------------------------------------ */
5558 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
5559                                  const decNumber *rhs, decContext *set,
5560                                  Flag quant, uInt *status) {
5561 #if DECSUBSET
5562   decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
5563   decNumber *allocrhs=NULL;        // .., rhs
5564 #endif
5565   const decNumber *inrhs=rhs;      // save original rhs
5566   Int   reqdigits=set->digits;     // requested DIGITS
5567   Int   reqexp;                    // requested exponent [-scale]
5568   Int   residue=0;                 // rounding residue
5569   Int   etiny=set->emin-(reqdigits-1);
5570 
5571   do {                             // protect allocated storage
5572 #if DECSUBSET
5573     if (!set->extended) {
5574       // reduce operands and set lostDigits status, as needed
5575       if (lhs->digits>reqdigits) {
5576         alloclhs=decRoundOperand(lhs, set, status);
5577         if (alloclhs==NULL) break;
5578         lhs=alloclhs;
5579         }
5580       if (rhs->digits>reqdigits) { // [this only checks lostDigits]
5581         allocrhs=decRoundOperand(rhs, set, status);
5582         if (allocrhs==NULL) break;
5583         rhs=allocrhs;
5584         }
5585       }
5586 #endif
5587     // [following code does not require input rounding]
5588 
5589     // Handle special values
5590     if (SPECIALARGS) {
5591       // NaNs get usual processing
5592       if (SPECIALARGS & (DECSNAN | DECNAN))
5593         decNaNs(res, lhs, rhs, set, status);
5594       // one infinity but not both is bad
5595       else if ((lhs->bits ^ rhs->bits) & DECINF)
5596         *status|=DEC_Invalid_operation;
5597       // both infinity: return lhs
5598       else decNumberCopy(res, lhs);          // [nop if in place]
5599       break;
5600       }
5601 
5602     // set requested exponent
5603     if (quant) reqexp=inrhs->exponent;  // quantize -- match exponents
5604      else {                             // rescale -- use value of rhs
5605       // Original rhs must be an integer that fits and is in range,
5606       // which could be from -1999999997 to +999999999, thanks to
5607       // subnormals
5608       reqexp=decGetInt(inrhs);               // [cannot fail]
5609       }
5610 
5611 #if DECSUBSET
5612     if (!set->extended) etiny=set->emin;     // no subnormals
5613 #endif
5614 
5615     if (reqexp==BADINT                       // bad (rescale only) or ..
5616      || reqexp==BIGODD || reqexp==BIGEVEN    // very big (ditto) or ..
5617      || (reqexp<etiny)                       // < lowest
5618      || (reqexp>set->emax)) {                // > emax
5619       *status|=DEC_Invalid_operation;
5620       break;}
5621 
5622     // the RHS has been processed, so it can be overwritten now if necessary
5623     if (ISZERO(lhs)) {                       // zero coefficient unchanged
5624       decNumberCopy(res, lhs);               // [nop if in place]
5625       res->exponent=reqexp;                  // .. just set exponent
5626 #if DECSUBSET
5627       if (!set->extended) res->bits=0;       // subset specification; no -0
5628 #endif
5629       }
5630      else {                                  // non-zero lhs
5631       Int adjust=reqexp-lhs->exponent;       // digit adjustment needed
5632       // if adjusted coefficient will definitely not fit, give up now
5633       if ((lhs->digits-adjust)>reqdigits) {
5634         *status|=DEC_Invalid_operation;
5635         break;
5636         }
5637 
5638       if (adjust>0) {                        // increasing exponent
5639         // this will decrease the length of the coefficient by adjust
5640         // digits, and must round as it does so
5641         decContext workset;                  // work
5642         workset=*set;                        // clone rounding, etc.
5643         workset.digits=lhs->digits-adjust;   // set requested length
5644         // [note that the latter can be <1, here]
5645         decCopyFit(res, lhs, &workset, &residue, status); // fit to result
5646         decApplyRound(res, &workset, residue, status);    // .. and round
5647         residue=0;                                        // [used]
5648         // If just rounded a 999s case, exponent will be off by one;
5649         // adjust back (after checking space), if so.
5650         if (res->exponent>reqexp) {
5651           // re-check needed, e.g., for quantize(0.9999, 0.001) under
5652           // set->digits==3
5653           if (res->digits==reqdigits) {      // cannot shift by 1
5654             *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]
5655             *status|=DEC_Invalid_operation;
5656             break;
5657             }
5658           res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift
5659           res->exponent--;                   // (re)adjust the exponent.
5660           }
5661 #if DECSUBSET
5662         if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0
5663 #endif
5664         } // increase
5665        else /* adjust<=0 */ {                // decreasing or = exponent
5666         // this will increase the length of the coefficient by -adjust
5667         // digits, by adding zero or more trailing zeros; this is
5668         // already checked for fit, above
5669         decNumberCopy(res, lhs);             // [it will fit]
5670         // if padding needed (adjust<0), add it now...
5671         if (adjust<0) {
5672           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5673           res->exponent+=adjust;             // adjust the exponent
5674           }
5675         } // decrease
5676       } // non-zero
5677 
5678     // Check for overflow [do not use Finalize in this case, as an
5679     // overflow here is a "don't fit" situation]
5680     if (res->exponent>set->emax-res->digits+1) {  // too big
5681       *status|=DEC_Invalid_operation;
5682       break;
5683       }
5684      else {
5685       decFinalize(res, set, &residue, status);    // set subnormal flags
5686       *status&=~DEC_Underflow;          // suppress Underflow [as per 754]
5687       }
5688     } while(0);                         // end protected
5689 
5690 #if DECSUBSET
5691   if (allocrhs!=NULL) FREE(allocrhs);   // drop any storage used
5692   if (alloclhs!=NULL) FREE(alloclhs);   // ..
5693 #endif
5694   return res;
5695   } // decQuantizeOp
5696 
5697 /* ------------------------------------------------------------------ */
5698 /* decCompareOp -- compare, min, or max two Numbers                   */
5699 /*                                                                    */
5700 /*   This computes C = A ? B and carries out one of four operations:  */
5701 /*     COMPARE    -- returns the signum (as a number) giving the      */
5702 /*                   result of a comparison unless one or both        */
5703 /*                   operands is a NaN (in which case a NaN results)  */
5704 /*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5705 /*                   Invalid operation.                               */
5706 /*     COMPMAX    -- returns the larger of the operands, using the    */
5707 /*                   754 maxnum operation                             */
5708 /*     COMPMAXMAG -- ditto, comparing absolute values                 */
5709 /*     COMPMIN    -- the 754 minnum operation                         */
5710 /*     COMPMINMAG -- ditto, comparing absolute values                 */
5711 /*     COMTOTAL   -- returns the signum (as a number) giving the      */
5712 /*                   result of a comparison using 754 total ordering  */
5713 /*                                                                    */
5714 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
5715 /*   lhs is A                                                         */
5716 /*   rhs is B                                                         */
5717 /*   set is the context                                               */
5718 /*   op  is the operation flag                                        */
5719 /*   status is the usual accumulator                                  */
5720 /*                                                                    */
5721 /* C must have space for one digit for COMPARE or set->digits for     */
5722 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
5723 /* ------------------------------------------------------------------ */
5724 /* The emphasis here is on speed for common cases, and avoiding       */
5725 /* coefficient comparison if possible.                                */
5726 /* ------------------------------------------------------------------ */
5727 decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
5728                          const decNumber *rhs, decContext *set,
5729                          Flag op, uInt *status) {
5730 #if DECSUBSET
5731   decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
5732   decNumber *allocrhs=NULL;        // .., rhs
5733 #endif
5734   Int   result=0;                  // default result value
5735   uByte merged;                    // work
5736 
5737   do {                             // protect allocated storage
5738 #if DECSUBSET
5739     if (!set->extended) {
5740       // reduce operands and set lostDigits status, as needed
5741       if (lhs->digits>set->digits) {
5742         alloclhs=decRoundOperand(lhs, set, status);
5743         if (alloclhs==NULL) {result=BADINT; break;}
5744         lhs=alloclhs;
5745         }
5746       if (rhs->digits>set->digits) {
5747         allocrhs=decRoundOperand(rhs, set, status);
5748         if (allocrhs==NULL) {result=BADINT; break;}
5749         rhs=allocrhs;
5750         }
5751       }
5752 #endif
5753     // [following code does not require input rounding]
5754 
5755     // If total ordering then handle differing signs 'up front'
5756     if (op==COMPTOTAL) {                // total ordering
5757       /* cppcheck-suppress bitwiseOnBoolean */
5758       /* cppcheck-suppress clarifyCondition */
5759       if (decNumberIsNegative(lhs) && !decNumberIsNegative(rhs)) {
5760         result=-1;
5761         break;
5762         }
5763       /* cppcheck-suppress bitwiseOnBoolean */
5764       /* cppcheck-suppress clarifyCondition */
5765       if (!decNumberIsNegative(lhs) && decNumberIsNegative(rhs)) {
5766         result=+1;
5767         break;
5768         }
5769       }
5770 
5771     // handle NaNs specially; let infinities drop through
5772     // This assumes sNaN (even just one) leads to NaN.
5773     merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
5774     if (merged) {                       // a NaN bit set
5775       if (op==COMPARE);                 // result will be NaN
5776        else if (op==COMPSIG)            // treat qNaN as sNaN
5777         *status|=DEC_Invalid_operation | DEC_sNaN;
5778        else if (op==COMPTOTAL) {        // total ordering, always finite
5779         // signs are known to be the same; compute the ordering here
5780         // as if the signs are both positive, then invert for negatives
5781         if (!decNumberIsNaN(lhs)) result=-1;
5782          else if (!decNumberIsNaN(rhs)) result=+1;
5783          // here if both NaNs
5784          else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
5785          else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
5786          else { // both NaN or both sNaN
5787           // now it just depends on the payload
5788           result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
5789                                 rhs->lsu, D2U(rhs->digits), 0);
5790           // [Error not possible, as these are 'aligned']
5791           } // both same NaNs
5792         if (decNumberIsNegative(lhs)) result=-result;
5793         break;
5794         } // total order
5795 
5796        else if (merged & DECSNAN);           // sNaN -> qNaN
5797        else { // here if MIN or MAX and one or two quiet NaNs
5798         // min or max -- 754 rules ignore single NaN
5799         if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
5800           // just one NaN; force choice to be the non-NaN operand
5801           op=COMPMAX;
5802           if (lhs->bits & DECNAN) result=-1; // pick rhs
5803                              else result=+1; // pick lhs
5804           break;
5805           }
5806         } // max or min
5807       op=COMPNAN;                            // use special path
5808       decNaNs(res, lhs, rhs, set, status);   // propagate NaN
5809       break;
5810       }
5811     // have numbers
5812     if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
5813      else result=decCompare(lhs, rhs, 0);    // sign matters
5814     } while(0);                              // end protected
5815 
5816   if (result==BADINT) *status|=DEC_Insufficient_storage; // rare
5817    else {
5818     if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum
5819       if (op==COMPTOTAL && result==0) {
5820         // operands are numerically equal or same NaN (and same sign,
5821         // tested first); if identical, leave result 0
5822         if (lhs->exponent!=rhs->exponent) {
5823           if (lhs->exponent<rhs->exponent) result=-1;
5824            else result=+1;
5825           if (decNumberIsNegative(lhs)) result=-result;
5826           } // lexp!=rexp
5827         } // total-order by exponent
5828       decNumberZero(res);               // [always a valid result]
5829       if (result!=0) {                  // must be -1 or +1
5830         *res->lsu=1;
5831         if (result<0) res->bits=DECNEG;
5832         }
5833       }
5834      else if (op==COMPNAN);             // special, drop through
5835      else {                             // MAX or MIN, non-NaN result
5836       Int residue=0;                    // rounding accumulator
5837       // choose the operand for the result
5838       const decNumber *choice;
5839       if (result==0) { // operands are numerically equal
5840         // choose according to sign then exponent (see 754)
5841         uByte slhs=(lhs->bits & DECNEG);
5842         uByte srhs=(rhs->bits & DECNEG);
5843 #if DECSUBSET
5844         if (!set->extended) {           // subset: force left-hand
5845           op=COMPMAX;
5846           result=+1;
5847           }
5848         else
5849 #endif
5850         if (slhs!=srhs) {          // signs differ
5851           if (slhs) result=-1;     // rhs is max
5852                else result=+1;     // lhs is max
5853           }
5854          /* cppcheck-suppress knownConditionTrueFalse */
5855          else if (slhs && srhs) {  // both negative
5856           if (lhs->exponent<rhs->exponent) result=+1;
5857                                       else result=-1;
5858           // [if equal, use lhs, technically identical]
5859           }
5860          else {                    // both positive
5861           if (lhs->exponent>rhs->exponent) result=+1;
5862                                       else result=-1;
5863           // [ditto]
5864           }
5865         } // numerically equal
5866       // here result will be non-0; reverse if looking for MIN
5867       if (op==COMPMIN || op==COMPMINMAG) result=-result;
5868       choice=(result>0 ? lhs : rhs);    // choose
5869       // copy chosen to result, rounding if need be
5870       decCopyFit(res, choice, set, &residue, status);
5871       decFinish(res, set, &residue, status);
5872       }
5873     }
5874 #if DECSUBSET
5875   if (allocrhs!=NULL) FREE(allocrhs);   // free any storage used
5876   if (alloclhs!=NULL) FREE(alloclhs);   // ..
5877 #endif
5878   return res;
5879   } // decCompareOp
5880 
5881 /* ------------------------------------------------------------------ */
5882 /* decCompare -- compare two decNumbers by numerical value            */
5883 /*                                                                    */
5884 /*  This routine compares A ? B without altering them.                */
5885 /*                                                                    */
5886 /*  Arg1 is A, a decNumber which is not a NaN                         */
5887 /*  Arg2 is B, a decNumber which is not a NaN                         */
5888 /*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
5889 /*                                                                    */
5890 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
5891 /*  (the only possible failure is an allocation error)                */
5892 /* ------------------------------------------------------------------ */
5893 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
     /* [previous][next][first][last][top][bottom][index][help] */
5894                       Flag abs) {
5895   Int   result;                    // result value
5896   Int   sigr;                      // rhs signum
5897   Int   compare;                   // work
5898 
5899   result=1;                                  // assume signum(lhs)
5900   if (ISZERO(lhs)) result=0;
5901   if (abs) {
5902     if (ISZERO(rhs)) return result;          // LHS wins or both 0
5903     // RHS is non-zero
5904     if (result==0) return -1;                // LHS is 0; RHS wins
5905     // [here, both non-zero, result=1]
5906     }
5907    else {                                    // signs matter
5908     if (result && decNumberIsNegative(lhs)) result=-1;
5909     sigr=1;                                  // compute signum(rhs)
5910     if (ISZERO(rhs)) sigr=0;
5911      else if (decNumberIsNegative(rhs)) sigr=-1;
5912     if (result > sigr) return +1;            // L > R, return 1
5913     if (result < sigr) return -1;            // L < R, return -1
5914     if (result==0) return 0;                   // both 0
5915     }
5916 
5917   // signums are the same; both are non-zero
5918   if ((lhs->bits | rhs->bits) & DECINF) {    // one or more infinities
5919     if (decNumberIsInfinite(rhs)) {
5920       if (decNumberIsInfinite(lhs)) result=0;// both infinite
5921        else result=-result;                  // only rhs infinite
5922       }
5923     return result;
5924     }
5925   // must compare the coefficients, allowing for exponents
5926   if (lhs->exponent>rhs->exponent) {         // LHS exponent larger
5927     // swap sides, and sign
5928     const decNumber *temp=lhs;
5929     lhs=rhs;
5930     rhs=temp;
5931     result=-result;
5932     }
5933   compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
5934                          rhs->lsu, D2U(rhs->digits),
5935                          rhs->exponent-lhs->exponent);
5936   if (compare!=BADINT) compare*=result;      // comparison succeeded
5937   return compare;
5938   } // decCompare
5939 
5940 /* ------------------------------------------------------------------ */
5941 /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
5942 /*                                                                    */
5943 /*  This routine compares A ? B*10**E where A and B are unit arrays   */
5944 /*  A is a plain integer                                              */
5945 /*  B has an exponent of E (which must be non-negative)               */
5946 /*                                                                    */
5947 /*  Arg1 is A first Unit (lsu)                                        */
5948 /*  Arg2 is A length in Units                                         */
5949 /*  Arg3 is B first Unit (lsu)                                        */
5950 /*  Arg4 is B length in Units                                         */
5951 /*  Arg5 is E (0 if the units are aligned)                            */
5952 /*                                                                    */
5953 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
5954 /*  (the only possible failure is an allocation error, which can      */
5955 /*  only occur if E!=0)                                               */
5956 /* ------------------------------------------------------------------ */
5957 static Int decUnitCompare(const Unit *a, Int alength,
     /* [previous][next][first][last][top][bottom][index][help] */
5958                           const Unit *b, Int blength, Int exp) {
5959   Unit  *acc;                      // accumulator for result
5960   Unit  accbuff[SD2U(DECBUFFER*2+1)]; // local buffer
5961   Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
5962   Int   accunits, need;            // units in use or needed for acc
5963   const Unit *l, *r, *u;           // work
5964   Int   expunits, exprem, result;  // ..
5965 
5966   if (exp==0) {                    // aligned; fastpath
5967     if (alength>blength) return 1;
5968     if (alength<blength) return -1;
5969     // same number of units in both -- need unit-by-unit compare
5970     l=a+alength-1;
5971     r=b+alength-1;
5972     for (;l>=a; l--, r--) {
5973       if (*l>*r) return 1;
5974       if (*l<*r) return -1;
5975       }
5976     return 0;                      // all units match
5977     } // aligned
5978 
5979   // Unaligned.  If one is >1 unit longer than the other, padded
5980   // approximately, then can return easily
5981   if (alength>blength+(Int)D2U(exp)) return 1;
5982   if (alength+1<blength+(Int)D2U(exp)) return -1;
5983 
5984   // Need to do a real subtract.  For this, a result buffer is needed
5985   // even though only the sign is of interest.  Its length needs
5986   // to be the larger of alength and padded blength, +2
5987   need=blength+D2U(exp);                // maximum real length of B
5988   if (need<alength) need=alength;
5989   need+=2;
5990   acc=accbuff;                          // assume use local buffer
5991   if (need*sizeof(Unit)>sizeof(accbuff)) {
5992     allocacc=(Unit *)malloc(need*sizeof(Unit));
5993     if (allocacc==NULL) return BADINT;  // hopeless -- abandon
5994     acc=allocacc;
5995     }
5996   // Calculate units and remainder from exponent.
5997   expunits=exp/DECDPUN;
5998   exprem=exp%DECDPUN;
5999   // subtract [A+B*(-m)]
6000   accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6001                          -(Int)powers[exprem]);
6002   // [UnitAddSub result may have leading zeros, even on zero]
6003   if (accunits<0) result=-1;            // negative result
6004    else {                               // non-negative result
6005     // check units of the result before freeing any storage
6006     for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6007     result=(*u==0 ? 0 : +1);
6008     }
6009   // clean up and return the result
6010   if (allocacc!=NULL) FREE(allocacc);   // drop any storage used
6011   return result;
6012   } // decUnitCompare
6013 
6014 /* ------------------------------------------------------------------ */
6015 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6016 /*                                                                    */
6017 /*  This routine performs the calculation:                            */
6018 /*                                                                    */
6019 /*  C=A+(B*M)                                                         */
6020 /*                                                                    */
6021 /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6022 /*                                                                    */
6023 /*  A may be shorter or longer than B.                                */
6024 /*                                                                    */
6025 /*  Leading zeros are not removed after a calculation.  The result is */
6026 /*  either the same length as the longer of A and B (adding any       */
6027 /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6028 /*                                                                    */
6029 /*  A and B content are not altered unless C is also A or B.          */
6030 /*  C may be the same array as A or B, but only if no zero padding is */
6031 /*  requested (that is, C may be B only if bshift==0).                */
6032 /*  C is filled from the lsu; only those units necessary to complete  */
6033 /*  the calculation are referenced.                                   */
6034 /*                                                                    */
6035 /*  Arg1 is A first Unit (lsu)                                        */
6036 /*  Arg2 is A length in Units                                         */
6037 /*  Arg3 is B first Unit (lsu)                                        */
6038 /*  Arg4 is B length in Units                                         */
6039 /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6040 /*  Arg6 is C first Unit (lsu)                                        */
6041 /*  Arg7 is M, the multiplier                                         */
6042 /*                                                                    */
6043 /*  returns the count of Units written to C, which will be non-zero   */
6044 /*  and negated if the result is negative.  That is, the sign of the  */
6045 /*  returned Int is the sign of the result (positive for zero) and    */
6046 /*  the absolute value of the Int is the count of Units.              */
6047 /*                                                                    */
6048 /*  It is the caller's responsibility to make sure that C size is     */
6049 /*  safe, allowing space if necessary for a one-Unit carry.           */
6050 /*                                                                    */
6051 /*  This routine is severely performance-critical; *any* change here  */
6052 /*  must be measured (timed) to assure no performance degradation.    */
6053 /*  In particular, trickery here tends to be counter-productive, as   */
6054 /*  increased complexity of code hurts register optimizations on      */
6055 /*  register-poor architectures.  Avoiding divisions is nearly        */
6056 /*  always a Good Idea, however.                                      */
6057 /*                                                                    */
6058 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6059 /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6060 /* ------------------------------------------------------------------ */
6061 static Int decUnitAddSub(const Unit *a, Int alength,
     /* [previous][next][first][last][top][bottom][index][help] */
6062                          const Unit *b, Int blength, Int bshift,
6063                          Unit *c, Int m) {
6064   const Unit *alsu=a;              // A lsu [need to remember it]
6065   Unit *clsu=c;                    // C ditto
6066   Unit *minC;                      // low water mark for C
6067   Unit *maxC;                      // high water mark for C
6068   eInt carry=0;                    // carry integer (could be Long)
6069   Int  add;                        // work
6070 #if DECDPUN<=4                   // myriadal, millenary, etc.
6071   Int  est;                        // estimated quotient
6072 #endif
6073 
6074   maxC=c+alength;                  // A is usually the longer
6075   minC=c+blength;                  // .. and B the shorter
6076   if (bshift!=0) {                 // B is shifted; low As copy across
6077     minC+=bshift;
6078     // if in place [common], skip copy unless there's a gap [rare]
6079     if (a==c && bshift<=alength) {
6080       c+=bshift;
6081       a+=bshift;
6082       }
6083      else for (; c<clsu+bshift; a++, c++) {  // copy needed
6084       if (a<alsu+alength) *c=*a;
6085        else *c=0;
6086       }
6087     }
6088   if (minC>maxC) { // swap
6089     Unit *hold=minC;
6090     minC=maxC;
6091     maxC=hold;
6092     }
6093 
6094   // For speed, do the addition as two loops; the first where both A
6095   // and B contribute, and the second (if necessary) where only one or
6096   // other of the numbers contribute.
6097   // Carry handling is the same (i.e., duplicated) in each case.
6098   for (; c<minC; c++) {
6099     carry+=*a;
6100     a++;
6101     carry+=((eInt)*b)*m;                // [special-casing m=1/-1
6102     b++;                                // here is not a win]
6103     // here carry is new Unit of digits; it could be +ve or -ve
6104     if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6105       *c=(Unit)carry;
6106       carry=0;
6107       continue;
6108       }
6109 #if DECDPUN==4                           // use divide-by-multiply
6110       if (carry>=0) {
6111         est=(((ueInt)carry>>11)*53687)>>18;
6112         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6113         carry=est;                           // likely quotient [89%]
6114         if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6115         carry++;
6116         *c-=DECDPUNMAX+1;
6117         continue;
6118         }
6119       // negative case
6120       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6121       est=(((ueInt)carry>>11)*53687)>>18;
6122       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6123       carry=est-(DECDPUNMAX+1);              // correctly negative
6124       if (*c<DECDPUNMAX+1) continue;         // was OK
6125       carry++;
6126       *c-=DECDPUNMAX+1;
6127 #elif DECDPUN==3
6128       if (carry>=0) {
6129         est=(((ueInt)carry>>3)*16777)>>21;
6130         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6131         carry=est;                           // likely quotient [99%]
6132         if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6133         carry++;
6134         *c-=DECDPUNMAX+1;
6135         continue;
6136         }
6137       // negative case
6138       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6139       est=(((ueInt)carry>>3)*16777)>>21;
6140       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6141       carry=est-(DECDPUNMAX+1);              // correctly negative
6142       if (*c<DECDPUNMAX+1) continue;         // was OK
6143       carry++;
6144       *c-=DECDPUNMAX+1;
6145 #elif DECDPUN<=2
6146       // Can use QUOT10 as carry <= 4 digits
6147       if (carry>=0) {
6148         est=QUOT10(carry, DECDPUN);
6149         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6150         carry=est;                           // quotient
6151         continue;
6152         }
6153       // negative case
6154       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6155       est=QUOT10(carry, DECDPUN);
6156       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6157       carry=est-(DECDPUNMAX+1);              // correctly negative
6158 #else
6159       // remainder operator is undefined if negative, so must test
6160       if ((ueInt)carry<(DECDPUNMAX+1)*2) {   // fastpath carry +1
6161         *c=(Unit)(carry-(DECDPUNMAX+1));     // [helps additions]
6162         carry=1;
6163         continue;
6164         }
6165       if (carry>=0) {
6166         *c=(Unit)(carry%(DECDPUNMAX+1));
6167         carry=carry/(DECDPUNMAX+1);
6168         continue;
6169         }
6170       // negative case
6171       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6172       *c=(Unit)(carry%(DECDPUNMAX+1));
6173       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6174 #endif
6175     } // c
6176 
6177   // now may have one or other to complete
6178   // [pretest to avoid loop setup/shutdown]
6179   if (c<maxC) for (; c<maxC; c++) {
6180     if (a<alsu+alength) {               // still in A
6181       carry+=*a;
6182       a++;
6183       }
6184      else {                             // inside B
6185       carry+=((eInt)*b)*m;
6186       b++;
6187       }
6188     // here carry is new Unit of digits; it could be +ve or -ve and
6189     // magnitude up to DECDPUNMAX squared
6190     if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6191       *c=(Unit)carry;
6192       carry=0;
6193       continue;
6194       }
6195     // result for this unit is negative or >DECDPUNMAX
6196 #if DECDPUN==4                           // use divide-by-multiply
6197       if (carry>=0) {
6198         est=(((ueInt)carry>>11)*53687)>>18;
6199         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6200         carry=est;                           // likely quotient [79.7%]
6201         if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6202         carry++;
6203         *c-=DECDPUNMAX+1;
6204         continue;
6205         }
6206       // negative case
6207       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6208       est=(((ueInt)carry>>11)*53687)>>18;
6209       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6210       carry=est-(DECDPUNMAX+1);              // correctly negative
6211       if (*c<DECDPUNMAX+1) continue;         // was OK
6212       carry++;
6213       *c-=DECDPUNMAX+1;
6214 #elif DECDPUN==3
6215       if (carry>=0) {
6216         est=(((ueInt)carry>>3)*16777)>>21;
6217         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6218         carry=est;                           // likely quotient [99%]
6219         if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6220         carry++;
6221         *c-=DECDPUNMAX+1;
6222         continue;
6223         }
6224       // negative case
6225       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6226       est=(((ueInt)carry>>3)*16777)>>21;
6227       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6228       carry=est-(DECDPUNMAX+1);              // correctly negative
6229       if (*c<DECDPUNMAX+1) continue;         // was OK
6230       carry++;
6231       *c-=DECDPUNMAX+1;
6232 #elif DECDPUN<=2
6233       if (carry>=0) {
6234         est=QUOT10(carry, DECDPUN);
6235         *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6236         carry=est;                           // quotient
6237         continue;
6238         }
6239       // negative case
6240       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6241       est=QUOT10(carry, DECDPUN);
6242       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6243       carry=est-(DECDPUNMAX+1);              // correctly negative
6244 #else
6245       if ((ueInt)carry<(DECDPUNMAX+1)*2){    // fastpath carry 1
6246         *c=(Unit)(carry-(DECDPUNMAX+1));
6247         carry=1;
6248         continue;
6249         }
6250       // remainder operator is undefined if negative, so must test
6251       if (carry>=0) {
6252         *c=(Unit)(carry%(DECDPUNMAX+1));
6253         carry=carry/(DECDPUNMAX+1);
6254         continue;
6255         }
6256       // negative case
6257       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6258       *c=(Unit)(carry%(DECDPUNMAX+1));
6259       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6260 #endif
6261     } // c
6262 
6263   // OK, all A and B processed; might still have carry or borrow
6264   // return number of Units in the result, negated if a borrow
6265   if (carry==0) return c-clsu;     // no carry, so no more to do
6266   if (carry>0) {                   // positive carry
6267     *c=(Unit)carry;                // place as new unit
6268     c++;                           // ..
6269     return c-clsu;
6270     }
6271   // -ve carry: it's a borrow; complement needed
6272   add=1;                           // temporary carry...
6273   for (c=clsu; c<maxC; c++) {
6274     add=DECDPUNMAX+add-*c;
6275     if (add<=DECDPUNMAX) {
6276       *c=(Unit)add;
6277       add=0;
6278       }
6279      else {
6280       *c=0;
6281       add=1;
6282       }
6283     }
6284   // add an extra unit iff it would be non-zero
6285   if ((add-carry-1)!=0) {
6286     *c=(Unit)(add-carry-1);
6287     c++;                      // interesting, include it
6288     }
6289   return clsu-c;              // -ve result indicates borrowed
6290   } // decUnitAddSub
6291 
6292 /* ------------------------------------------------------------------ */
6293 /* decTrim -- trim trailing zeros or normalize                        */
6294 /*                                                                    */
6295 /*   dn is the number to trim or normalize                            */
6296 /*   set is the context to use to check for clamp                     */
6297 /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6298 /*   noclamp is 1 to unconditional (unclamped) trim                   */
6299 /*   dropped returns the number of discarded trailing zeros           */
6300 /*   returns dn                                                       */
6301 /*                                                                    */
6302 /* If clamp is set in the context then the number of zeros trimmed    */
6303 /* may be limited if the exponent is high.                            */
6304 /* All fields are updated as required.  This is a utility operation,  */
6305 /* so special values are unchanged and no error is possible.          */
6306 /* ------------------------------------------------------------------ */
6307 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
     /* [previous][next][first][last][top][bottom][index][help] */
6308                            Flag noclamp, Int *dropped) {
6309   Int   d, exp;                    // work
6310   uInt  cut;                       // ..
6311   Unit  *up;                       // -> current Unit
6312 
6313   *dropped=0;                           // assume no zeros dropped
6314   if ((dn->bits & DECSPECIAL)           // fast exit if special ..
6315     || (*dn->lsu & 0x01)) return dn;    // .. or odd
6316   if (ISZERO(dn)) {                     // .. or 0
6317     dn->exponent=0;                     // (sign is preserved)
6318     return dn;
6319     }
6320 
6321   // have a finite number which is even
6322   exp=dn->exponent;
6323   cut=1;                           // digit (1-DECDPUN) in Unit
6324   up=dn->lsu;                      // -> current Unit
6325   for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]
6326     // slice by powers
6327 #if DECDPUN<=4
6328       uInt quot=QUOT10(*up, cut);
6329       if ((*up-quot*powers[cut])!=0) break;  // found non-0 digit
6330 #else
6331       if (*up%powers[cut]!=0) break;         // found non-0 digit
6332 #endif
6333     // have a trailing 0
6334     if (!all) {                    // trimming
6335       // [if exp>0 then all trailing 0s are significant for trim]
6336       if (exp<=0) {                // if digit might be significant
6337         if (exp==0) break;         // then quit
6338         exp++;                     // next digit might be significant
6339         }
6340       }
6341     cut++;                         // next power
6342     if (cut>DECDPUN) {             // need new Unit
6343       up++;
6344       cut=1;
6345       }
6346     } // d
6347   if (d==0) return dn;             // none to drop
6348 
6349   // may need to limit drop if clamping
6350   if (set->clamp && !noclamp) {
6351     Int maxd=set->emax-set->digits+1-dn->exponent;
6352     if (maxd<=0) return dn;        // nothing possible
6353     if (d>maxd) d=maxd;
6354     }
6355 
6356   // effect the drop
6357   decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6358   dn->exponent+=d;                 // maintain numerical value
6359   dn->digits-=d;                   // new length
6360   *dropped=d;                      // report the count
6361   return dn;
6362   } // decTrim
6363 
6364 /* ------------------------------------------------------------------ */
6365 /* decReverse -- reverse a Unit array in place                        */
6366 /*                                                                    */
6367 /*   ulo    is the start of the array                                 */
6368 /*   uhi    is the end of the array (highest Unit to include)         */
6369 /*                                                                    */
6370 /* The units ulo through uhi are reversed in place (if the number     */
6371 /* of units is odd, the middle one is untouched).  Note that the      */
6372 /* digit(s) in each unit are unaffected.                              */
6373 /* ------------------------------------------------------------------ */
6374 static void decReverse(Unit *ulo, Unit *uhi) {
     /* [previous][next][first][last][top][bottom][index][help] */
6375   Unit temp;
6376   for (; ulo<uhi; ulo++, uhi--) {
6377     temp=*ulo;
6378     *ulo=*uhi;
6379     *uhi=temp;
6380     }
6381   return;
6382   } // decReverse
6383 
6384 /* ------------------------------------------------------------------ */
6385 /* decShiftToMost -- shift digits in array towards most significant   */
6386 /*                                                                    */
6387 /*   uar    is the array                                              */
6388 /*   digits is the count of digits in use in the array                */
6389 /*   shift  is the number of zeros to pad with (least significant);   */
6390 /*     it must be zero or positive                                    */
6391 /*                                                                    */
6392 /*   returns the new length of the integer in the array, in digits    */
6393 /*                                                                    */
6394 /* No overflow is permitted (that is, the uar array must be known to  */
6395 /* be large enough to hold the result, after shifting).               */
6396 /* ------------------------------------------------------------------ */
6397 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
     /* [previous][next][first][last][top][bottom][index][help] */
6398   Unit  *target, *source, *first;  // work
6399   Int   cut;                       // odd 0's to add
6400   uInt  next;                      // work
6401 
6402   if (shift==0) return digits;     // [fastpath] nothing to do
6403   if ((digits+shift)<=DECDPUN) {   // [fastpath] single-unit case
6404     *uar=(Unit)(*uar*powers[shift]);
6405     return digits+shift;
6406     }
6407 
6408   next=0;                          // all paths
6409   source=uar+D2U(digits)-1;        // where msu comes from
6410   target=source+D2U(shift);        // where upper part of first cut goes
6411   cut=DECDPUN-MSUDIGITS(shift);    // where to slice
6412   if (cut==0) {                    // unit-boundary case
6413     for (; source>=uar; source--, target--) *target=*source;
6414     }
6415    else {
6416     first=uar+D2U(digits+shift)-1; // where msu of source will end up
6417     for (; source>=uar; source--, target--) {
6418       // split the source Unit and accumulate remainder for next
6419 #if DECDPUN<=4
6420         uInt quot=QUOT10(*source, cut);
6421         uInt rem=*source-quot*powers[cut];
6422         next+=quot;
6423 #else
6424         uInt rem=*source%powers[cut];
6425         next+=*source/powers[cut];
6426 #endif
6427       if (target<=first) *target=(Unit)next;   // write to target iff valid
6428       next=rem*powers[DECDPUN-cut];            // save remainder for next Unit
6429       }
6430     } // shift-move
6431 
6432   // propagate any partial unit to one below and clear the rest
6433   for (; target>=uar; target--) {
6434     *target=(Unit)next;
6435     next=0;
6436     }
6437   return digits+shift;
6438   } // decShiftToMost
6439 
6440 /* ------------------------------------------------------------------ */
6441 /* decShiftToLeast -- shift digits in array towards least significant */
6442 /*                                                                    */
6443 /*   uar   is the array                                               */
6444 /*   units is length of the array, in units                           */
6445 /*   shift is the number of digits to remove from the lsu end; it     */
6446 /*     must be zero or positive and <= than units*DECDPUN.            */
6447 /*                                                                    */
6448 /*   returns the new length of the integer in the array, in units     */
6449 /*                                                                    */
6450 /* Removed digits are discarded (lost).  Units not required to hold   */
6451 /* the final result are unchanged.                                    */
6452 /* ------------------------------------------------------------------ */
6453 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
     /* [previous][next][first][last][top][bottom][index][help] */
6454   Unit  *target, *up;              // work
6455   Int   cut, count;                // work
6456   Int   quot, rem;                 // for division
6457 
6458   if (shift==0) return units;      // [fastpath] nothing to do
6459   if (shift==units*DECDPUN) {      // [fastpath] little to do
6460     *uar=0;                        // all digits cleared gives zero
6461     return 1;                      // leaves just the one
6462     }
6463 
6464   target=uar;                      // both paths
6465   cut=MSUDIGITS(shift);
6466   if (cut==DECDPUN) {              // unit-boundary case; easy
6467     up=uar+D2U(shift);
6468     for (; up<uar+units; target++, up++) *target=*up;
6469     return target-uar;
6470     }
6471 
6472   // messier
6473   up=uar+D2U(shift-cut);           // source; correct to whole Units
6474   count=units*DECDPUN-shift;       // the maximum new length
6475 #if DECDPUN<=4
6476     quot=QUOT10(*up, cut);
6477 #else
6478     quot=*up/powers[cut];
6479 #endif
6480   for (; ; target++) {
6481     *target=(Unit)quot;
6482     count-=(DECDPUN-cut);
6483     if (count<=0) break;
6484     up++;
6485     quot=*up;
6486 #if DECDPUN<=4
6487       quot=QUOT10(quot, cut);
6488       rem=*up-quot*powers[cut];
6489 #else
6490       rem=quot%powers[cut];
6491       quot=quot/powers[cut];
6492 #endif
6493     *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6494     count-=cut;
6495     if (count<=0) break;
6496     }
6497   return target-uar+1;
6498   } // decShiftToLeast
6499 
6500 #if DECSUBSET
6501 /* ------------------------------------------------------------------ */
6502 /* decRoundOperand -- round an operand  [used for subset only]        */
6503 /*                                                                    */
6504 /*   dn is the number to round (dn->digits is > set->digits)          */
6505 /*   set is the relevant context                                      */
6506 /*   status is the status accumulator                                 */
6507 /*                                                                    */
6508 /*   returns an allocated decNumber with the rounded result.          */
6509 /*                                                                    */
6510 /* lostDigits and other status may be set by this.                    */
6511 /*                                                                    */
6512 /* Since the input is an operand, it must not be modified.            */
6513 /* Instead, return an allocated decNumber, rounded as required.       */
6514 /* It is the caller's responsibility to free the allocated storage.   */
6515 /*                                                                    */
6516 /* If no storage is available then the result cannot be used, so NULL */
6517 /* is returned.                                                       */
6518 /* ------------------------------------------------------------------ */
6519 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
     /* [previous][next][first][last][top][bottom][index][help] */
6520                                   uInt *status) {
6521   decNumber *res;                       // result structure
6522   uInt newstatus=0;                     // status from round
6523   Int  residue=0;                       // rounding accumulator
6524 
6525   // Allocate storage for the returned decNumber, big enough for the
6526   // length specified by the context
6527   res=(decNumber *)malloc(sizeof(decNumber)
6528                           +(D2U(set->digits)-1)*sizeof(Unit));
6529   if (res==NULL) {
6530     *status|=DEC_Insufficient_storage;
6531     return NULL;
6532     }
6533   decCopyFit(res, dn, set, &residue, &newstatus);
6534   decApplyRound(res, set, residue, &newstatus);
6535 
6536   // If that set Inexact then "lost digits" is raised...
6537   if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6538   *status|=newstatus;
6539   return res;
6540   } // decRoundOperand
6541 #endif
6542 
6543 /* ------------------------------------------------------------------ */
6544 /* decCopyFit -- copy a number, truncating the coefficient if needed  */
6545 /*                                                                    */
6546 /*   dest is the target decNumber                                     */
6547 /*   src  is the source decNumber                                     */
6548 /*   set is the context [used for length (digits) and rounding mode]  */
6549 /*   residue is the residue accumulator                               */
6550 /*   status contains the current status to be updated                 */
6551 /*                                                                    */
6552 /* (dest==src is allowed and will be a no-op if fits)                 */
6553 /* All fields are updated as required.                                */
6554 /* ------------------------------------------------------------------ */
6555 static void decCopyFit(decNumber *dest, const decNumber *src,
     /* [previous][next][first][last][top][bottom][index][help] */
6556                        decContext *set, Int *residue, uInt *status) {
6557   dest->bits=src->bits;
6558   dest->exponent=src->exponent;
6559   decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6560   } // decCopyFit
6561 
6562 /* ------------------------------------------------------------------ */
6563 /* decSetCoeff -- set the coefficient of a number                     */
6564 /*                                                                    */
6565 /*   dn    is the number whose coefficient array is to be set.        */
6566 /*         It must have space for set->digits digits                  */
6567 /*   set   is the context [for size]                                  */
6568 /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6569 /*   len   is digits in the source coefficient [may be dn->digits]    */
6570 /*   residue is the residue accumulator.  This has values as in       */
6571 /*         decApplyRound, and will be unchanged unless the            */
6572 /*         target size is less than len.  In this case, the           */
6573 /*         coefficient is truncated and the residue is updated to     */
6574 /*         reflect the previous residue and the dropped digits.       */
6575 /*   status is the status accumulator, as usual                       */
6576 /*                                                                    */
6577 /* The coefficient may already be in the number, or it can be an      */
6578 /* external intermediate array.  If it is in the number, lsu must ==  */
6579 /* dn->lsu and len must == dn->digits.                                */
6580 /*                                                                    */
6581 /* Note that the coefficient length (len) may be < set->digits, and   */
6582 /* in this case this merely copies the coefficient (or is a no-op     */
6583 /* if dn->lsu==lsu).                                                  */
6584 /*                                                                    */
6585 /* Note also that (only internally, from decQuantizeOp and            */
6586 /* decSetSubnormal) the value of set->digits may be less than one,    */
6587 /* indicating a round to left.  This routine handles that case        */
6588 /* correctly; caller ensures space.                                   */
6589 /*                                                                    */
6590 /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6591 /* updated as necessary.   dn->bits (sign) is unchanged.              */
6592 /*                                                                    */
6593 /* DEC_Rounded status is set if any digits are discarded.             */
6594 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6595 /*                       incoming residue was non-0 (implies rounded) */
6596 /* ------------------------------------------------------------------ */
6597 // mapping array: maps 0-9 to canonical residues, so that a residue
6598 // can be adjusted in the range [-1, +1] and achieve correct rounding
6599 //                             0  1  2  3  4  5  6  7  8  9
6600 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6601 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
     /* [previous][next][first][last][top][bottom][index][help] */
6602                         Int len, Int *residue, uInt *status) {
6603   Int   discard;              // number of digits to discard
6604   uInt  cut;                  // cut point in Unit
6605   const Unit *up;             // work
6606   Unit  *target;              // ..
6607   Int   count;                // ..
6608 #if DECDPUN<=4
6609   uInt  temp;                 // ..
6610 #endif
6611 
6612   discard=len-set->digits;    // digits to discard
6613   if (discard<=0) {           // no digits are being discarded
6614     if (dn->lsu!=lsu) {       // copy needed
6615       // copy the coefficient array to the result number; no shift needed
6616       count=len;              // avoids D2U
6617       up=lsu;
6618       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6619         *target=*up;
6620       dn->digits=len;         // set the new length
6621       }
6622     // dn->exponent and residue are unchanged, record any inexactitude
6623     if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6624     return;
6625     }
6626 
6627   // some digits must be discarded ...
6628   dn->exponent+=discard;      // maintain numerical value
6629   *status|=DEC_Rounded;       // accumulate Rounded status
6630   if (*residue>1) *residue=1; // previous residue now to right, so reduce
6631 
6632   if (discard>len) {          // everything, +1, is being discarded
6633     // guard digit is 0
6634     // residue is all the number [NB could be all 0s]
6635     if (*residue<=0) {        // not already positive
6636       count=len;              // avoids D2U
6637       for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0
6638         *residue=1;
6639         break;                // no need to check any others
6640         }
6641       }
6642     if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
6643     *dn->lsu=0;               // coefficient will now be 0
6644     dn->digits=1;             // ..
6645     return;
6646     } // total discard
6647 
6648   // partial discard [most common case]
6649   // here, at least the first (most significant) discarded digit exists
6650 
6651   // spin up the number, noting residue during the spin, until get to
6652   // the Unit with the first discarded digit.  When reach it, extract
6653   // it and remember its position
6654   count=0;
6655   for (up=lsu;; up++) {
6656     count+=DECDPUN;
6657     if (count>=discard) break; // full ones all checked
6658     if (*up!=0) *residue=1;
6659     } // up
6660 
6661   // here up -> Unit with first discarded digit
6662   cut=discard-(count-DECDPUN)-1;
6663   if (cut==DECDPUN-1) {       // unit-boundary case (fast)
6664     Unit half=(Unit)powers[DECDPUN]>>1;
6665     // set residue directly
6666     if (*up>=half) {
6667       if (*up>half) *residue=7;
6668       else *residue+=5;       // add sticky bit
6669       }
6670      else { // <half
6671       if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]
6672       }
6673     if (set->digits<=0) {     // special for Quantize/Subnormal :-(
6674       *dn->lsu=0;             // .. result is 0
6675       dn->digits=1;           // ..
6676       }
6677      else {                   // shift to least
6678       count=set->digits;      // now digits to end up with
6679       dn->digits=count;       // set the new length
6680       up++;                   // move to next
6681       // on unit boundary, so shift-down copy loop is simple
6682       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6683         *target=*up;
6684       }
6685     } // unit-boundary case
6686 
6687    else { // discard digit is in low digit(s), and not top digit
6688     uInt  discard1;                // first discarded digit
6689     uInt  quot, rem;               // for divisions
6690     if (cut==0) quot=*up;          // is at bottom of unit
6691      else /* cut>0 */ {            // it's not at bottom of unit
6692 #if DECDPUN<=4
6693         quot=QUOT10(*up, cut);
6694         rem=*up-quot*powers[cut];
6695 #else
6696         rem=*up%powers[cut];
6697         quot=*up/powers[cut];
6698 #endif
6699       if (rem!=0) *residue=1;
6700       }
6701     // discard digit is now at bottom of quot
6702 #if DECDPUN<=4
6703       temp=(quot*6554)>>16;        // fast /10
6704       // Vowels algorithm here not a win (9 instructions)
6705       discard1=quot-X10(temp);
6706       quot=temp;
6707 #else
6708       discard1=quot%10;
6709       quot=quot/10;
6710 #endif
6711     // here, discard1 is the guard digit, and residue is everything
6712     // else [use mapping array to accumulate residue safely]
6713     *residue+=resmap[discard1];
6714     cut++;                         // update cut
6715     // here: up -> Unit of the array with bottom digit
6716     //       cut is the division point for each Unit
6717     //       quot holds the uncut high-order digits for the current unit
6718     if (set->digits<=0) {          // special for Quantize/Subnormal :-(
6719       *dn->lsu=0;                  // .. result is 0
6720       dn->digits=1;                // ..
6721       }
6722      else {                        // shift to least needed
6723       count=set->digits;           // now digits to end up with
6724       dn->digits=count;            // set the new length
6725       // shift-copy the coefficient array to the result number
6726       for (target=dn->lsu; ; target++) {
6727         *target=(Unit)quot;
6728         count-=(DECDPUN-cut);
6729         if (count<=0) break;
6730         up++;
6731         quot=*up;
6732 #if DECDPUN<=4
6733           quot=QUOT10(quot, cut);
6734           rem=*up-quot*powers[cut];
6735 #else
6736           rem=quot%powers[cut];
6737           quot=quot/powers[cut];
6738 #endif
6739         *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6740         count-=cut;
6741         if (count<=0) break;
6742         } // shift-copy loop
6743       } // shift to least
6744     } // not unit boundary
6745 
6746   if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
6747   return;
6748   } // decSetCoeff
6749 
6750 /* ------------------------------------------------------------------ */
6751 /* decApplyRound -- apply pending rounding to a number                */
6752 /*                                                                    */
6753 /*   dn    is the number, with space for set->digits digits           */
6754 /*   set   is the context [for size and rounding mode]                */
6755 /*   residue indicates pending rounding, being any accumulated        */
6756 /*         guard and sticky information.  It may be:                  */
6757 /*         6-9: rounding digit is >5                                  */
6758 /*         5:   rounding digit is exactly half-way                    */
6759 /*         1-4: rounding digit is <5 and >0                           */
6760 /*         0:   the coefficient is exact                              */
6761 /*        -1:   as 1, but the hidden digits are subtractive, that     */
6762 /*              is, of the opposite sign to dn.  In this case the     */
6763 /*              coefficient must be non-0.  This case occurs when     */
6764 /*              subtracting a small number (which can be reduced to   */
6765 /*              a sticky bit); see decAddOp.                          */
6766 /*   status is the status accumulator, as usual                       */
6767 /*                                                                    */
6768 /* This routine applies rounding while keeping the length of the      */
6769 /* coefficient constant.  The exponent and status are unchanged       */
6770 /* except if:                                                         */
6771 /*                                                                    */
6772 /*   -- the coefficient was increased and is all nines (in which      */
6773 /*      case Overflow could occur, and is handled directly here so    */
6774 /*      the caller does not need to re-test for overflow)             */
6775 /*                                                                    */
6776 /*   -- the coefficient was decreased and becomes all nines (in which */
6777 /*      case Underflow could occur, and is also handled directly).    */
6778 /*                                                                    */
6779 /* All fields in dn are updated as required.                          */
6780 /*                                                                    */
6781 /* ------------------------------------------------------------------ */
6782 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
     /* [previous][next][first][last][top][bottom][index][help] */
6783                           uInt *status) {
6784   Int  bump;                  // 1 if coefficient needs to be incremented
6785                               // -1 if coefficient needs to be decremented
6786 
6787   if (residue==0) return;     // nothing to apply
6788 
6789   bump=0;                     // assume a smooth ride
6790 
6791   // now decide whether, and how, to round, depending on mode
6792   switch (set->round) {
6793     case DEC_ROUND_05UP: {    // round zero or five up (for reround)
6794       // This is the same as DEC_ROUND_DOWN unless there is a
6795       // positive residue and the lsd of dn is 0 or 5, in which case
6796       // it is bumped; when residue is <0, the number is therefore
6797       // bumped down unless the final digit was 1 or 6 (in which
6798       // case it is bumped down and then up -- a no-op)
6799       Int lsd5=*dn->lsu%5;     // get lsd and quintate
6800       if (residue<0 && lsd5!=1) bump=-1;
6801        else if (residue>0 && lsd5==0) bump=1;
6802       // [bump==1 could be applied directly; use common path for clarity]
6803       break;} // r-05
6804 
6805     case DEC_ROUND_DOWN: {
6806       // no change, except if negative residue
6807       if (residue<0) bump=-1;
6808       break;} // r-d
6809 
6810     case DEC_ROUND_HALF_DOWN: {
6811       if (residue>5) bump=1;
6812       break;} // r-h-d
6813 
6814     case DEC_ROUND_HALF_EVEN: {
6815       if (residue>5) bump=1;            // >0.5 goes up
6816        else if (residue==5) {           // exactly 0.5000...
6817         // 0.5 goes up iff [new] lsd is odd
6818         if (*dn->lsu & 0x01) bump=1;
6819         }
6820       break;} // r-h-e
6821 
6822     case DEC_ROUND_HALF_UP: {
6823       if (residue>=5) bump=1;
6824       break;} // r-h-u
6825 
6826     case DEC_ROUND_UP: {
6827       if (residue>0) bump=1;
6828       break;} // r-u
6829 
6830     case DEC_ROUND_CEILING: {
6831       // same as _UP for positive numbers, and as _DOWN for negatives
6832       // [negative residue cannot occur on 0]
6833       if (decNumberIsNegative(dn)) {
6834         if (residue<0) bump=-1;
6835         }
6836        else {
6837         if (residue>0) bump=1;
6838         }
6839       break;} // r-c
6840 
6841     case DEC_ROUND_FLOOR: {
6842       // same as _UP for negative numbers, and as _DOWN for positive
6843       // [negative residue cannot occur on 0]
6844       if (!decNumberIsNegative(dn)) {
6845         if (residue<0) bump=-1;
6846         }
6847        else {
6848         if (residue>0) bump=1;
6849         }
6850       break;} // r-f
6851 
6852     default: {      // e.g., DEC_ROUND_MAX
6853       *status|=DEC_Invalid_context;
6854       break;}
6855     } // switch
6856 
6857   // now bump the number, up or down, if need be
6858   if (bump==0) return;                       // no action required
6859 
6860   // Simply use decUnitAddSub unless bumping up and the number is
6861   // all nines.  In this special case set to 100... explicitly
6862   // and adjust the exponent by one (as otherwise could overflow
6863   // the array)
6864   // Similarly handle all-nines result if bumping down.
6865   if (bump>0) {
6866     Unit *up;                                // work
6867     uInt count=dn->digits;                   // digits to be checked
6868     for (up=dn->lsu; ; up++) {
6869       if (count<=DECDPUN) {
6870         // this is the last Unit (the msu)
6871         if (*up!=powers[count]-1) break;     // not still 9s
6872         // here if it, too, is all nines
6873         *up=(Unit)powers[count-1];           // here 999 -> 100 etc.
6874         for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0
6875         dn->exponent++;                      // and bump exponent
6876         // [which, very rarely, could cause Overflow...]
6877         if ((dn->exponent+dn->digits)>set->emax+1) {
6878           decSetOverflow(dn, set, status);
6879           }
6880         return;                              // done
6881         }
6882       // a full unit to check, with more to come
6883       if (*up!=DECDPUNMAX) break;            // not still 9s
6884       count-=DECDPUN;
6885       } // up
6886     } // bump>0
6887    else {                                    // -1
6888     // here checking for a pre-bump of 1000... (leading 1, all
6889     // other digits zero)
6890     Unit *up, *sup;                          // work
6891     uInt count=dn->digits;                   // digits to be checked
6892     for (up=dn->lsu; ; up++) {
6893       if (count<=DECDPUN) {
6894         // this is the last Unit (the msu)
6895         if (*up!=powers[count-1]) break;     // not 100..
6896         // here if have the 1000... case
6897         sup=up;                              // save msu pointer
6898         *up=(Unit)powers[count]-1;           // here 100 in msu -> 999
6899         // others all to all-nines, too
6900         for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
6901         dn->exponent--;                      // and bump exponent
6902 
6903         // iff the number was at the subnormal boundary (exponent=etiny)
6904         // then the exponent is now out of range, so it will in fact get
6905         // clamped to etiny and the final 9 dropped.
6906         // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,
6907         //        dn->exponent, set->digits);
6908         if (dn->exponent+1==set->emin-set->digits+1) { //-V584
6909           if (count==1 && dn->digits==1) *sup=0;  // here 9 -> 0[.9]
6910            else {
6911             *sup=(Unit)powers[count-1]-1;    // here 999.. in msu -> 99..
6912             dn->digits--;
6913             }
6914           dn->exponent++;
6915           *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
6916           }
6917         return;                              // done
6918         }
6919 
6920       // a full unit to check, with more to come
6921       if (*up!=0) break;                     // not still 0s
6922       count-=DECDPUN;
6923       } // up
6924 
6925     } // bump<0
6926 
6927   // Actual bump needed.  Do it.
6928   decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
6929   } // decApplyRound
6930 
6931 #if DECSUBSET
6932 /* ------------------------------------------------------------------ */
6933 /* decFinish -- finish processing a number                            */
6934 /*                                                                    */
6935 /*   dn is the number                                                 */
6936 /*   set is the context                                               */
6937 /*   residue is the rounding accumulator (as in decApplyRound)        */
6938 /*   status is the accumulator                                        */
6939 /*                                                                    */
6940 /* This finishes off the current number by:                           */
6941 /*    1. If not extended:                                             */
6942 /*       a. Converting a zero result to clean '0'                     */
6943 /*       b. Reducing positive exponents to 0, if would fit in digits  */
6944 /*    2. Checking for overflow and subnormals (always)                */
6945 /* Note this is just Finalize when no subset arithmetic.              */
6946 /* All fields are updated as required.                                */
6947 /* ------------------------------------------------------------------ */
6948 static void decFinish(decNumber *dn, decContext *set, Int *residue,
     /* [previous][next][first][last][top][bottom][index][help] */
6949                       uInt *status) {
6950   if (!set->extended) {
6951     if ISZERO(dn) {                // value is zero
6952       dn->exponent=0;              // clean exponent ..
6953       dn->bits=0;                  // .. and sign
6954       return;                      // no error possible
6955       }
6956     if (dn->exponent>=0) {         // non-negative exponent
6957       // >0; reduce to integer if possible
6958       if (set->digits >= (dn->exponent+dn->digits)) {
6959         dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
6960         dn->exponent=0;
6961         }
6962       }
6963     } // !extended
6964 
6965   decFinalize(dn, set, residue, status);
6966   } // decFinish
6967 #endif
6968 
6969 /* ------------------------------------------------------------------ */
6970 /* decFinalize -- final check, clamp, and round of a number           */
6971 /*                                                                    */
6972 /*   dn is the number                                                 */
6973 /*   set is the context                                               */
6974 /*   residue is the rounding accumulator (as in decApplyRound)        */
6975 /*   status is the status accumulator                                 */
6976 /*                                                                    */
6977 /* This finishes off the current number by checking for subnormal     */
6978 /* results, applying any pending rounding, checking for overflow,     */
6979 /* and applying any clamping.                                         */
6980 /* Underflow and overflow conditions are raised as appropriate.       */
6981 /* All fields are updated as required.                                */
6982 /* ------------------------------------------------------------------ */
6983 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
     /* [previous][next][first][last][top][bottom][index][help] */
6984                         uInt *status) {
6985   Int shift;                            // shift needed if clamping
6986   Int tinyexp=set->emin-dn->digits+1;   // precalculate subnormal boundary
6987 
6988   // Must be careful, here, when checking the exponent as the
6989   // adjusted exponent could overflow 31 bits [because it may already
6990   // be up to twice the expected].
6991 
6992   // First test for subnormal.  This must be done before any final
6993   // round as the result could be rounded to Nmin or 0.
6994   if (dn->exponent<=tinyexp) {          // prefilter
6995     Int comp;
6996     decNumber nmin;
6997     // A very nasty case here is dn == Nmin and residue<0
6998     if (dn->exponent<tinyexp) {
6999       // Go handle subnormals; this will apply round if needed.
7000       decSetSubnormal(dn, set, residue, status);
7001       return;
7002       }
7003     // Equals case: only subnormal if dn=Nmin and negative residue
7004     decNumberZero(&nmin);
7005     nmin.lsu[0]=1;
7006     nmin.exponent=set->emin;
7007     comp=decCompare(dn, &nmin, 1);                // (signless compare)
7008     if (comp==BADINT) {                           // oops
7009       *status|=DEC_Insufficient_storage;          // abandon...
7010       return;
7011       }
7012     if (*residue<0 && comp==0) {                  // neg residue and dn==Nmin
7013       decApplyRound(dn, set, *residue, status);   // might force down
7014       decSetSubnormal(dn, set, residue, status);
7015       return;
7016       }
7017     }
7018 
7019   // now apply any pending round (this could raise overflow).
7020   if (*residue!=0) decApplyRound(dn, set, *residue, status);
7021 
7022   // Check for overflow [redundant in the 'rare' case] or clamp
7023   if (dn->exponent<=set->emax-set->digits+1) return;   // neither needed
7024 
7025   // here when might have an overflow or clamp to do
7026   if (dn->exponent>set->emax-dn->digits+1) {           // too big
7027     decSetOverflow(dn, set, status);
7028     return;
7029     }
7030   // here when the result is normal but in clamp range
7031   if (!set->clamp) return;
7032 
7033   // here when need to apply the IEEE exponent clamp (fold-down)
7034   shift=dn->exponent-(set->emax-set->digits+1);
7035 
7036   // shift coefficient (if non-zero)
7037   if (!ISZERO(dn)) {
7038     dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7039     }
7040   dn->exponent-=shift;   // adjust the exponent to match
7041   *status|=DEC_Clamped;  // and record the dirty deed
7042   return;
7043   } // decFinalize
7044 
7045 /* ------------------------------------------------------------------ */
7046 /* decSetOverflow -- set number to proper overflow value              */
7047 /*                                                                    */
7048 /*   dn is the number (used for sign [only] and result)               */
7049 /*   set is the context [used for the rounding mode, etc.]            */
7050 /*   status contains the current status to be updated                 */
7051 /*                                                                    */
7052 /* This sets the sign of a number and sets its value to either        */
7053 /* Infinity or the maximum finite value, depending on the sign of     */
7054 /* dn and the rounding mode, following IEEE 754 rules.                */
7055 /* ------------------------------------------------------------------ */
7056 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
     /* [previous][next][first][last][top][bottom][index][help] */
7057   Flag needmax=0;                  // result is maximum finite value
7058   uByte sign=dn->bits&DECNEG;      // clean and save sign bit
7059 
7060   if (ISZERO(dn)) {                // zero does not overflow magnitude
7061     Int emax=set->emax;                      // limit value
7062     if (set->clamp) emax-=set->digits-1;     // lower if clamping
7063     if (dn->exponent>emax) {                 // clamp required
7064       dn->exponent=emax;
7065       *status|=DEC_Clamped;
7066       }
7067     return;
7068     }
7069 
7070   decNumberZero(dn);
7071   switch (set->round) {
7072     case DEC_ROUND_DOWN: {
7073       needmax=1; //-V1037          // never Infinity
7074       break;} // r-d
7075     case DEC_ROUND_05UP: {
7076       needmax=1; //-V1037          // never Infinity
7077       break;} // r-05
7078     case DEC_ROUND_CEILING: {
7079       if (sign) needmax=1;         // Infinity if non-negative
7080       break;} // r-c
7081     case DEC_ROUND_FLOOR: {
7082       if (!sign) needmax=1;        // Infinity if negative
7083       break;} // r-f
7084     default: break;                // Infinity in all other cases
7085     }
7086   if (needmax) {
7087     decSetMaxValue(dn, set);
7088     dn->bits=sign;                 // set sign
7089     }
7090    else dn->bits=sign|DECINF;      // Value is +/-Infinity
7091   *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7092   } // decSetOverflow
7093 
7094 /* ------------------------------------------------------------------ */
7095 /* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7096 /*                                                                    */
7097 /*   dn is the number to set                                          */
7098 /*   set is the context [used for digits and emax]                    */
7099 /*                                                                    */
7100 /* This sets the number to the maximum positive value.                */
7101 /* ------------------------------------------------------------------ */
7102 static void decSetMaxValue(decNumber *dn, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
7103   Unit *up;                        // work
7104   Int count=set->digits;           // nines to add
7105   dn->digits=count;
7106   // fill in all nines to set maximum value
7107   for (up=dn->lsu; ; up++) {
7108     if (count>DECDPUN) *up=DECDPUNMAX;  // unit full o'nines
7109      else {                             // this is the msu
7110       *up=(Unit)(powers[count]-1);
7111       break;
7112       }
7113     count-=DECDPUN;                // filled those digits
7114     } // up
7115   dn->bits=0;                      // + sign
7116   dn->exponent=set->emax-set->digits+1;
7117   } // decSetMaxValue
7118 
7119 /* ------------------------------------------------------------------ */
7120 /* decSetSubnormal -- process value whose exponent is <Emin           */
7121 /*                                                                    */
7122 /*   dn is the number (used as input as well as output; it may have   */
7123 /*         an allowed subnormal value, which may need to be rounded)  */
7124 /*   set is the context [used for the rounding mode]                  */
7125 /*   residue is any pending residue                                   */
7126 /*   status contains the current status to be updated                 */
7127 /*                                                                    */
7128 /* If subset mode, set result to zero and set Underflow flags.        */
7129 /*                                                                    */
7130 /* Value may be zero with a low exponent; this does not set Subnormal */
7131 /* but the exponent will be clamped to Etiny.                         */
7132 /*                                                                    */
7133 /* Otherwise ensure exponent is not out of range, and round as        */
7134 /* necessary.  Underflow is set if the result is Inexact.             */
7135 /* ------------------------------------------------------------------ */
7136 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
     /* [previous][next][first][last][top][bottom][index][help] */
7137                             uInt *status) {
7138   decContext workset;         // work
7139   Int        etiny, adjust;   // ..
7140 
7141 #if DECSUBSET
7142   // simple set to zero and 'hard underflow' for subset
7143   if (!set->extended) {
7144     decNumberZero(dn);
7145     // always full overflow
7146     *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7147     return;
7148     }
7149 #endif
7150 
7151   // Full arithmetic -- allow subnormals, rounded to minimum exponent
7152   // (Etiny) if needed
7153   etiny=set->emin-(set->digits-1);      // smallest allowed exponent
7154 
7155   if ISZERO(dn) {                       // value is zero
7156     // residue can never be non-zero here
7157     if (dn->exponent<etiny) {           // clamp required
7158       dn->exponent=etiny;
7159       *status|=DEC_Clamped;
7160       }
7161     return;
7162     }
7163 
7164   *status|=DEC_Subnormal;               // have a non-zero subnormal
7165   adjust=etiny-dn->exponent;            // calculate digits to remove
7166   if (adjust<=0) {                      // not out of range; unrounded
7167     // residue can never be non-zero here, except in the Nmin-residue
7168     // case (which is a subnormal result), so can take fast-path here
7169     // it may already be inexact (from setting the coefficient)
7170     if (*status&DEC_Inexact) *status|=DEC_Underflow;
7171     return;
7172     }
7173 
7174   // adjust>0, so need to rescale the result so exponent becomes Etiny
7175   // [this code is similar to that in rescale]
7176   workset=*set;                         // clone rounding, etc.
7177   workset.digits=dn->digits-adjust;     // set requested length
7178   workset.emin-=adjust;                 // and adjust emin to match
7179   // [note that the latter can be <1, here, similar to Rescale case]
7180   decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7181   decApplyRound(dn, &workset, *residue, status);
7182 
7183   // Use 754 default rule: Underflow is set iff Inexact
7184   // [independent of whether trapped]
7185   if (*status&DEC_Inexact) *status|=DEC_Underflow;
7186 
7187   // if rounded up a 999s case, exponent will be off by one; adjust
7188   // back if so [it will fit, because it was shortened earlier]
7189   if (dn->exponent>etiny) {
7190     dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7191     dn->exponent--;                     // (re)adjust the exponent.
7192     }
7193 
7194   // if rounded to zero, it is by definition clamped...
7195   if (ISZERO(dn)) *status|=DEC_Clamped;
7196   } // decSetSubnormal
7197 
7198 /* ------------------------------------------------------------------ */
7199 /* decCheckMath - check entry conditions for a math function          */
7200 /*                                                                    */
7201 /*   This checks the context and the operand                          */
7202 /*                                                                    */
7203 /*   rhs is the operand to check                                      */
7204 /*   set is the context to check                                      */
7205 /*   status is unchanged if both are good                             */
7206 /*                                                                    */
7207 /* returns non-zero if status is changed, 0 otherwise                 */
7208 /*                                                                    */
7209 /* Restrictions enforced:                                             */
7210 /*                                                                    */
7211 /*   digits, emax, and -emin in the context must be less than         */
7212 /*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7213 /*   non-zero.  Invalid_operation is set in the status if a           */
7214 /*   restriction is violated.                                         */
7215 /* ------------------------------------------------------------------ */
7216 static uInt decCheckMath(const decNumber *rhs, decContext *set,
     /* [previous][next][first][last][top][bottom][index][help] */
7217                          uInt *status) {
7218   uInt save=*status;                         // record
7219   if (set->digits>DEC_MAX_MATH
7220    || set->emax>DEC_MAX_MATH
7221    || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7222    else if ((rhs->digits>DEC_MAX_MATH
7223      || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7224      || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7225      && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7226   return (*status!=save);
7227   } // decCheckMath
7228 
7229 /* ------------------------------------------------------------------ */
7230 /* decGetInt -- get integer from a number                             */
7231 /*                                                                    */
7232 /*   dn is the number [which will not be altered]                     */
7233 /*                                                                    */
7234 /*   returns one of:                                                  */
7235 /*     BADINT if there is a non-zero fraction                         */
7236 /*     the converted integer                                          */
7237 /*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7238 /*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7239 /*                                                                    */
7240 /* This checks and gets a whole number from the input decNumber.      */
7241 /* The sign can be determined from dn by the caller when BIGEVEN or   */
7242 /* BIGODD is returned.                                                */
7243 /* ------------------------------------------------------------------ */
7244 static Int decGetInt(const decNumber *dn) {
     /* [previous][next][first][last][top][bottom][index][help] */
7245   Int  theInt;                          // result accumulator
7246   const Unit *up;                       // work
7247   Int  got;                             // digits (real or not) processed
7248   Int  ilength=dn->digits+dn->exponent; // integral length
7249   Flag neg=decNumberIsNegative(dn);     // 1 if -ve
7250 
7251   // The number must be an integer that fits in 10 digits
7252   // Assert, here, that 10 is enough for any rescale Etiny
7253 #if DEC_MAX_EMAX > 999999999
7254 # error GetInt may need updating [for Emax]
7255 #endif
7256 #if DEC_MIN_EMIN < -999999999
7257 # error GetInt may need updating [for Emin]
7258 #endif
7259   if (ISZERO(dn)) return 0;             // zeros are OK, with any exponent
7260 
7261   up=dn->lsu;                           // ready for lsu
7262   theInt=0;                             // ready to accumulate
7263   if (dn->exponent>=0) {                // relatively easy
7264     // no fractional part [usual]; allow for positive exponent
7265     got=dn->exponent;
7266     }
7267    else { // -ve exponent; some fractional part to check and discard
7268     Int count=-dn->exponent;            // digits to discard
7269     // spin up whole units until reach the Unit with the unit digit
7270     for (; count>=DECDPUN; up++) {
7271       if (*up!=0) return BADINT;        // non-zero Unit to discard
7272       count-=DECDPUN;
7273       }
7274     if (count==0) got=0;                // [a multiple of DECDPUN]
7275      else {                             // [not multiple of DECDPUN]
7276       Int rem;                          // work
7277       // slice off fraction digits and check for non-zero
7278 #if DECDPUN<=4
7279         theInt=QUOT10(*up, count);
7280         rem=*up-theInt*powers[count];
7281 #else
7282         rem=*up%powers[count];          // slice off discards
7283         theInt=*up/powers[count];
7284 #endif
7285       if (rem!=0) return BADINT;        // non-zero fraction
7286       // it looks good
7287       got=DECDPUN-count;                // number of digits so far
7288       up++;                             // ready for next
7289       }
7290     }
7291   // now it's known there's no fractional part
7292 
7293   // tricky code now, to accumulate up to 9.3 digits
7294   if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there
7295 
7296   if (ilength<11) {
7297     Int save=theInt;
7298     // collect any remaining unit(s)
7299     for (; got<ilength; up++) {
7300       theInt+=*up*powers[got];
7301       got+=DECDPUN;
7302       }
7303     if (ilength==10) {                  // need to check for wrap
7304       if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7305          // [that test also disallows the BADINT result case]
7306        else if (neg && theInt>1999999997) ilength=11;
7307        else if (!neg && theInt>999999999) ilength=11;
7308       if (ilength==11) theInt=save;     // restore correct low bit
7309       }
7310     }
7311 
7312   if (ilength>10) {                     // too big
7313     if (theInt&1) return BIGODD;        // bottom bit 1
7314     return BIGEVEN;                     // bottom bit 0
7315     }
7316 
7317   if (neg) theInt=-theInt;              // apply sign
7318   return theInt;
7319   } // decGetInt
7320 
7321 /* ------------------------------------------------------------------ */
7322 /* decDecap -- decapitate the coefficient of a number                 */
7323 /*                                                                    */
7324 /*   dn   is the number to be decapitated                             */
7325 /*   drop is the number of digits to be removed from the left of dn;  */
7326 /*     this must be <= dn->digits (if equal, the coefficient is       */
7327 /*     set to 0)                                                      */
7328 /*                                                                    */
7329 /* Returns dn; dn->digits will be <= the initial digits less drop     */
7330 /* (after removing drop digits there may be leading zero digits       */
7331 /* which will also be removed).  Only dn->lsu and dn->digits change.  */
7332 /* ------------------------------------------------------------------ */
7333 static decNumber *decDecap(decNumber *dn, Int drop) {
     /* [previous][next][first][last][top][bottom][index][help] */
7334   Unit *msu;                            // -> target cut point
7335   Int cut;                              // work
7336   if (drop>=dn->digits) {               // losing the whole thing
7337     dn->lsu[0]=0;
7338     dn->digits=1;
7339     return dn;
7340     }
7341   msu=dn->lsu+D2U(dn->digits-drop)-1;   // -> likely msu
7342   cut=MSUDIGITS(dn->digits-drop);       // digits to be in use in msu
7343   if (cut!=DECDPUN) *msu%=powers[cut];  // clear left digits
7344   // that may have left leading zero digits, so do a proper count...
7345   dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7346   return dn;
7347   } // decDecap
7348 
7349 /* ------------------------------------------------------------------ */
7350 /* decBiStr -- compare string with pairwise options                   */
7351 /*                                                                    */
7352 /*   targ is the string to compare                                    */
7353 /*   str1 is one of the strings to compare against (length may be 0)  */
7354 /*   str2 is the other; it must be the same length as str1            */
7355 /*                                                                    */
7356 /*   returns 1 if strings compare equal, (that is, it is the same     */
7357 /*   length as str1 and str2, and each character of targ is in either */
7358 /*   str1 or str2 in the corresponding position), or 0 otherwise      */
7359 /*                                                                    */
7360 /* This is used for generic caseless compare, including the awkward   */
7361 /* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7362 /*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7363 /* ------------------------------------------------------------------ */
7364 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
     /* [previous][next][first][last][top][bottom][index][help] */
7365   for (;;targ++, str1++, str2++) {
7366     if (*targ!=*str1 && *targ!=*str2) return 0;
7367     // *targ has a match in one (or both, if terminator)
7368     if (*targ=='\0') break;
7369     } // forever
7370   return 1;
7371   } // decBiStr
7372 
7373 /* ------------------------------------------------------------------ */
7374 /* decNaNs -- handle NaN operand or operands                          */
7375 /*                                                                    */
7376 /*   res     is the result number                                     */
7377 /*   lhs     is the first operand                                     */
7378 /*   rhs     is the second operand, or NULL if none                   */
7379 /*   context is used to limit payload length                          */
7380 /*   status  contains the current status                              */
7381 /*   returns res in case convenient                                   */
7382 /*                                                                    */
7383 /* Called when one or both operands is a NaN, and propagates the      */
7384 /* appropriate result to res.  When an sNaN is found, it is changed   */
7385 /* to a qNaN and Invalid operation is set.                            */
7386 /* ------------------------------------------------------------------ */
7387 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
     /* [previous][next][first][last][top][bottom][index][help] */
7388                            const decNumber *rhs, decContext *set,
7389                            uInt *status) {
7390   // This decision tree ends up with LHS being the source pointer,
7391   // and status updated if need be
7392   if (lhs->bits & DECSNAN)
7393     *status|=DEC_Invalid_operation | DEC_sNaN;
7394    else if (rhs==NULL);
7395    else if (rhs->bits & DECSNAN) {
7396     lhs=rhs;
7397     *status|=DEC_Invalid_operation | DEC_sNaN;
7398     }
7399    else if (lhs->bits & DECNAN);
7400    else lhs=rhs;
7401 
7402   // propagate the payload
7403   if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy
7404    else { // too long
7405     const Unit *ul;
7406     Unit *ur, *uresp1;
7407     // copy safe number of units, then decapitate
7408     res->bits=lhs->bits;                // need sign etc.
7409     uresp1=res->lsu+D2U(set->digits);
7410 #ifndef __clang_analyzer__
7411     for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7412 #endif /* ifndef __clang_analyzer__ */
7413     res->digits=D2U(set->digits)*DECDPUN;
7414     // maybe still too long
7415     if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7416     }
7417 
7418   res->bits&=~DECSNAN;        // convert any sNaN to NaN, while
7419   res->bits|=DECNAN;          // .. preserving sign
7420   res->exponent=0;            // clean exponent
7421                               // [coefficient was copied/decapitated]
7422   return res;
7423   } // decNaNs
7424 
7425 /* ------------------------------------------------------------------ */
7426 /* decStatus -- apply non-zero status                                 */
7427 /*                                                                    */
7428 /*   dn     is the number to set if error                             */
7429 /*   status contains the current status (not yet in context)          */
7430 /*   set    is the context                                            */
7431 /*                                                                    */
7432 /* If the status is an error status, the number is set to a NaN,      */
7433 /* unless the error was an overflow, divide-by-zero, or underflow,    */
7434 /* in which case the number will have already been set.               */
7435 /*                                                                    */
7436 /* The context status is then updated with the new status.  Note that */
7437 /* this may raise a signal, so control may never return from this     */
7438 /* routine (hence resources must be recovered before it is called).   */
7439 /* ------------------------------------------------------------------ */
7440 static void decStatus(decNumber *dn, uInt status, decContext *set) {
     /* [previous][next][first][last][top][bottom][index][help] */
7441   if (status & DEC_NaNs) {              // error status -> NaN
7442     // if cause was an sNaN, clear and propagate [NaN is already set up]
7443     if (status & DEC_sNaN) status&=~DEC_sNaN;
7444      else {
7445       decNumberZero(dn);                // other error: clean throughout
7446       dn->bits=DECNAN;                  // and make a quiet NaN
7447       }
7448     }
7449   (void)decContextSetStatus(set, status);     // [may not return]
7450   return;
7451   } // decStatus
7452 
7453 /* ------------------------------------------------------------------ */
7454 /* decGetDigits -- count digits in a Units array                      */
7455 /*                                                                    */
7456 /*   uar is the Unit array holding the number (this is often an       */
7457 /*          accumulator of some sort)                                 */
7458 /*   len is the length of the array in units [>=1]                    */
7459 /*                                                                    */
7460 /*   returns the number of (significant) digits in the array          */
7461 /*                                                                    */
7462 /* All leading zeros are excluded, except the last if the array has   */
7463 /* only zero Units.                                                   */
7464 /* ------------------------------------------------------------------ */
7465 // This may be called twice during some operations.
7466 static Int decGetDigits(Unit *uar, Int len) {
     /* [previous][next][first][last][top][bottom][index][help] */
7467   Unit *up=uar+(len-1);            // -> msu
7468   Int  digits=(len-1)*DECDPUN+1;   // possible digits excluding msu
7469 #if DECDPUN>4
7470   uInt const *pow;                 // work
7471 #endif
7472                                    // (at least 1 in final msu)
7473   for (; up>=uar; up--) {
7474     if (*up==0) {                  // unit is all 0s
7475       if (digits==1) break;        // a zero has one digit
7476       digits-=DECDPUN;             // adjust for 0 unit
7477       continue;}
7478     // found the first (most significant) non-zero Unit
7479 #if DECDPUN>1                  // not done yet
7480     if (*up<10) break;             // is 1-9
7481     digits++;
7482 # if DECDPUN>2                  // not done yet
7483     if (*up<100) break;            // is 10-99
7484     digits++;
7485 #  if DECDPUN>3                  // not done yet
7486     if (*up<1000) break;           // is 100-999
7487     digits++;
7488 #   if DECDPUN>4                  // count the rest ...
7489     for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7490 #   endif
7491 #  endif
7492 # endif
7493 #endif
7494     break;
7495     } // up
7496   return digits;
7497   } // decGetDigits

/* [previous][next][first][last][top][bottom][index][help] */