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

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