github.com/matrixorigin/matrixone@v0.7.0/cgo/external/decNumber/decNumber.c (about)

     1  /* ------------------------------------------------------------------ */
     2  /* Decimal Number arithmetic module                                   */
     3  /* ------------------------------------------------------------------ */
     4  /* Copyright (c) IBM Corporation, 2000, 2009.  All rights reserved.   */
     5  /*                                                                    */
     6  /* This software is made available under the terms of the             */
     7  /* ICU License -- ICU 1.8.1 and later.                                */
     8  /*                                                                    */
     9  /* The description and User's Guide ("The decNumber C Library") for   */
    10  /* this software is called decNumber.pdf.  This document is           */
    11  /* available, together with arithmetic and format specifications,     */
    12  /* testcases, and Web links, on the General Decimal Arithmetic page.  */
    13  /*                                                                    */
    14  /* Please send comments, suggestions, and corrections to the author:  */
    15  /*   mfc@uk.ibm.com                                                   */
    16  /*   Mike Cowlishaw, IBM Fellow                                       */
    17  /*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */
    18  /* ------------------------------------------------------------------ */
    19  /* This module comprises the routines for arbitrary-precision General */
    20  /* Decimal Arithmetic as defined in the specification which may be    */
    21  /* found on the General Decimal Arithmetic pages.  It implements both */
    22  /* the full ('extended') arithmetic and the simpler ('subset')        */
    23  /* arithmetic.                                                        */
    24  /*                                                                    */
    25  /* Usage notes:                                                       */
    26  /*                                                                    */
    27  /* 1. This code is ANSI C89 except:                                   */
    28  /*                                                                    */
    29  /*    a) C99 line comments (double forward slash) are used.  (Most C  */
    30  /*       compilers accept these.  If yours does not, a simple script  */
    31  /*       can be used to convert them to ANSI C comments.)             */
    32  /*                                                                    */
    33  /*    b) Types from C99 stdint.h are used.  If you do not have this   */
    34  /*       header file, see the User's Guide section of the decNumber   */
    35  /*       documentation; this lists the necessary definitions.         */
    36  /*                                                                    */
    37  /*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
    38  /*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
    39  /*       and DECDPUN<=4 (see documentation).                          */
    40  /*                                                                    */
    41  /*    The code also conforms to C99 restrictions; in particular,      */
    42  /*    strict aliasing rules are observed.                             */
    43  /*                                                                    */
    44  /* 2. The decNumber format which this library uses is optimized for   */
    45  /*    efficient processing of relatively short numbers; in particular */
    46  /*    it allows the use of fixed sized structures and minimizes copy  */
    47  /*    and move operations.  It does, however, support arbitrary       */
    48  /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
    49  /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
    50  /*    range -999,999,999 through 0).  Mathematical functions (for     */
    51  /*    example decNumberExp) as identified below are restricted more   */
    52  /*    tightly: digits, emax, and -emin in the context must be <=      */
    53  /*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
    54  /*    these bounds.                                                   */
    55  /*                                                                    */
    56  /* 3. Logical functions are further restricted; their operands must   */
    57  /*    be finite, positive, have an exponent of zero, and all digits   */
    58  /*    must be either 0 or 1.  The result will only contain digits     */
    59  /*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
    60  /*                                                                    */
    61  /* 4. Operands to operator functions are never modified unless they   */
    62  /*    are also specified to be the result number (which is always     */
    63  /*    permitted).  Other than that case, operands must not overlap.   */
    64  /*                                                                    */
    65  /* 5. Error handling: the type of the error is ORed into the status   */
    66  /*    flags in the current context (decContext structure).  The       */
    67  /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
    68  /*    flag in the decContext is set (is 1).                           */
    69  /*                                                                    */
    70  /*    It is the responsibility of the caller to clear the status      */
    71  /*    flags as required.                                              */
    72  /*                                                                    */
    73  /*    The result of any routine which returns a number will always    */
    74  /*    be a valid number (which may be a special value, such as an     */
    75  /*    Infinity or NaN).                                               */
    76  /*                                                                    */
    77  /* 6. The decNumber format is not an exchangeable concrete            */
    78  /*    representation as it comprises fields which may be machine-     */
    79  /*    dependent (packed or unpacked, or special length, for example). */
    80  /*    Canonical conversions to and from strings are provided; other   */
    81  /*    conversions are available in separate modules.                  */
    82  /*                                                                    */
    83  /* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
    84  /*    to 1 for extended operand checking (including NULL operands).   */
    85  /*    Results are undefined if a badly-formed structure (or a NULL    */
    86  /*    pointer to a structure) is provided, though with DECCHECK       */
    87  /*    enabled the operator routines are protected against exceptions. */
    88  /*    (Except if the result pointer is NULL, which is unrecoverable.) */
    89  /*                                                                    */
    90  /*    However, the routines will never cause exceptions if they are   */
    91  /*    given well-formed operands, even if the value of the operands   */
    92  /*    is inappropriate for the operation and DECCHECK is not set.     */
    93  /*    (Except for SIGFPE, as and where documented.)                   */
    94  /*                                                                    */
    95  /* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
    96  /* ------------------------------------------------------------------ */
    97  /* Implementation notes for maintenance of this module:               */
    98  /*                                                                    */
    99  /* 1. Storage leak protection:  Routines which use malloc are not     */
   100  /*    permitted to use return for fastpath or error exits (i.e.,      */
   101  /*    they follow strict structured programming conventions).         */
   102  /*    Instead they have a do{}while(0); construct surrounding the     */
   103  /*    code which is protected -- break may be used to exit this.      */
   104  /*    Other routines can safely use the return statement inline.      */
   105  /*                                                                    */
   106  /*    Storage leak accounting can be enabled using DECALLOC.          */
   107  /*                                                                    */
   108  /* 2. All loops use the for(;;) construct.  Any do construct does     */
   109  /*    not loop; it is for allocation protection as just described.    */
   110  /*                                                                    */
   111  /* 3. Setting status in the context must always be the very last      */
   112  /*    action in a routine, as non-0 status may raise a trap and hence */
   113  /*    the call to set status may not return (if the handler uses long */
   114  /*    jump).  Therefore all cleanup must be done first.  In general,  */
   115  /*    to achieve this status is accumulated and is only applied just  */
   116  /*    before return by calling decContextSetStatus (via decStatus).   */
   117  /*                                                                    */
   118  /*    Routines which allocate storage cannot, in general, use the     */
   119  /*    'top level' routines which could cause a non-returning          */
   120  /*    transfer of control.  The decXxxxOp routines are safe (do not   */
   121  /*    call decStatus even if traps are set in the context) and should */
   122  /*    be used instead (they are also a little faster).                */
   123  /*                                                                    */
   124  /* 4. Exponent checking is minimized by allowing the exponent to      */
   125  /*    grow outside its limits during calculations, provided that      */
   126  /*    the decFinalize function is called later.  Multiplication and   */
   127  /*    division, and intermediate calculations in exponentiation,      */
   128  /*    require more careful checks because of the risk of 31-bit       */
   129  /*    overflow (the most negative valid exponent is -1999999997, for  */
   130  /*    a 999999999-digit number with adjusted exponent of -999999999). */
   131  /*                                                                    */
   132  /* 5. Rounding is deferred until finalization of results, with any    */
   133  /*    'off to the right' data being represented as a single digit     */
   134  /*    residue (in the range -1 through 9).  This avoids any double-   */
   135  /*    rounding when more than one shortening takes place (for         */
   136  /*    example, when a result is subnormal).                           */
   137  /*                                                                    */
   138  /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
   139  /*    during many operations, so whole Units are handled and exact    */
   140  /*    accounting of digits is not needed.  The correct digits value   */
   141  /*    is found by decGetDigits, which accounts for leading zeros.     */
   142  /*    This must be called before any rounding if the number of digits */
   143  /*    is not known exactly.                                           */
   144  /*                                                                    */
   145  /* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
   146  /*    numbers up to four digits, using appropriate constants.  This   */
   147  /*    is not useful for longer numbers because overflow of 32 bits    */
   148  /*    would lead to 4 multiplies, which is almost as expensive as     */
   149  /*    a divide (unless a floating-point or 64-bit multiply is         */
   150  /*    assumed to be available).                                       */
   151  /*                                                                    */
   152  /* 8. Unusual abbreviations that may be used in the commentary:       */
   153  /*      lhs -- left hand side (operand, of an operation)              */
   154  /*      lsd -- least significant digit (of coefficient)               */
   155  /*      lsu -- least significant Unit (of coefficient)                */
   156  /*      msd -- most significant digit (of coefficient)                */
   157  /*      msi -- most significant item (in an array)                    */
   158  /*      msu -- most significant Unit (of coefficient)                 */
   159  /*      rhs -- right hand side (operand, of an operation)             */
   160  /*      +ve -- positive                                               */
   161  /*      -ve -- negative                                               */
   162  /*      **  -- raise to the power                                     */
   163  /* ------------------------------------------------------------------ */
   164  
   165  #include <stdlib.h>                // for malloc, free, etc.
   166  #include <stdio.h>                 // for printf [if needed]
   167  #include <string.h>                // for strcpy
   168  #include <ctype.h>                 // for lower
   169  #include "decNumber.h"             // base number library
   170  #include "decNumberLocal.h"        // decNumber local types, etc.
   171  
   172  /* Constants */
   173  // Public lookup table used by the D2U macro
   174  const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
   175  
   176  #define DECVERB     1              // set to 1 for verbose DECCHECK
   177  #define powers      DECPOWERS      // old internal name
   178  
   179  // Local constants
   180  #define DIVIDE      0x80           // Divide operators
   181  #define REMAINDER   0x40           // ..
   182  #define DIVIDEINT   0x20           // ..
   183  #define REMNEAR     0x10           // ..
   184  #define COMPARE     0x01           // Compare operators
   185  #define COMPMAX     0x02           // ..
   186  #define COMPMIN     0x03           // ..
   187  #define COMPTOTAL   0x04           // ..
   188  #define COMPNAN     0x05           // .. [NaN processing]
   189  #define COMPSIG     0x06           // .. [signaling COMPARE]
   190  #define COMPMAXMAG  0x07           // ..
   191  #define COMPMINMAG  0x08           // ..
   192  
   193  #define DEC_sNaN     0x40000000    // local status: sNaN signal
   194  #define BADINT  (Int)0x80000000    // most-negative Int; error indicator
   195  // Next two indicate an integer >= 10**6, and its parity (bottom bit)
   196  #define BIGEVEN (Int)0x80000002
   197  #define BIGODD  (Int)0x80000003
   198  
   199  static Unit uarrone[1]={1};   // Unit array of 1, used for incrementing
   200  
   201  /* Granularity-dependent code */
   202  #if DECDPUN<=4
   203    #define eInt  Int           // extended integer
   204    #define ueInt uInt          // unsigned extended integer
   205    // Constant multipliers for divide-by-power-of five using reciprocal
   206    // multiply, after removing powers of 2 by shifting, and final shift
   207    // of 17 [we only need up to **4]
   208    static const uInt multies[]={131073, 26215, 5243, 1049, 210};
   209    // QUOT10 -- macro to return the quotient of unit u divided by 10**n
   210    #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
   211  #else
   212    // For DECDPUN>4 non-ANSI-89 64-bit types are needed.
   213    #if !DECUSE64
   214      #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
   215    #endif
   216    #define eInt  Long          // extended integer
   217    #define ueInt uLong         // unsigned extended integer
   218  #endif
   219  
   220  /* Local routines */
   221  static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
   222                                decContext *, uByte, uInt *);
   223  static Flag        decBiStr(const char *, const char *, const char *);
   224  static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
   225  static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
   226  static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
   227  static decNumber * decCompareOp(decNumber *, const decNumber *,
   228                                const decNumber *, decContext *,
   229                                Flag, uInt *);
   230  static void        decCopyFit(decNumber *, const decNumber *, decContext *,
   231                                Int *, uInt *);
   232  static decNumber * decDecap(decNumber *, Int);
   233  static decNumber * decDivideOp(decNumber *, const decNumber *,
   234                                const decNumber *, decContext *, Flag, uInt *);
   235  static decNumber * decExpOp(decNumber *, const decNumber *,
   236                                decContext *, uInt *);
   237  static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
   238  static Int         decGetDigits(Unit *, Int);
   239  static Int         decGetInt(const decNumber *);
   240  static decNumber * decLnOp(decNumber *, const decNumber *,
   241                                decContext *, uInt *);
   242  static decNumber * decMultiplyOp(decNumber *, const decNumber *,
   243                                const decNumber *, decContext *,
   244                                uInt *);
   245  static decNumber * decNaNs(decNumber *, const decNumber *,
   246                                const decNumber *, decContext *, uInt *);
   247  static decNumber * decQuantizeOp(decNumber *, const decNumber *,
   248                                const decNumber *, decContext *, Flag,
   249                                uInt *);
   250  static void        decReverse(Unit *, Unit *);
   251  static void        decSetCoeff(decNumber *, decContext *, const Unit *,
   252                                Int, Int *, uInt *);
   253  static void        decSetMaxValue(decNumber *, decContext *);
   254  static void        decSetOverflow(decNumber *, decContext *, uInt *);
   255  static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
   256  static Int         decShiftToLeast(Unit *, Int, Int);
   257  static Int         decShiftToMost(Unit *, Int, Int);
   258  static void        decStatus(decNumber *, uInt, decContext *);
   259  static void        decToString(const decNumber *, char[], Flag);
   260  static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
   261  static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
   262                                Unit *, Int);
   263  static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
   264  
   265  #if !DECSUBSET
   266  /* decFinish == decFinalize when no subset arithmetic needed */
   267  #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
   268  #else
   269  static void        decFinish(decNumber *, decContext *, Int *, uInt *);
   270  static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
   271  #endif
   272  
   273  /* Local macros */
   274  // masked special-values bits
   275  #define SPECIALARG  (rhs->bits & DECSPECIAL)
   276  #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
   277  
   278  /* Diagnostic macros, etc. */
   279  #if DECALLOC
   280  // Handle malloc/free accounting.  If enabled, our accountable routines
   281  // are used; otherwise the code just goes straight to the system malloc
   282  // and free routines.
   283  #define malloc(a) decMalloc(a)
   284  #define free(a) decFree(a)
   285  #define DECFENCE 0x5a              // corruption detector
   286  // 'Our' malloc and free:
   287  static void *decMalloc(size_t);
   288  static void  decFree(void *);
   289  uInt decAllocBytes=0;              // count of bytes allocated
   290  // Note that DECALLOC code only checks for storage buffer overflow.
   291  // To check for memory leaks, the decAllocBytes variable must be
   292  // checked to be 0 at appropriate times (e.g., after the test
   293  // harness completes a set of tests).  This checking may be unreliable
   294  // if the testing is done in a multi-thread environment.
   295  #endif
   296  
   297  #if DECCHECK
   298  // Optional checking routines.  Enabling these means that decNumber
   299  // and decContext operands to operator routines are checked for
   300  // correctness.  This roughly doubles the execution time of the
   301  // fastest routines (and adds 600+ bytes), so should not normally be
   302  // used in 'production'.
   303  // decCheckInexact is used to check that inexact results have a full
   304  // complement of digits (where appropriate -- this is not the case
   305  // for Quantize, for example)
   306  #define DECUNRESU ((decNumber *)(void *)0xffffffff)
   307  #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
   308  #define DECUNCONT ((decContext *)(void *)(0xffffffff))
   309  static Flag decCheckOperands(decNumber *, const decNumber *,
   310                               const decNumber *, decContext *);
   311  static Flag decCheckNumber(const decNumber *);
   312  static void decCheckInexact(const decNumber *, decContext *);
   313  #endif
   314  
   315  #if DECTRACE || DECCHECK
   316  // Optional trace/debugging routines (may or may not be used)
   317  void decNumberShow(const decNumber *);  // displays the components of a number
   318  static void decDumpAr(char, const Unit *, Int);
   319  #endif
   320  
   321  /* ================================================================== */
   322  /* Conversions                                                        */
   323  /* ================================================================== */
   324  
   325  /* ------------------------------------------------------------------ */
   326  /* from-int32 -- conversion from Int or uInt                          */
   327  /*                                                                    */
   328  /*  dn is the decNumber to receive the integer                        */
   329  /*  in or uin is the integer to be converted                          */
   330  /*  returns dn                                                        */
   331  /*                                                                    */
   332  /* No error is possible.                                              */
   333  /* ------------------------------------------------------------------ */
   334  decNumber * decNumberFromInt32(decNumber *dn, Int in) {
   335    uInt unsig;
   336    if (in>=0) unsig=in;
   337     else {                               // negative (possibly BADINT)
   338      if (in==BADINT) unsig=(uInt)1073741824*2; // special case
   339       else unsig=-in;                    // invert
   340      }
   341    // in is now positive
   342    decNumberFromUInt32(dn, unsig);
   343    if (in<0) dn->bits=DECNEG;            // sign needed
   344    return dn;
   345    } // decNumberFromInt32
   346  
   347  decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
   348    Unit *up;                             // work pointer
   349    decNumberZero(dn);                    // clean
   350    if (uin==0) return dn;                // [or decGetDigits bad call]
   351    for (up=dn->lsu; uin>0; up++) {
   352      *up=(Unit)(uin%(DECDPUNMAX+1));
   353      uin=uin/(DECDPUNMAX+1);
   354      }
   355    dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
   356    return dn;
   357    } // decNumberFromUInt32
   358  
   359  /* ------------------------------------------------------------------ */
   360  /* to-int32 -- conversion to Int or uInt                              */
   361  /*                                                                    */
   362  /*  dn is the decNumber to convert                                    */
   363  /*  set is the context for reporting errors                           */
   364  /*  returns the converted decNumber, or 0 if Invalid is set           */
   365  /*                                                                    */
   366  /* Invalid is set if the decNumber does not have exponent==0 or if    */
   367  /* it is a NaN, Infinite, or out-of-range.                            */
   368  /* ------------------------------------------------------------------ */
   369  Int decNumberToInt32(const decNumber *dn, decContext *set) {
   370    #if DECCHECK
   371    if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
   372    #endif
   373  
   374    // special or too many digits, or bad exponent
   375    if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad
   376     else { // is a finite integer with 10 or fewer digits
   377      Int d;                         // work
   378      const Unit *up;                // ..
   379      uInt hi=0, lo;                 // ..
   380      up=dn->lsu;                    // -> lsu
   381      lo=*up;                        // get 1 to 9 digits
   382      #if DECDPUN>1                  // split to higher
   383        hi=lo/10;
   384        lo=lo%10;
   385      #endif
   386      up++;
   387      // collect remaining Units, if any, into hi
   388      for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
   389      // now low has the lsd, hi the remainder
   390      if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
   391        // most-negative is a reprieve
   392        if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
   393        // bad -- drop through
   394        }
   395       else { // in-range always
   396        Int i=X10(hi)+lo;
   397        if (dn->bits&DECNEG) return -i;
   398        return i;
   399        }
   400      } // integer
   401    decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
   402    return 0;
   403    } // decNumberToInt32
   404  
   405  uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
   406    #if DECCHECK
   407    if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
   408    #endif
   409    // special or too many digits, or bad exponent, or negative (<0)
   410    if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
   411      || (dn->bits&DECNEG && !ISZERO(dn)));                   // bad
   412     else { // is a finite integer with 10 or fewer digits
   413      Int d;                         // work
   414      const Unit *up;                // ..
   415      uInt hi=0, lo;                 // ..
   416      up=dn->lsu;                    // -> lsu
   417      lo=*up;                        // get 1 to 9 digits
   418      #if DECDPUN>1                  // split to higher
   419        hi=lo/10;
   420        lo=lo%10;
   421      #endif
   422      up++;
   423      // collect remaining Units, if any, into hi
   424      for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
   425  
   426      // now low has the lsd, hi the remainder
   427      if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible
   428       else return X10(hi)+lo;
   429      } // integer
   430    decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
   431    return 0;
   432    } // decNumberToUInt32
   433  
   434  /* ------------------------------------------------------------------ */
   435  /* to-scientific-string -- conversion to numeric string               */
   436  /* to-engineering-string -- conversion to numeric string              */
   437  /*                                                                    */
   438  /*   decNumberToString(dn, string);                                   */
   439  /*   decNumberToEngString(dn, string);                                */
   440  /*                                                                    */
   441  /*  dn is the decNumber to convert                                    */
   442  /*  string is the string where the result will be laid out            */
   443  /*                                                                    */
   444  /*  string must be at least dn->digits+14 characters long             */
   445  /*                                                                    */
   446  /*  No error is possible, and no status can be set.                   */
   447  /* ------------------------------------------------------------------ */
   448  char * decNumberToString(const decNumber *dn, char *string){
   449    decToString(dn, string, 0);
   450    return string;
   451    } // DecNumberToString
   452  
   453  char * decNumberToEngString(const decNumber *dn, char *string){
   454    decToString(dn, string, 1);
   455    return string;
   456    } // DecNumberToEngString
   457  
   458  /* ------------------------------------------------------------------ */
   459  /* to-number -- conversion from numeric string                        */
   460  /*                                                                    */
   461  /* decNumberFromString -- convert string to decNumber                 */
   462  /*   dn        -- the number structure to fill                        */
   463  /*   chars[]   -- the string to convert ('\0' terminated)             */
   464  /*   set       -- the context used for processing any error,          */
   465  /*                determining the maximum precision available         */
   466  /*                (set.digits), determining the maximum and minimum   */
   467  /*                exponent (set.emax and set.emin), determining if    */
   468  /*                extended values are allowed, and checking the       */
   469  /*                rounding mode if overflow occurs or rounding is     */
   470  /*                needed.                                             */
   471  /*                                                                    */
   472  /* The length of the coefficient and the size of the exponent are     */
   473  /* checked by this routine, so the correct error (Underflow or        */
   474  /* Overflow) can be reported or rounding applied, as necessary.       */
   475  /*                                                                    */
   476  /* If bad syntax is detected, the result will be a quiet NaN.         */
   477  /* ------------------------------------------------------------------ */
   478  decNumber * decNumberFromString(decNumber *dn, const char chars[],
   479                                  decContext *set) {
   480    Int   exponent=0;                // working exponent [assume 0]
   481    uByte bits=0;                    // working flags [assume +ve]
   482    Unit  *res;                      // where result will be built
   483    Unit  resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
   484                                     // [+9 allows for ln() constants]
   485    Unit  *allocres=NULL;            // -> allocated result, iff allocated
   486    Int   d=0;                       // count of digits found in decimal part
   487    const char *dotchar=NULL;        // where dot was found
   488    const char *cfirst=chars;        // -> first character of decimal part
   489    const char *last=NULL;           // -> last digit of decimal part
   490    const char *c;                   // work
   491    Unit  *up;                       // ..
   492    #if DECDPUN>1
   493    Int   cut, out;                  // ..
   494    #endif
   495    Int   residue;                   // rounding residue
   496    uInt  status=0;                  // error code
   497  
   498    #if DECCHECK
   499    if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
   500      return decNumberZero(dn);
   501    #endif
   502  
   503    do {                             // status & malloc protection
   504      for (c=chars;; c++) {          // -> input character
   505        if (*c>='0' && *c<='9') {    // test for Arabic digit
   506          last=c;
   507          d++;                       // count of real digits
   508          continue;                  // still in decimal part
   509          }
   510        if (*c=='.' && dotchar==NULL) { // first '.'
   511          dotchar=c;                 // record offset into decimal part
   512          if (c==cfirst) cfirst++;   // first digit must follow
   513          continue;}
   514        if (c==chars) {              // first in string...
   515          if (*c=='-') {             // valid - sign
   516            cfirst++;
   517            bits=DECNEG;
   518            continue;}
   519          if (*c=='+') {             // valid + sign
   520            cfirst++;
   521            continue;}
   522          }
   523        // *c is not a digit, or a valid +, -, or '.'
   524        break;
   525        } // c
   526  
   527      if (last==NULL) {              // no digits yet
   528        status=DEC_Conversion_syntax;// assume the worst
   529        if (*c=='\0') break;         // and no more to come...
   530        #if DECSUBSET
   531        // if subset then infinities and NaNs are not allowed
   532        if (!set->extended) break;   // hopeless
   533        #endif
   534        // Infinities and NaNs are possible, here
   535        if (dotchar!=NULL) break;    // .. unless had a dot
   536        decNumberZero(dn);           // be optimistic
   537        if (decBiStr(c, "infinity", "INFINITY")
   538         || decBiStr(c, "inf", "INF")) {
   539          dn->bits=bits | DECINF;
   540          status=0;                  // is OK
   541          break; // all done
   542          }
   543        // a NaN expected
   544        // 2003.09.10 NaNs are now permitted to have a sign
   545        dn->bits=bits | DECNAN;      // assume simple NaN
   546        if (*c=='s' || *c=='S') {    // looks like an sNaN
   547          c++;
   548          dn->bits=bits | DECSNAN;
   549          }
   550        if (*c!='n' && *c!='N') break;    // check caseless "NaN"
   551        c++;
   552        if (*c!='a' && *c!='A') break;    // ..
   553        c++;
   554        if (*c!='n' && *c!='N') break;    // ..
   555        c++;
   556        // now either nothing, or nnnn payload, expected
   557        // -> start of integer and skip leading 0s [including plain 0]
   558        for (cfirst=c; *cfirst=='0';) cfirst++;
   559        if (*cfirst=='\0') {         // "NaN" or "sNaN", maybe with all 0s
   560          status=0;                  // it's good
   561          break;                     // ..
   562          }
   563        // something other than 0s; setup last and d as usual [no dots]
   564        for (c=cfirst;; c++, d++) {
   565          if (*c<'0' || *c>'9') break; // test for Arabic digit
   566          last=c;
   567          }
   568        if (*c!='\0') break;         // not all digits
   569        if (d>set->digits-1) {
   570          // [NB: payload in a decNumber can be full length unless
   571          // clamped, in which case can only be digits-1]
   572          if (set->clamp) break;
   573          if (d>set->digits) break;
   574          } // too many digits?
   575        // good; drop through to convert the integer to coefficient
   576        status=0;                    // syntax is OK
   577        bits=dn->bits;               // for copy-back
   578        } // last==NULL
   579  
   580       else if (*c!='\0') {          // more to process...
   581        // had some digits; exponent is only valid sequence now
   582        Flag nege;                   // 1=negative exponent
   583        const char *firstexp;        // -> first significant exponent digit
   584        status=DEC_Conversion_syntax;// assume the worst
   585        if (*c!='e' && *c!='E') break;
   586        /* Found 'e' or 'E' -- now process explicit exponent */
   587        // 1998.07.11: sign no longer required
   588        nege=0;
   589        c++;                         // to (possible) sign
   590        if (*c=='-') {nege=1; c++;}
   591         else if (*c=='+') c++;
   592        if (*c=='\0') break;
   593  
   594        for (; *c=='0' && *(c+1)!='\0';) c++;  // strip insignificant zeros
   595        firstexp=c;                            // save exponent digit place
   596        for (; ;c++) {
   597          if (*c<'0' || *c>'9') break;         // not a digit
   598          exponent=X10(exponent)+(Int)*c-(Int)'0';
   599          } // c
   600        // if not now on a '\0', *c must not be a digit
   601        if (*c!='\0') break;
   602  
   603        // (this next test must be after the syntax checks)
   604        // if it was too long the exponent may have wrapped, so check
   605        // carefully and set it to a certain overflow if wrap possible
   606        if (c>=firstexp+9+1) {
   607          if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
   608          // [up to 1999999999 is OK, for example 1E-1000000998]
   609          }
   610        if (nege) exponent=-exponent;     // was negative
   611        status=0;                         // is OK
   612        } // stuff after digits
   613  
   614      // Here when whole string has been inspected; syntax is good
   615      // cfirst->first digit (never dot), last->last digit (ditto)
   616  
   617      // strip leading zeros/dot [leave final 0 if all 0's]
   618      if (*cfirst=='0') {                 // [cfirst has stepped over .]
   619        for (c=cfirst; c<last; c++, cfirst++) {
   620          if (*c=='.') continue;          // ignore dots
   621          if (*c!='0') break;             // non-zero found
   622          d--;                            // 0 stripped
   623          } // c
   624        #if DECSUBSET
   625        // make a rapid exit for easy zeros if !extended
   626        if (*cfirst=='0' && !set->extended) {
   627          decNumberZero(dn);              // clean result
   628          break;                          // [could be return]
   629          }
   630        #endif
   631        } // at least one leading 0
   632  
   633      // Handle decimal point...
   634      if (dotchar!=NULL && dotchar<last)  // non-trailing '.' found?
   635        exponent-=(last-dotchar);         // adjust exponent
   636      // [we can now ignore the .]
   637  
   638      // OK, the digits string is good.  Assemble in the decNumber, or in
   639      // a temporary units array if rounding is needed
   640      if (d<=set->digits) res=dn->lsu;    // fits into supplied decNumber
   641       else {                             // rounding needed
   642        Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
   643        res=resbuff;                      // assume use local buffer
   644        if (needbytes>(Int)sizeof(resbuff)) { // too big for local
   645          allocres=(Unit *)malloc(needbytes);
   646          if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
   647          res=allocres;
   648          }
   649        }
   650      // res now -> number lsu, buffer, or allocated storage for Unit array
   651  
   652      // Place the coefficient into the selected Unit array
   653      // [this is often 70% of the cost of this function when DECDPUN>1]
   654      #if DECDPUN>1
   655      out=0;                         // accumulator
   656      up=res+D2U(d)-1;               // -> msu
   657      cut=d-(up-res)*DECDPUN;        // digits in top unit
   658      for (c=cfirst;; c++) {         // along the digits
   659        if (*c=='.') continue;       // ignore '.' [don't decrement cut]
   660        out=X10(out)+(Int)*c-(Int)'0';
   661        if (c==last) break;          // done [never get to trailing '.']
   662        cut--;
   663        if (cut>0) continue;         // more for this unit
   664        *up=(Unit)out;               // write unit
   665        up--;                        // prepare for unit below..
   666        cut=DECDPUN;                 // ..
   667        out=0;                       // ..
   668        } // c
   669      *up=(Unit)out;                 // write lsu
   670  
   671      #else
   672      // DECDPUN==1
   673      up=res;                        // -> lsu
   674      for (c=last; c>=cfirst; c--) { // over each character, from least
   675        if (*c=='.') continue;       // ignore . [don't step up]
   676        *up=(Unit)((Int)*c-(Int)'0');
   677        up++;
   678        } // c
   679      #endif
   680  
   681      dn->bits=bits;
   682      dn->exponent=exponent;
   683      dn->digits=d;
   684  
   685      // if not in number (too long) shorten into the number
   686      if (d>set->digits) {
   687        residue=0;
   688        decSetCoeff(dn, set, res, d, &residue, &status);
   689        // always check for overflow or subnormal and round as needed
   690        decFinalize(dn, set, &residue, &status);
   691        }
   692       else { // no rounding, but may still have overflow or subnormal
   693        // [these tests are just for performance; finalize repeats them]
   694        if ((dn->exponent-1<set->emin-dn->digits)
   695         || (dn->exponent-1>set->emax-set->digits)) {
   696          residue=0;
   697          decFinalize(dn, set, &residue, &status);
   698          }
   699        }
   700      // decNumberShow(dn);
   701      } while(0);                         // [for break]
   702  
   703    if (allocres!=NULL) free(allocres);   // drop any storage used
   704    if (status!=0) decStatus(dn, status, set);
   705    return dn;
   706    } /* decNumberFromString */
   707  
   708  /* ================================================================== */
   709  /* Operators                                                          */
   710  /* ================================================================== */
   711  
   712  /* ------------------------------------------------------------------ */
   713  /* decNumberAbs -- absolute value operator                            */
   714  /*                                                                    */
   715  /*   This computes C = abs(A)                                         */
   716  /*                                                                    */
   717  /*   res is C, the result.  C may be A                                */
   718  /*   rhs is A                                                         */
   719  /*   set is the context                                               */
   720  /*                                                                    */
   721  /* See also decNumberCopyAbs for a quiet bitwise version of this.     */
   722  /* C must have space for set->digits digits.                          */
   723  /* ------------------------------------------------------------------ */
   724  /* This has the same effect as decNumberPlus unless A is negative,    */
   725  /* in which case it has the same effect as decNumberMinus.            */
   726  /* ------------------------------------------------------------------ */
   727  decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
   728                           decContext *set) {
   729    decNumber dzero;                      // for 0
   730    uInt status=0;                        // accumulator
   731  
   732    #if DECCHECK
   733    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
   734    #endif
   735  
   736    decNumberZero(&dzero);                // set 0
   737    dzero.exponent=rhs->exponent;         // [no coefficient expansion]
   738    decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
   739    if (status!=0) decStatus(res, status, set);
   740    #if DECCHECK
   741    decCheckInexact(res, set);
   742    #endif
   743    return res;
   744    } // decNumberAbs
   745  
   746  /* ------------------------------------------------------------------ */
   747  /* decNumberAdd -- add two Numbers                                    */
   748  /*                                                                    */
   749  /*   This computes C = A + B                                          */
   750  /*                                                                    */
   751  /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
   752  /*   lhs is A                                                         */
   753  /*   rhs is B                                                         */
   754  /*   set is the context                                               */
   755  /*                                                                    */
   756  /* C must have space for set->digits digits.                          */
   757  /* ------------------------------------------------------------------ */
   758  /* This just calls the routine shared with Subtract                   */
   759  decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
   760                           const decNumber *rhs, decContext *set) {
   761    uInt status=0;                        // accumulator
   762    decAddOp(res, lhs, rhs, set, 0, &status);
   763    if (status!=0) decStatus(res, status, set);
   764    #if DECCHECK
   765    decCheckInexact(res, set);
   766    #endif
   767    return res;
   768    } // decNumberAdd
   769  
   770  /* ------------------------------------------------------------------ */
   771  /* decNumberAnd -- AND two Numbers, digitwise                         */
   772  /*                                                                    */
   773  /*   This computes C = A & B                                          */
   774  /*                                                                    */
   775  /*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
   776  /*   lhs is A                                                         */
   777  /*   rhs is B                                                         */
   778  /*   set is the context (used for result length and error report)     */
   779  /*                                                                    */
   780  /* C must have space for set->digits digits.                          */
   781  /*                                                                    */
   782  /* Logical function restrictions apply (see above); a NaN is          */
   783  /* returned with Invalid_operation if a restriction is violated.      */
   784  /* ------------------------------------------------------------------ */
   785  decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
   786                           const decNumber *rhs, decContext *set) {
   787    const Unit *ua, *ub;                  // -> operands
   788    const Unit *msua, *msub;              // -> operand msus
   789    Unit *uc,  *msuc;                     // -> result and its msu
   790    Int   msudigs;                        // digits in res msu
   791    #if DECCHECK
   792    if (decCheckOperands(res, lhs, rhs, set)) return res;
   793    #endif
   794  
   795    if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
   796     || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
   797      decStatus(res, DEC_Invalid_operation, set);
   798      return res;
   799      }
   800  
   801    // operands are valid
   802    ua=lhs->lsu;                          // bottom-up
   803    ub=rhs->lsu;                          // ..
   804    uc=res->lsu;                          // ..
   805    msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
   806    msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
   807    msuc=uc+D2U(set->digits)-1;           // -> msu of result
   808    msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
   809    for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
   810      Unit a, b;                          // extract units
   811      if (ua>msua) a=0;
   812       else a=*ua;
   813      if (ub>msub) b=0;
   814       else b=*ub;
   815      *uc=0;                              // can now write back
   816      if (a|b) {                          // maybe 1 bits to examine
   817        Int i, j;
   818        *uc=0;                            // can now write back
   819        // This loop could be unrolled and/or use BIN2BCD tables
   820        for (i=0; i<DECDPUN; i++) {
   821          if (a&b&1) *uc=*uc+(Unit)powers[i];  // effect AND
   822          j=a%10;
   823          a=a/10;
   824          j|=b%10;
   825          b=b/10;
   826          if (j>1) {
   827            decStatus(res, DEC_Invalid_operation, set);
   828            return res;
   829            }
   830          if (uc==msuc && i==msudigs-1) break; // just did final digit
   831          } // each digit
   832        } // both OK
   833      } // each unit
   834    // [here uc-1 is the msu of the result]
   835    res->digits=decGetDigits(res->lsu, uc-res->lsu);
   836    res->exponent=0;                      // integer
   837    res->bits=0;                          // sign=0
   838    return res;  // [no status to set]
   839    } // decNumberAnd
   840  
   841  /* ------------------------------------------------------------------ */
   842  /* decNumberCompare -- compare two Numbers                            */
   843  /*                                                                    */
   844  /*   This computes C = A ? B                                          */
   845  /*                                                                    */
   846  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
   847  /*   lhs is A                                                         */
   848  /*   rhs is B                                                         */
   849  /*   set is the context                                               */
   850  /*                                                                    */
   851  /* C must have space for one digit (or NaN).                          */
   852  /* ------------------------------------------------------------------ */
   853  decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
   854                               const decNumber *rhs, decContext *set) {
   855    uInt status=0;                        // accumulator
   856    decCompareOp(res, lhs, rhs, set, COMPARE, &status);
   857    if (status!=0) decStatus(res, status, set);
   858    return res;
   859    } // decNumberCompare
   860  
   861  /* ------------------------------------------------------------------ */
   862  /* decNumberCompareSignal -- compare, signalling on all NaNs          */
   863  /*                                                                    */
   864  /*   This computes C = A ? B                                          */
   865  /*                                                                    */
   866  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
   867  /*   lhs is A                                                         */
   868  /*   rhs is B                                                         */
   869  /*   set is the context                                               */
   870  /*                                                                    */
   871  /* C must have space for one digit (or NaN).                          */
   872  /* ------------------------------------------------------------------ */
   873  decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
   874                                     const decNumber *rhs, decContext *set) {
   875    uInt status=0;                        // accumulator
   876    decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
   877    if (status!=0) decStatus(res, status, set);
   878    return res;
   879    } // decNumberCompareSignal
   880  
   881  /* ------------------------------------------------------------------ */
   882  /* decNumberCompareTotal -- compare two Numbers, using total ordering */
   883  /*                                                                    */
   884  /*   This computes C = A ? B, under total ordering                    */
   885  /*                                                                    */
   886  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
   887  /*   lhs is A                                                         */
   888  /*   rhs is B                                                         */
   889  /*   set is the context                                               */
   890  /*                                                                    */
   891  /* C must have space for one digit; the result will always be one of  */
   892  /* -1, 0, or 1.                                                       */
   893  /* ------------------------------------------------------------------ */
   894  decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
   895                                    const decNumber *rhs, decContext *set) {
   896    uInt status=0;                        // accumulator
   897    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
   898    if (status!=0) decStatus(res, status, set);
   899    return res;
   900    } // decNumberCompareTotal
   901  
   902  /* ------------------------------------------------------------------ */
   903  /* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
   904  /*                                                                    */
   905  /*   This computes C = |A| ? |B|, under total ordering                */
   906  /*                                                                    */
   907  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
   908  /*   lhs is A                                                         */
   909  /*   rhs is B                                                         */
   910  /*   set is the context                                               */
   911  /*                                                                    */
   912  /* C must have space for one digit; the result will always be one of  */
   913  /* -1, 0, or 1.                                                       */
   914  /* ------------------------------------------------------------------ */
   915  decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
   916                                       const decNumber *rhs, decContext *set) {
   917    uInt status=0;                   // accumulator
   918    uInt needbytes;                  // for space calculations
   919    decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
   920    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
   921    decNumber bufb[D2N(DECBUFFER+1)];
   922    decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
   923    decNumber *a, *b;                // temporary pointers
   924  
   925    #if DECCHECK
   926    if (decCheckOperands(res, lhs, rhs, set)) return res;
   927    #endif
   928  
   929    do {                                  // protect allocated storage
   930      // if either is negative, take a copy and absolute
   931      if (decNumberIsNegative(lhs)) {     // lhs<0
   932        a=bufa;
   933        needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
   934        if (needbytes>sizeof(bufa)) {     // need malloc space
   935          allocbufa=(decNumber *)malloc(needbytes);
   936          if (allocbufa==NULL) {          // hopeless -- abandon
   937            status|=DEC_Insufficient_storage;
   938            break;}
   939          a=allocbufa;                    // use the allocated space
   940          }
   941        decNumberCopy(a, lhs);            // copy content
   942        a->bits&=~DECNEG;                 // .. and clear the sign
   943        lhs=a;                            // use copy from here on
   944        }
   945      if (decNumberIsNegative(rhs)) {     // rhs<0
   946        b=bufb;
   947        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
   948        if (needbytes>sizeof(bufb)) {     // need malloc space
   949          allocbufb=(decNumber *)malloc(needbytes);
   950          if (allocbufb==NULL) {          // hopeless -- abandon
   951            status|=DEC_Insufficient_storage;
   952            break;}
   953          b=allocbufb;                    // use the allocated space
   954          }
   955        decNumberCopy(b, rhs);            // copy content
   956        b->bits&=~DECNEG;                 // .. and clear the sign
   957        rhs=b;                            // use copy from here on
   958        }
   959      decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
   960      } while(0);                         // end protected
   961  
   962    if (allocbufa!=NULL) free(allocbufa); // drop any storage used
   963    if (allocbufb!=NULL) free(allocbufb); // ..
   964    if (status!=0) decStatus(res, status, set);
   965    return res;
   966    } // decNumberCompareTotalMag
   967  
   968  /* ------------------------------------------------------------------ */
   969  /* decNumberDivide -- divide one number by another                    */
   970  /*                                                                    */
   971  /*   This computes C = A / B                                          */
   972  /*                                                                    */
   973  /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
   974  /*   lhs is A                                                         */
   975  /*   rhs is B                                                         */
   976  /*   set is the context                                               */
   977  /*                                                                    */
   978  /* C must have space for set->digits digits.                          */
   979  /* ------------------------------------------------------------------ */
   980  decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
   981                              const decNumber *rhs, decContext *set) {
   982    uInt status=0;                        // accumulator
   983    decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
   984    if (status!=0) decStatus(res, status, set);
   985    #if DECCHECK
   986    decCheckInexact(res, set);
   987    #endif
   988    return res;
   989    } // decNumberDivide
   990  
   991  /* ------------------------------------------------------------------ */
   992  /* decNumberDivideInteger -- divide and return integer quotient       */
   993  /*                                                                    */
   994  /*   This computes C = A # B, where # is the integer divide operator  */
   995  /*                                                                    */
   996  /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
   997  /*   lhs is A                                                         */
   998  /*   rhs is B                                                         */
   999  /*   set is the context                                               */
  1000  /*                                                                    */
  1001  /* C must have space for set->digits digits.                          */
  1002  /* ------------------------------------------------------------------ */
  1003  decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
  1004                                     const decNumber *rhs, decContext *set) {
  1005    uInt status=0;                        // accumulator
  1006    decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
  1007    if (status!=0) decStatus(res, status, set);
  1008    return res;
  1009    } // decNumberDivideInteger
  1010  
  1011  /* ------------------------------------------------------------------ */
  1012  /* decNumberExp -- exponentiation                                     */
  1013  /*                                                                    */
  1014  /*   This computes C = exp(A)                                         */
  1015  /*                                                                    */
  1016  /*   res is C, the result.  C may be A                                */
  1017  /*   rhs is A                                                         */
  1018  /*   set is the context; note that rounding mode has no effect        */
  1019  /*                                                                    */
  1020  /* C must have space for set->digits digits.                          */
  1021  /*                                                                    */
  1022  /* Mathematical function restrictions apply (see above); a NaN is     */
  1023  /* returned with Invalid_operation if a restriction is violated.      */
  1024  /*                                                                    */
  1025  /* Finite results will always be full precision and Inexact, except   */
  1026  /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
  1027  /*                                                                    */
  1028  /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
  1029  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  1030  /* error in rare cases.                                               */
  1031  /* ------------------------------------------------------------------ */
  1032  /* This is a wrapper for decExpOp which can handle the slightly wider */
  1033  /* (double) range needed by Ln (which has to be able to calculate     */
  1034  /* exp(-a) where a can be the tiniest number (Ntiny).                 */
  1035  /* ------------------------------------------------------------------ */
  1036  decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
  1037                           decContext *set) {
  1038    uInt status=0;                        // accumulator
  1039    #if DECSUBSET
  1040    decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
  1041    #endif
  1042  
  1043    #if DECCHECK
  1044    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1045    #endif
  1046  
  1047    // Check restrictions; these restrictions ensure that if h=8 (see
  1048    // decExpOp) then the result will either overflow or underflow to 0.
  1049    // Other math functions restrict the input range, too, for inverses.
  1050    // If not violated then carry out the operation.
  1051    if (!decCheckMath(rhs, set, &status)) do { // protect allocation
  1052      #if DECSUBSET
  1053      if (!set->extended) {
  1054        // reduce operand and set lostDigits status, as needed
  1055        if (rhs->digits>set->digits) {
  1056          allocrhs=decRoundOperand(rhs, set, &status);
  1057          if (allocrhs==NULL) break;
  1058          rhs=allocrhs;
  1059          }
  1060        }
  1061      #endif
  1062      decExpOp(res, rhs, set, &status);
  1063      } while(0);                         // end protected
  1064  
  1065    #if DECSUBSET
  1066    if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
  1067    #endif
  1068    // apply significant status
  1069    if (status!=0) decStatus(res, status, set);
  1070    #if DECCHECK
  1071    decCheckInexact(res, set);
  1072    #endif
  1073    return res;
  1074    } // decNumberExp
  1075  
  1076  /* ------------------------------------------------------------------ */
  1077  /* decNumberFMA -- fused multiply add                                 */
  1078  /*                                                                    */
  1079  /*   This computes D = (A * B) + C with only one rounding             */
  1080  /*                                                                    */
  1081  /*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
  1082  /*   lhs is A                                                         */
  1083  /*   rhs is B                                                         */
  1084  /*   fhs is C [far hand side]                                         */
  1085  /*   set is the context                                               */
  1086  /*                                                                    */
  1087  /* Mathematical function restrictions apply (see above); a NaN is     */
  1088  /* returned with Invalid_operation if a restriction is violated.      */
  1089  /*                                                                    */
  1090  /* C must have space for set->digits digits.                          */
  1091  /* ------------------------------------------------------------------ */
  1092  decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
  1093                           const decNumber *rhs, const decNumber *fhs,
  1094                           decContext *set) {
  1095    uInt status=0;                   // accumulator
  1096    decContext dcmul;                // context for the multiplication
  1097    uInt needbytes;                  // for space calculations
  1098    decNumber bufa[D2N(DECBUFFER*2+1)];
  1099    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
  1100    decNumber *acc;                  // accumulator pointer
  1101    decNumber dzero;                 // work
  1102  
  1103    #if DECCHECK
  1104    if (decCheckOperands(res, lhs, rhs, set)) return res;
  1105    if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
  1106    #endif
  1107  
  1108    do {                                  // protect allocated storage
  1109      #if DECSUBSET
  1110      if (!set->extended) {               // [undefined if subset]
  1111        status|=DEC_Invalid_operation;
  1112        break;}
  1113      #endif
  1114      // Check math restrictions [these ensure no overflow or underflow]
  1115      if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
  1116       || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
  1117       || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
  1118      // set up context for multiply
  1119      dcmul=*set;
  1120      dcmul.digits=lhs->digits+rhs->digits; // just enough
  1121      // [The above may be an over-estimate for subset arithmetic, but that's OK]
  1122      dcmul.emax=DEC_MAX_EMAX;            // effectively unbounded ..
  1123      dcmul.emin=DEC_MIN_EMIN;            // [thanks to Math restrictions]
  1124      // set up decNumber space to receive the result of the multiply
  1125      acc=bufa;                           // may fit
  1126      needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
  1127      if (needbytes>sizeof(bufa)) {       // need malloc space
  1128        allocbufa=(decNumber *)malloc(needbytes);
  1129        if (allocbufa==NULL) {            // hopeless -- abandon
  1130          status|=DEC_Insufficient_storage;
  1131          break;}
  1132        acc=allocbufa;                    // use the allocated space
  1133        }
  1134      // multiply with extended range and necessary precision
  1135      //printf("emin=%ld\n", dcmul.emin);
  1136      decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
  1137      // Only Invalid operation (from sNaN or Inf * 0) is possible in
  1138      // status; if either is seen than ignore fhs (in case it is
  1139      // another sNaN) and set acc to NaN unless we had an sNaN
  1140      // [decMultiplyOp leaves that to caller]
  1141      // Note sNaN has to go through addOp to shorten payload if
  1142      // necessary
  1143      if ((status&DEC_Invalid_operation)!=0) {
  1144        if (!(status&DEC_sNaN)) {         // but be true invalid
  1145          decNumberZero(res);             // acc not yet set
  1146          res->bits=DECNAN;
  1147          break;
  1148          }
  1149        decNumberZero(&dzero);            // make 0 (any non-NaN would do)
  1150        fhs=&dzero;                       // use that
  1151        }
  1152      #if DECCHECK
  1153       else { // multiply was OK
  1154        if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
  1155        }
  1156      #endif
  1157      // add the third operand and result -> res, and all is done
  1158      decAddOp(res, acc, fhs, set, 0, &status);
  1159      } while(0);                         // end protected
  1160  
  1161    if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  1162    if (status!=0) decStatus(res, status, set);
  1163    #if DECCHECK
  1164    decCheckInexact(res, set);
  1165    #endif
  1166    return res;
  1167    } // decNumberFMA
  1168  
  1169  /* ------------------------------------------------------------------ */
  1170  /* decNumberInvert -- invert a Number, digitwise                      */
  1171  /*                                                                    */
  1172  /*   This computes C = ~A                                             */
  1173  /*                                                                    */
  1174  /*   res is C, the result.  C may be A (e.g., X=~X)                   */
  1175  /*   rhs is A                                                         */
  1176  /*   set is the context (used for result length and error report)     */
  1177  /*                                                                    */
  1178  /* C must have space for set->digits digits.                          */
  1179  /*                                                                    */
  1180  /* Logical function restrictions apply (see above); a NaN is          */
  1181  /* returned with Invalid_operation if a restriction is violated.      */
  1182  /* ------------------------------------------------------------------ */
  1183  decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
  1184                              decContext *set) {
  1185    const Unit *ua, *msua;                // -> operand and its msu
  1186    Unit  *uc, *msuc;                     // -> result and its msu
  1187    Int   msudigs;                        // digits in res msu
  1188    #if DECCHECK
  1189    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1190    #endif
  1191  
  1192    if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1193      decStatus(res, DEC_Invalid_operation, set);
  1194      return res;
  1195      }
  1196    // operand is valid
  1197    ua=rhs->lsu;                          // bottom-up
  1198    uc=res->lsu;                          // ..
  1199    msua=ua+D2U(rhs->digits)-1;           // -> msu of rhs
  1200    msuc=uc+D2U(set->digits)-1;           // -> msu of result
  1201    msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
  1202    for (; uc<=msuc; ua++, uc++) {        // Unit loop
  1203      Unit a;                             // extract unit
  1204      Int  i, j;                          // work
  1205      if (ua>msua) a=0;
  1206       else a=*ua;
  1207      *uc=0;                              // can now write back
  1208      // always need to examine all bits in rhs
  1209      // This loop could be unrolled and/or use BIN2BCD tables
  1210      for (i=0; i<DECDPUN; i++) {
  1211        if ((~a)&1) *uc=*uc+(Unit)powers[i];   // effect INVERT
  1212        j=a%10;
  1213        a=a/10;
  1214        if (j>1) {
  1215          decStatus(res, DEC_Invalid_operation, set);
  1216          return res;
  1217          }
  1218        if (uc==msuc && i==msudigs-1) break;   // just did final digit
  1219        } // each digit
  1220      } // each unit
  1221    // [here uc-1 is the msu of the result]
  1222    res->digits=decGetDigits(res->lsu, uc-res->lsu);
  1223    res->exponent=0;                      // integer
  1224    res->bits=0;                          // sign=0
  1225    return res;  // [no status to set]
  1226    } // decNumberInvert
  1227  
  1228  /* ------------------------------------------------------------------ */
  1229  /* decNumberLn -- natural logarithm                                   */
  1230  /*                                                                    */
  1231  /*   This computes C = ln(A)                                          */
  1232  /*                                                                    */
  1233  /*   res is C, the result.  C may be A                                */
  1234  /*   rhs is A                                                         */
  1235  /*   set is the context; note that rounding mode has no effect        */
  1236  /*                                                                    */
  1237  /* C must have space for set->digits digits.                          */
  1238  /*                                                                    */
  1239  /* Notable cases:                                                     */
  1240  /*   A<0 -> Invalid                                                   */
  1241  /*   A=0 -> -Infinity (Exact)                                         */
  1242  /*   A=+Infinity -> +Infinity (Exact)                                 */
  1243  /*   A=1 exactly -> 0 (Exact)                                         */
  1244  /*                                                                    */
  1245  /* Mathematical function restrictions apply (see above); a NaN is     */
  1246  /* returned with Invalid_operation if a restriction is violated.      */
  1247  /*                                                                    */
  1248  /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
  1249  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  1250  /* error in rare cases.                                               */
  1251  /* ------------------------------------------------------------------ */
  1252  /* This is a wrapper for decLnOp which can handle the slightly wider  */
  1253  /* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
  1254  /* to calculate at p+e+2).                                            */
  1255  /* ------------------------------------------------------------------ */
  1256  decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
  1257                          decContext *set) {
  1258    uInt status=0;                   // accumulator
  1259    #if DECSUBSET
  1260    decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
  1261    #endif
  1262  
  1263    #if DECCHECK
  1264    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1265    #endif
  1266  
  1267    // Check restrictions; this is a math function; if not violated
  1268    // then carry out the operation.
  1269    if (!decCheckMath(rhs, set, &status)) do { // protect allocation
  1270      #if DECSUBSET
  1271      if (!set->extended) {
  1272        // reduce operand and set lostDigits status, as needed
  1273        if (rhs->digits>set->digits) {
  1274          allocrhs=decRoundOperand(rhs, set, &status);
  1275          if (allocrhs==NULL) break;
  1276          rhs=allocrhs;
  1277          }
  1278        // special check in subset for rhs=0
  1279        if (ISZERO(rhs)) {                // +/- zeros -> error
  1280          status|=DEC_Invalid_operation;
  1281          break;}
  1282        } // extended=0
  1283      #endif
  1284      decLnOp(res, rhs, set, &status);
  1285      } while(0);                         // end protected
  1286  
  1287    #if DECSUBSET
  1288    if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
  1289    #endif
  1290    // apply significant status
  1291    if (status!=0) decStatus(res, status, set);
  1292    #if DECCHECK
  1293    decCheckInexact(res, set);
  1294    #endif
  1295    return res;
  1296    } // decNumberLn
  1297  
  1298  /* ------------------------------------------------------------------ */
  1299  /* decNumberLogB - get adjusted exponent, by 754 rules                */
  1300  /*                                                                    */
  1301  /*   This computes C = adjustedexponent(A)                            */
  1302  /*                                                                    */
  1303  /*   res is C, the result.  C may be A                                */
  1304  /*   rhs is A                                                         */
  1305  /*   set is the context, used only for digits and status              */
  1306  /*                                                                    */
  1307  /* For an unrounded result, digits may need to be 10 (A might have    */
  1308  /* 10**9 digits and an exponent of +999999999, or one digit and an    */
  1309  /* exponent of -1999999999).                                          */
  1310  /*                                                                    */
  1311  /* This returns the adjusted exponent of A after (in theory) padding  */
  1312  /* with zeros on the right to set->digits digits while keeping the    */
  1313  /* same value.  The exponent is not limited by emin/emax.             */
  1314  /*                                                                    */
  1315  /* Notable cases:                                                     */
  1316  /*   A<0 -> Use |A|                                                   */
  1317  /*   A=0 -> -Infinity (Division by zero)                              */
  1318  /*   A=Infinite -> +Infinity (Exact)                                  */
  1319  /*   A=1 exactly -> 0 (Exact)                                         */
  1320  /*   NaNs are propagated as usual                                     */
  1321  /* ------------------------------------------------------------------ */
  1322  decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
  1323                            decContext *set) {
  1324    uInt status=0;                   // accumulator
  1325  
  1326    #if DECCHECK
  1327    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1328    #endif
  1329  
  1330    // NaNs as usual; Infinities return +Infinity; 0->oops
  1331    if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
  1332     else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
  1333     else if (decNumberIsZero(rhs)) {
  1334      decNumberZero(res);                 // prepare for Infinity
  1335      res->bits=DECNEG|DECINF;            // -Infinity
  1336      status|=DEC_Division_by_zero;       // as per 754
  1337      }
  1338     else { // finite non-zero
  1339      Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
  1340      if (set->digits>=10) decNumberFromInt32(res, ae);  // lay it out
  1341       else {
  1342        decNumber buft[D2N(10)];          // temporary number
  1343        decNumber *t=buft;                // ..
  1344        decNumberFromInt32(t, ae);        // lay it out
  1345        decNumberPlus(res, t, set);       // round as necessary
  1346        }
  1347      }
  1348  
  1349    if (status!=0) decStatus(res, status, set);
  1350    return res;
  1351    } // decNumberLogB
  1352  
  1353  /* ------------------------------------------------------------------ */
  1354  /* decNumberLog10 -- logarithm in base 10                             */
  1355  /*                                                                    */
  1356  /*   This computes C = log10(A)                                       */
  1357  /*                                                                    */
  1358  /*   res is C, the result.  C may be A                                */
  1359  /*   rhs is A                                                         */
  1360  /*   set is the context; note that rounding mode has no effect        */
  1361  /*                                                                    */
  1362  /* C must have space for set->digits digits.                          */
  1363  /*                                                                    */
  1364  /* Notable cases:                                                     */
  1365  /*   A<0 -> Invalid                                                   */
  1366  /*   A=0 -> -Infinity (Exact)                                         */
  1367  /*   A=+Infinity -> +Infinity (Exact)                                 */
  1368  /*   A=10**n (if n is an integer) -> n (Exact)                        */
  1369  /*                                                                    */
  1370  /* Mathematical function restrictions apply (see above); a NaN is     */
  1371  /* returned with Invalid_operation if a restriction is violated.      */
  1372  /*                                                                    */
  1373  /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
  1374  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  1375  /* error in rare cases.                                               */
  1376  /* ------------------------------------------------------------------ */
  1377  /* This calculates ln(A)/ln(10) using appropriate precision.  For     */
  1378  /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
  1379  /* requested digits and t is the number of digits in the exponent     */
  1380  /* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
  1381  /* fastpath in decLnOp.  The final division is done to the requested  */
  1382  /* precision.                                                         */
  1383  /* ------------------------------------------------------------------ */
  1384  decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
  1385                            decContext *set) {
  1386    uInt status=0, ignore=0;         // status accumulators
  1387    uInt needbytes;                  // for space calculations
  1388    Int p;                           // working precision
  1389    Int t;                           // digits in exponent of A
  1390  
  1391    // buffers for a and b working decimals
  1392    // (adjustment calculator, same size)
  1393    decNumber bufa[D2N(DECBUFFER+2)];
  1394    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
  1395    decNumber *a=bufa;               // temporary a
  1396    decNumber bufb[D2N(DECBUFFER+2)];
  1397    decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
  1398    decNumber *b=bufb;               // temporary b
  1399    decNumber bufw[D2N(10)];         // working 2-10 digit number
  1400    decNumber *w=bufw;               // ..
  1401    #if DECSUBSET
  1402    decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
  1403    #endif
  1404  
  1405    decContext aset;                 // working context
  1406  
  1407    #if DECCHECK
  1408    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1409    #endif
  1410  
  1411    // Check restrictions; this is a math function; if not violated
  1412    // then carry out the operation.
  1413    if (!decCheckMath(rhs, set, &status)) do { // protect malloc
  1414      #if DECSUBSET
  1415      if (!set->extended) {
  1416        // reduce operand and set lostDigits status, as needed
  1417        if (rhs->digits>set->digits) {
  1418          allocrhs=decRoundOperand(rhs, set, &status);
  1419          if (allocrhs==NULL) break;
  1420          rhs=allocrhs;
  1421          }
  1422        // special check in subset for rhs=0
  1423        if (ISZERO(rhs)) {                // +/- zeros -> error
  1424          status|=DEC_Invalid_operation;
  1425          break;}
  1426        } // extended=0
  1427      #endif
  1428  
  1429      decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
  1430  
  1431      // handle exact powers of 10; only check if +ve finite
  1432      if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
  1433        Int residue=0;               // (no residue)
  1434        uInt copystat=0;             // clean status
  1435  
  1436        // round to a single digit...
  1437        aset.digits=1;
  1438        decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten
  1439        // if exact and the digit is 1, rhs is a power of 10
  1440        if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
  1441          // the exponent, conveniently, is the power of 10; making
  1442          // this the result needs a little care as it might not fit,
  1443          // so first convert it into the working number, and then move
  1444          // to res
  1445          decNumberFromInt32(w, w->exponent);
  1446          residue=0;
  1447          decCopyFit(res, w, set, &residue, &status); // copy & round
  1448          decFinish(res, set, &residue, &status);     // cleanup/set flags
  1449          break;
  1450          } // not a power of 10
  1451        } // not a candidate for exact
  1452  
  1453      // simplify the information-content calculation to use 'total
  1454      // number of digits in a, including exponent' as compared to the
  1455      // requested digits, as increasing this will only rarely cost an
  1456      // iteration in ln(a) anyway
  1457      t=6;                                // it can never be >6
  1458  
  1459      // allocate space when needed...
  1460      p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
  1461      needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1462      if (needbytes>sizeof(bufa)) {       // need malloc space
  1463        allocbufa=(decNumber *)malloc(needbytes);
  1464        if (allocbufa==NULL) {            // hopeless -- abandon
  1465          status|=DEC_Insufficient_storage;
  1466          break;}
  1467        a=allocbufa;                      // use the allocated space
  1468        }
  1469      aset.digits=p;                      // as calculated
  1470      aset.emax=DEC_MAX_MATH;             // usual bounds
  1471      aset.emin=-DEC_MAX_MATH;            // ..
  1472      aset.clamp=0;                       // and no concrete format
  1473      decLnOp(a, rhs, &aset, &status);    // a=ln(rhs)
  1474  
  1475      // skip the division if the result so far is infinite, NaN, or
  1476      // zero, or there was an error; note NaN from sNaN needs copy
  1477      if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
  1478      if (a->bits&DECSPECIAL || ISZERO(a)) {
  1479        decNumberCopy(res, a);            // [will fit]
  1480        break;}
  1481  
  1482      // for ln(10) an extra 3 digits of precision are needed
  1483      p=set->digits+3;
  1484      needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
  1485      if (needbytes>sizeof(bufb)) {       // need malloc space
  1486        allocbufb=(decNumber *)malloc(needbytes);
  1487        if (allocbufb==NULL) {            // hopeless -- abandon
  1488          status|=DEC_Insufficient_storage;
  1489          break;}
  1490        b=allocbufb;                      // use the allocated space
  1491        }
  1492      decNumberZero(w);                   // set up 10...
  1493      #if DECDPUN==1
  1494      w->lsu[1]=1; w->lsu[0]=0;           // ..
  1495      #else
  1496      w->lsu[0]=10;                       // ..
  1497      #endif
  1498      w->digits=2;                        // ..
  1499  
  1500      aset.digits=p;
  1501      decLnOp(b, w, &aset, &ignore);      // b=ln(10)
  1502  
  1503      aset.digits=set->digits;            // for final divide
  1504      decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
  1505      } while(0);                         // [for break]
  1506  
  1507    if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  1508    if (allocbufb!=NULL) free(allocbufb); // ..
  1509    #if DECSUBSET
  1510    if (allocrhs !=NULL) free(allocrhs);  // ..
  1511    #endif
  1512    // apply significant status
  1513    if (status!=0) decStatus(res, status, set);
  1514    #if DECCHECK
  1515    decCheckInexact(res, set);
  1516    #endif
  1517    return res;
  1518    } // decNumberLog10
  1519  
  1520  /* ------------------------------------------------------------------ */
  1521  /* decNumberMax -- compare two Numbers and return the maximum         */
  1522  /*                                                                    */
  1523  /*   This computes C = A ? B, returning the maximum by 754 rules      */
  1524  /*                                                                    */
  1525  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
  1526  /*   lhs is A                                                         */
  1527  /*   rhs is B                                                         */
  1528  /*   set is the context                                               */
  1529  /*                                                                    */
  1530  /* C must have space for set->digits digits.                          */
  1531  /* ------------------------------------------------------------------ */
  1532  decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
  1533                           const decNumber *rhs, decContext *set) {
  1534    uInt status=0;                        // accumulator
  1535    decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
  1536    if (status!=0) decStatus(res, status, set);
  1537    #if DECCHECK
  1538    decCheckInexact(res, set);
  1539    #endif
  1540    return res;
  1541    } // decNumberMax
  1542  
  1543  /* ------------------------------------------------------------------ */
  1544  /* decNumberMaxMag -- compare and return the maximum by magnitude     */
  1545  /*                                                                    */
  1546  /*   This computes C = A ? B, returning the maximum by 754 rules      */
  1547  /*                                                                    */
  1548  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
  1549  /*   lhs is A                                                         */
  1550  /*   rhs is B                                                         */
  1551  /*   set is the context                                               */
  1552  /*                                                                    */
  1553  /* C must have space for set->digits digits.                          */
  1554  /* ------------------------------------------------------------------ */
  1555  decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
  1556                           const decNumber *rhs, decContext *set) {
  1557    uInt status=0;                        // accumulator
  1558    decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
  1559    if (status!=0) decStatus(res, status, set);
  1560    #if DECCHECK
  1561    decCheckInexact(res, set);
  1562    #endif
  1563    return res;
  1564    } // decNumberMaxMag
  1565  
  1566  /* ------------------------------------------------------------------ */
  1567  /* decNumberMin -- compare two Numbers and return the minimum         */
  1568  /*                                                                    */
  1569  /*   This computes C = A ? B, returning the minimum by 754 rules      */
  1570  /*                                                                    */
  1571  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
  1572  /*   lhs is A                                                         */
  1573  /*   rhs is B                                                         */
  1574  /*   set is the context                                               */
  1575  /*                                                                    */
  1576  /* C must have space for set->digits digits.                          */
  1577  /* ------------------------------------------------------------------ */
  1578  decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
  1579                           const decNumber *rhs, decContext *set) {
  1580    uInt status=0;                        // accumulator
  1581    decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
  1582    if (status!=0) decStatus(res, status, set);
  1583    #if DECCHECK
  1584    decCheckInexact(res, set);
  1585    #endif
  1586    return res;
  1587    } // decNumberMin
  1588  
  1589  /* ------------------------------------------------------------------ */
  1590  /* decNumberMinMag -- compare and return the minimum by magnitude     */
  1591  /*                                                                    */
  1592  /*   This computes C = A ? B, returning the minimum by 754 rules      */
  1593  /*                                                                    */
  1594  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
  1595  /*   lhs is A                                                         */
  1596  /*   rhs is B                                                         */
  1597  /*   set is the context                                               */
  1598  /*                                                                    */
  1599  /* C must have space for set->digits digits.                          */
  1600  /* ------------------------------------------------------------------ */
  1601  decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
  1602                           const decNumber *rhs, decContext *set) {
  1603    uInt status=0;                        // accumulator
  1604    decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
  1605    if (status!=0) decStatus(res, status, set);
  1606    #if DECCHECK
  1607    decCheckInexact(res, set);
  1608    #endif
  1609    return res;
  1610    } // decNumberMinMag
  1611  
  1612  /* ------------------------------------------------------------------ */
  1613  /* decNumberMinus -- prefix minus operator                            */
  1614  /*                                                                    */
  1615  /*   This computes C = 0 - A                                          */
  1616  /*                                                                    */
  1617  /*   res is C, the result.  C may be A                                */
  1618  /*   rhs is A                                                         */
  1619  /*   set is the context                                               */
  1620  /*                                                                    */
  1621  /* See also decNumberCopyNegate for a quiet bitwise version of this.  */
  1622  /* C must have space for set->digits digits.                          */
  1623  /* ------------------------------------------------------------------ */
  1624  /* Simply use AddOp for the subtract, which will do the necessary.    */
  1625  /* ------------------------------------------------------------------ */
  1626  decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
  1627                             decContext *set) {
  1628    decNumber dzero;
  1629    uInt status=0;                        // accumulator
  1630  
  1631    #if DECCHECK
  1632    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1633    #endif
  1634  
  1635    decNumberZero(&dzero);                // make 0
  1636    dzero.exponent=rhs->exponent;         // [no coefficient expansion]
  1637    decAddOp(res, &dzero, rhs, set, DECNEG, &status);
  1638    if (status!=0) decStatus(res, status, set);
  1639    #if DECCHECK
  1640    decCheckInexact(res, set);
  1641    #endif
  1642    return res;
  1643    } // decNumberMinus
  1644  
  1645  /* ------------------------------------------------------------------ */
  1646  /* decNumberNextMinus -- next towards -Infinity                       */
  1647  /*                                                                    */
  1648  /*   This computes C = A - infinitesimal, rounded towards -Infinity   */
  1649  /*                                                                    */
  1650  /*   res is C, the result.  C may be A                                */
  1651  /*   rhs is A                                                         */
  1652  /*   set is the context                                               */
  1653  /*                                                                    */
  1654  /* This is a generalization of 754 NextDown.                          */
  1655  /* ------------------------------------------------------------------ */
  1656  decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
  1657                                 decContext *set) {
  1658    decNumber dtiny;                           // constant
  1659    decContext workset=*set;                   // work
  1660    uInt status=0;                             // accumulator
  1661    #if DECCHECK
  1662    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1663    #endif
  1664  
  1665    // +Infinity is the special case
  1666    if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
  1667      decSetMaxValue(res, set);                // is +ve
  1668      // there is no status to set
  1669      return res;
  1670      }
  1671    decNumberZero(&dtiny);                     // start with 0
  1672    dtiny.lsu[0]=1;                            // make number that is ..
  1673    dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
  1674    workset.round=DEC_ROUND_FLOOR;
  1675    decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
  1676    status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
  1677    if (status!=0) decStatus(res, status, set);
  1678    return res;
  1679    } // decNumberNextMinus
  1680  
  1681  /* ------------------------------------------------------------------ */
  1682  /* decNumberNextPlus -- next towards +Infinity                        */
  1683  /*                                                                    */
  1684  /*   This computes C = A + infinitesimal, rounded towards +Infinity   */
  1685  /*                                                                    */
  1686  /*   res is C, the result.  C may be A                                */
  1687  /*   rhs is A                                                         */
  1688  /*   set is the context                                               */
  1689  /*                                                                    */
  1690  /* This is a generalization of 754 NextUp.                            */
  1691  /* ------------------------------------------------------------------ */
  1692  decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
  1693                                decContext *set) {
  1694    decNumber dtiny;                           // constant
  1695    decContext workset=*set;                   // work
  1696    uInt status=0;                             // accumulator
  1697    #if DECCHECK
  1698    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1699    #endif
  1700  
  1701    // -Infinity is the special case
  1702    if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1703      decSetMaxValue(res, set);
  1704      res->bits=DECNEG;                        // negative
  1705      // there is no status to set
  1706      return res;
  1707      }
  1708    decNumberZero(&dtiny);                     // start with 0
  1709    dtiny.lsu[0]=1;                            // make number that is ..
  1710    dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
  1711    workset.round=DEC_ROUND_CEILING;
  1712    decAddOp(res, rhs, &dtiny, &workset, 0, &status);
  1713    status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
  1714    if (status!=0) decStatus(res, status, set);
  1715    return res;
  1716    } // decNumberNextPlus
  1717  
  1718  /* ------------------------------------------------------------------ */
  1719  /* decNumberNextToward -- next towards rhs                            */
  1720  /*                                                                    */
  1721  /*   This computes C = A +/- infinitesimal, rounded towards           */
  1722  /*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
  1723  /*   modified during revision but dropped from 754-2008.              */
  1724  /*                                                                    */
  1725  /*   res is C, the result.  C may be A or B.                          */
  1726  /*   lhs is A                                                         */
  1727  /*   rhs is B                                                         */
  1728  /*   set is the context                                               */
  1729  /*                                                                    */
  1730  /* This is a generalization of 754-1985 NextAfter.                    */
  1731  /* ------------------------------------------------------------------ */
  1732  decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
  1733                                  const decNumber *rhs, decContext *set) {
  1734    decNumber dtiny;                           // constant
  1735    decContext workset=*set;                   // work
  1736    Int result;                                // ..
  1737    uInt status=0;                             // accumulator
  1738    #if DECCHECK
  1739    if (decCheckOperands(res, lhs, rhs, set)) return res;
  1740    #endif
  1741  
  1742    if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
  1743      decNaNs(res, lhs, rhs, set, &status);
  1744      }
  1745     else { // Is numeric, so no chance of sNaN Invalid, etc.
  1746      result=decCompare(lhs, rhs, 0);     // sign matters
  1747      if (result==BADINT) status|=DEC_Insufficient_storage; // rare
  1748       else { // valid compare
  1749        if (result==0) decNumberCopySign(res, lhs, rhs); // easy
  1750         else { // differ: need NextPlus or NextMinus
  1751          uByte sub;                      // add or subtract
  1752          if (result<0) {                 // lhs<rhs, do nextplus
  1753            // -Infinity is the special case
  1754            if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
  1755              decSetMaxValue(res, set);
  1756              res->bits=DECNEG;           // negative
  1757              return res;                 // there is no status to set
  1758              }
  1759            workset.round=DEC_ROUND_CEILING;
  1760            sub=0;                        // add, please
  1761            } // plus
  1762           else {                         // lhs>rhs, do nextminus
  1763            // +Infinity is the special case
  1764            if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
  1765              decSetMaxValue(res, set);
  1766              return res;                 // there is no status to set
  1767              }
  1768            workset.round=DEC_ROUND_FLOOR;
  1769            sub=DECNEG;                   // subtract, please
  1770            } // minus
  1771          decNumberZero(&dtiny);          // start with 0
  1772          dtiny.lsu[0]=1;                 // make number that is ..
  1773          dtiny.exponent=DEC_MIN_EMIN-1;  // .. smaller than tiniest
  1774          decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
  1775          // turn off exceptions if the result is a normal number
  1776          // (including Nmin), otherwise let all status through
  1777          if (decNumberIsNormal(res, set)) status=0;
  1778          } // unequal
  1779        } // compare OK
  1780      } // numeric
  1781    if (status!=0) decStatus(res, status, set);
  1782    return res;
  1783    } // decNumberNextToward
  1784  
  1785  /* ------------------------------------------------------------------ */
  1786  /* decNumberOr -- OR two Numbers, digitwise                           */
  1787  /*                                                                    */
  1788  /*   This computes C = A | B                                          */
  1789  /*                                                                    */
  1790  /*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
  1791  /*   lhs is A                                                         */
  1792  /*   rhs is B                                                         */
  1793  /*   set is the context (used for result length and error report)     */
  1794  /*                                                                    */
  1795  /* C must have space for set->digits digits.                          */
  1796  /*                                                                    */
  1797  /* Logical function restrictions apply (see above); a NaN is          */
  1798  /* returned with Invalid_operation if a restriction is violated.      */
  1799  /* ------------------------------------------------------------------ */
  1800  decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
  1801                          const decNumber *rhs, decContext *set) {
  1802    const Unit *ua, *ub;                  // -> operands
  1803    const Unit *msua, *msub;              // -> operand msus
  1804    Unit  *uc, *msuc;                     // -> result and its msu
  1805    Int   msudigs;                        // digits in res msu
  1806    #if DECCHECK
  1807    if (decCheckOperands(res, lhs, rhs, set)) return res;
  1808    #endif
  1809  
  1810    if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  1811     || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  1812      decStatus(res, DEC_Invalid_operation, set);
  1813      return res;
  1814      }
  1815    // operands are valid
  1816    ua=lhs->lsu;                          // bottom-up
  1817    ub=rhs->lsu;                          // ..
  1818    uc=res->lsu;                          // ..
  1819    msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
  1820    msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
  1821    msuc=uc+D2U(set->digits)-1;           // -> msu of result
  1822    msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
  1823    for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
  1824      Unit a, b;                          // extract units
  1825      if (ua>msua) a=0;
  1826       else a=*ua;
  1827      if (ub>msub) b=0;
  1828       else b=*ub;
  1829      *uc=0;                              // can now write back
  1830      if (a|b) {                          // maybe 1 bits to examine
  1831        Int i, j;
  1832        // This loop could be unrolled and/or use BIN2BCD tables
  1833        for (i=0; i<DECDPUN; i++) {
  1834          if ((a|b)&1) *uc=*uc+(Unit)powers[i];     // effect OR
  1835          j=a%10;
  1836          a=a/10;
  1837          j|=b%10;
  1838          b=b/10;
  1839          if (j>1) {
  1840            decStatus(res, DEC_Invalid_operation, set);
  1841            return res;
  1842            }
  1843          if (uc==msuc && i==msudigs-1) break;      // just did final digit
  1844          } // each digit
  1845        } // non-zero
  1846      } // each unit
  1847    // [here uc-1 is the msu of the result]
  1848    res->digits=decGetDigits(res->lsu, uc-res->lsu);
  1849    res->exponent=0;                      // integer
  1850    res->bits=0;                          // sign=0
  1851    return res;  // [no status to set]
  1852    } // decNumberOr
  1853  
  1854  /* ------------------------------------------------------------------ */
  1855  /* decNumberPlus -- prefix plus operator                              */
  1856  /*                                                                    */
  1857  /*   This computes C = 0 + A                                          */
  1858  /*                                                                    */
  1859  /*   res is C, the result.  C may be A                                */
  1860  /*   rhs is A                                                         */
  1861  /*   set is the context                                               */
  1862  /*                                                                    */
  1863  /* See also decNumberCopy for a quiet bitwise version of this.        */
  1864  /* C must have space for set->digits digits.                          */
  1865  /* ------------------------------------------------------------------ */
  1866  /* This simply uses AddOp; Add will take fast path after preparing A. */
  1867  /* Performance is a concern here, as this routine is often used to    */
  1868  /* check operands and apply rounding and overflow/underflow testing.  */
  1869  /* ------------------------------------------------------------------ */
  1870  decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
  1871                            decContext *set) {
  1872    decNumber dzero;
  1873    uInt status=0;                        // accumulator
  1874    #if DECCHECK
  1875    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  1876    #endif
  1877  
  1878    decNumberZero(&dzero);                // make 0
  1879    dzero.exponent=rhs->exponent;         // [no coefficient expansion]
  1880    decAddOp(res, &dzero, rhs, set, 0, &status);
  1881    if (status!=0) decStatus(res, status, set);
  1882    #if DECCHECK
  1883    decCheckInexact(res, set);
  1884    #endif
  1885    return res;
  1886    } // decNumberPlus
  1887  
  1888  /* ------------------------------------------------------------------ */
  1889  /* decNumberMultiply -- multiply two Numbers                          */
  1890  /*                                                                    */
  1891  /*   This computes C = A x B                                          */
  1892  /*                                                                    */
  1893  /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
  1894  /*   lhs is A                                                         */
  1895  /*   rhs is B                                                         */
  1896  /*   set is the context                                               */
  1897  /*                                                                    */
  1898  /* C must have space for set->digits digits.                          */
  1899  /* ------------------------------------------------------------------ */
  1900  decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
  1901                                const decNumber *rhs, decContext *set) {
  1902    uInt status=0;                   // accumulator
  1903    decMultiplyOp(res, lhs, rhs, set, &status);
  1904    if (status!=0) decStatus(res, status, set);
  1905    #if DECCHECK
  1906    decCheckInexact(res, set);
  1907    #endif
  1908    return res;
  1909    } // decNumberMultiply
  1910  
  1911  /* ------------------------------------------------------------------ */
  1912  /* decNumberPower -- raise a number to a power                        */
  1913  /*                                                                    */
  1914  /*   This computes C = A ** B                                         */
  1915  /*                                                                    */
  1916  /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
  1917  /*   lhs is A                                                         */
  1918  /*   rhs is B                                                         */
  1919  /*   set is the context                                               */
  1920  /*                                                                    */
  1921  /* C must have space for set->digits digits.                          */
  1922  /*                                                                    */
  1923  /* Mathematical function restrictions apply (see above); a NaN is     */
  1924  /* returned with Invalid_operation if a restriction is violated.      */
  1925  /*                                                                    */
  1926  /* However, if 1999999997<=B<=999999999 and B is an integer then the  */
  1927  /* restrictions on A and the context are relaxed to the usual bounds, */
  1928  /* for compatibility with the earlier (integer power only) version    */
  1929  /* of this function.                                                  */
  1930  /*                                                                    */
  1931  /* When B is an integer, the result may be exact, even if rounded.    */
  1932  /*                                                                    */
  1933  /* The final result is rounded according to the context; it will      */
  1934  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  1935  /* error in rare cases.                                               */
  1936  /* ------------------------------------------------------------------ */
  1937  decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
  1938                             const decNumber *rhs, decContext *set) {
  1939    #if DECSUBSET
  1940    decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
  1941    decNumber *allocrhs=NULL;        // .., rhs
  1942    #endif
  1943    decNumber *allocdac=NULL;        // -> allocated acc buffer, iff used
  1944    decNumber *allocinv=NULL;        // -> allocated 1/x buffer, iff used
  1945    Int   reqdigits=set->digits;     // requested DIGITS
  1946    Int   n;                         // rhs in binary
  1947    Flag  rhsint=0;                  // 1 if rhs is an integer
  1948    Flag  useint=0;                  // 1 if can use integer calculation
  1949    Flag  isoddint=0;                // 1 if rhs is an integer and odd
  1950    Int   i;                         // work
  1951    #if DECSUBSET
  1952    Int   dropped;                   // ..
  1953    #endif
  1954    uInt  needbytes;                 // buffer size needed
  1955    Flag  seenbit;                   // seen a bit while powering
  1956    Int   residue=0;                 // rounding residue
  1957    uInt  status=0;                  // accumulators
  1958    uByte bits=0;                    // result sign if errors
  1959    decContext aset;                 // working context
  1960    decNumber dnOne;                 // work value 1...
  1961    // local accumulator buffer [a decNumber, with digits+elength+1 digits]
  1962    decNumber dacbuff[D2N(DECBUFFER+9)];
  1963    decNumber *dac=dacbuff;          // -> result accumulator
  1964    // same again for possible 1/lhs calculation
  1965    decNumber invbuff[D2N(DECBUFFER+9)];
  1966  
  1967    #if DECCHECK
  1968    if (decCheckOperands(res, lhs, rhs, set)) return res;
  1969    #endif
  1970  
  1971    do {                             // protect allocated storage
  1972      #if DECSUBSET
  1973      if (!set->extended) { // reduce operands and set status, as needed
  1974        if (lhs->digits>reqdigits) {
  1975          alloclhs=decRoundOperand(lhs, set, &status);
  1976          if (alloclhs==NULL) break;
  1977          lhs=alloclhs;
  1978          }
  1979        if (rhs->digits>reqdigits) {
  1980          allocrhs=decRoundOperand(rhs, set, &status);
  1981          if (allocrhs==NULL) break;
  1982          rhs=allocrhs;
  1983          }
  1984        }
  1985      #endif
  1986      // [following code does not require input rounding]
  1987  
  1988      // handle NaNs and rhs Infinity (lhs infinity is harder)
  1989      if (SPECIALARGS) {
  1990        if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
  1991          decNaNs(res, lhs, rhs, set, &status);
  1992          break;}
  1993        if (decNumberIsInfinite(rhs)) {   // rhs Infinity
  1994          Flag rhsneg=rhs->bits&DECNEG;   // save rhs sign
  1995          if (decNumberIsNegative(lhs)    // lhs<0
  1996           && !decNumberIsZero(lhs))      // ..
  1997            status|=DEC_Invalid_operation;
  1998           else {                         // lhs >=0
  1999            decNumberZero(&dnOne);        // set up 1
  2000            dnOne.lsu[0]=1;
  2001            decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1
  2002            decNumberZero(res);           // prepare for 0/1/Infinity
  2003            if (decNumberIsNegative(dac)) {    // lhs<1
  2004              if (rhsneg) res->bits|=DECINF;   // +Infinity [else is +0]
  2005              }
  2006             else if (dac->lsu[0]==0) {        // lhs=1
  2007              // 1**Infinity is inexact, so return fully-padded 1.0000
  2008              Int shift=set->digits-1;
  2009              *res->lsu=1;                     // was 0, make int 1
  2010              res->digits=decShiftToMost(res->lsu, 1, shift);
  2011              res->exponent=-shift;            // make 1.0000...
  2012              status|=DEC_Inexact|DEC_Rounded; // deemed inexact
  2013              }
  2014             else {                            // lhs>1
  2015              if (!rhsneg) res->bits|=DECINF;  // +Infinity [else is +0]
  2016              }
  2017            } // lhs>=0
  2018          break;}
  2019        // [lhs infinity drops through]
  2020        } // specials
  2021  
  2022      // Original rhs may be an integer that fits and is in range
  2023      n=decGetInt(rhs);
  2024      if (n!=BADINT) {                    // it is an integer
  2025        rhsint=1;                         // record the fact for 1**n
  2026        isoddint=(Flag)n&1;               // [works even if big]
  2027        if (n!=BIGEVEN && n!=BIGODD)      // can use integer path?
  2028          useint=1;                       // looks good
  2029        }
  2030  
  2031      if (decNumberIsNegative(lhs)        // -x ..
  2032        && isoddint) bits=DECNEG;         // .. to an odd power
  2033  
  2034      // handle LHS infinity
  2035      if (decNumberIsInfinite(lhs)) {     // [NaNs already handled]
  2036        uByte rbits=rhs->bits;            // save
  2037        decNumberZero(res);               // prepare
  2038        if (n==0) *res->lsu=1;            // [-]Inf**0 => 1
  2039         else {
  2040          // -Inf**nonint -> error
  2041          if (!rhsint && decNumberIsNegative(lhs)) {
  2042            status|=DEC_Invalid_operation;     // -Inf**nonint is error
  2043            break;}
  2044          if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n
  2045          // [otherwise will be 0 or -0]
  2046          res->bits=bits;
  2047          }
  2048        break;}
  2049  
  2050      // similarly handle LHS zero
  2051      if (decNumberIsZero(lhs)) {
  2052        if (n==0) {                            // 0**0 => Error
  2053          #if DECSUBSET
  2054          if (!set->extended) {                // [unless subset]
  2055            decNumberZero(res);
  2056            *res->lsu=1;                       // return 1
  2057            break;}
  2058          #endif
  2059          status|=DEC_Invalid_operation;
  2060          }
  2061         else {                                // 0**x
  2062          uByte rbits=rhs->bits;               // save
  2063          if (rbits & DECNEG) {                // was a 0**(-n)
  2064            #if DECSUBSET
  2065            if (!set->extended) {              // [bad if subset]
  2066              status|=DEC_Invalid_operation;
  2067              break;}
  2068            #endif
  2069            bits|=DECINF;
  2070            }
  2071          decNumberZero(res);                  // prepare
  2072          // [otherwise will be 0 or -0]
  2073          res->bits=bits;
  2074          }
  2075        break;}
  2076  
  2077      // here both lhs and rhs are finite; rhs==0 is handled in the
  2078      // integer path.  Next handle the non-integer cases
  2079      if (!useint) {                      // non-integral rhs
  2080        // any -ve lhs is bad, as is either operand or context out of
  2081        // bounds
  2082        if (decNumberIsNegative(lhs)) {
  2083          status|=DEC_Invalid_operation;
  2084          break;}
  2085        if (decCheckMath(lhs, set, &status)
  2086         || decCheckMath(rhs, set, &status)) break; // variable status
  2087  
  2088        decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
  2089        aset.emax=DEC_MAX_MATH;           // usual bounds
  2090        aset.emin=-DEC_MAX_MATH;          // ..
  2091        aset.clamp=0;                     // and no concrete format
  2092  
  2093        // calculate the result using exp(ln(lhs)*rhs), which can
  2094        // all be done into the accumulator, dac.  The precision needed
  2095        // is enough to contain the full information in the lhs (which
  2096        // is the total digits, including exponent), or the requested
  2097        // precision, if larger, + 4; 6 is used for the exponent
  2098        // maximum length, and this is also used when it is shorter
  2099        // than the requested digits as it greatly reduces the >0.5 ulp
  2100        // cases at little cost (because Ln doubles digits each
  2101        // iteration so a few extra digits rarely causes an extra
  2102        // iteration)
  2103        aset.digits=MAXI(lhs->digits, set->digits)+6+4;
  2104        } // non-integer rhs
  2105  
  2106       else { // rhs is in-range integer
  2107        if (n==0) {                       // x**0 = 1
  2108          // (0**0 was handled above)
  2109          decNumberZero(res);             // result=1
  2110          *res->lsu=1;                    // ..
  2111          break;}
  2112        // rhs is a non-zero integer
  2113        if (n<0) n=-n;                    // use abs(n)
  2114  
  2115        aset=*set;                        // clone the context
  2116        aset.round=DEC_ROUND_HALF_EVEN;   // internally use balanced
  2117        // calculate the working DIGITS
  2118        aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
  2119        #if DECSUBSET
  2120        if (!set->extended) aset.digits--;     // use classic precision
  2121        #endif
  2122        // it's an error if this is more than can be handled
  2123        if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
  2124        } // integer path
  2125  
  2126      // aset.digits is the count of digits for the accumulator needed
  2127      // if accumulator is too long for local storage, then allocate
  2128      needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
  2129      // [needbytes also used below if 1/lhs needed]
  2130      if (needbytes>sizeof(dacbuff)) {
  2131        allocdac=(decNumber *)malloc(needbytes);
  2132        if (allocdac==NULL) {   // hopeless -- abandon
  2133          status|=DEC_Insufficient_storage;
  2134          break;}
  2135        dac=allocdac;           // use the allocated space
  2136        }
  2137      // here, aset is set up and accumulator is ready for use
  2138  
  2139      if (!useint) {                           // non-integral rhs
  2140        // x ** y; special-case x=1 here as it will otherwise always
  2141        // reduce to integer 1; decLnOp has a fastpath which detects
  2142        // the case of x=1
  2143        decLnOp(dac, lhs, &aset, &status);     // dac=ln(lhs)
  2144        // [no error possible, as lhs 0 already handled]
  2145        if (ISZERO(dac)) {                     // x==1, 1.0, etc.
  2146          // need to return fully-padded 1.0000 etc., but rhsint->1
  2147          *dac->lsu=1;                         // was 0, make int 1
  2148          if (!rhsint) {                       // add padding
  2149            Int shift=set->digits-1;
  2150            dac->digits=decShiftToMost(dac->lsu, 1, shift);
  2151            dac->exponent=-shift;              // make 1.0000...
  2152            status|=DEC_Inexact|DEC_Rounded;   // deemed inexact
  2153            }
  2154          }
  2155         else {
  2156          decMultiplyOp(dac, dac, rhs, &aset, &status);  // dac=dac*rhs
  2157          decExpOp(dac, dac, &aset, &status);            // dac=exp(dac)
  2158          }
  2159        // and drop through for final rounding
  2160        } // non-integer rhs
  2161  
  2162       else {                             // carry on with integer
  2163        decNumberZero(dac);               // acc=1
  2164        *dac->lsu=1;                      // ..
  2165  
  2166        // if a negative power the constant 1 is needed, and if not subset
  2167        // invert the lhs now rather than inverting the result later
  2168        if (decNumberIsNegative(rhs)) {   // was a **-n [hence digits>0]
  2169          decNumber *inv=invbuff;         // asssume use fixed buffer
  2170          decNumberCopy(&dnOne, dac);     // dnOne=1;  [needed now or later]
  2171          #if DECSUBSET
  2172          if (set->extended) {            // need to calculate 1/lhs
  2173          #endif
  2174            // divide lhs into 1, putting result in dac [dac=1/dac]
  2175            decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
  2176            // now locate or allocate space for the inverted lhs
  2177            if (needbytes>sizeof(invbuff)) {
  2178              allocinv=(decNumber *)malloc(needbytes);
  2179              if (allocinv==NULL) {       // hopeless -- abandon
  2180                status|=DEC_Insufficient_storage;
  2181                break;}
  2182              inv=allocinv;               // use the allocated space
  2183              }
  2184            // [inv now points to big-enough buffer or allocated storage]
  2185            decNumberCopy(inv, dac);      // copy the 1/lhs
  2186            decNumberCopy(dac, &dnOne);   // restore acc=1
  2187            lhs=inv;                      // .. and go forward with new lhs
  2188          #if DECSUBSET
  2189            }
  2190          #endif
  2191          }
  2192  
  2193        // Raise-to-the-power loop...
  2194        seenbit=0;                   // set once a 1-bit is encountered
  2195        for (i=1;;i++){              // for each bit [top bit ignored]
  2196          // abandon if had overflow or terminal underflow
  2197          if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?
  2198            if (status&DEC_Overflow || ISZERO(dac)) break;
  2199            }
  2200          // [the following two lines revealed an optimizer bug in a C++
  2201          // compiler, with symptom: 5**3 -> 25, when n=n+n was used]
  2202          n=n<<1;                    // move next bit to testable position
  2203          if (n<0) {                 // top bit is set
  2204            seenbit=1;               // OK, significant bit seen
  2205            decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x
  2206            }
  2207          if (i==31) break;          // that was the last bit
  2208          if (!seenbit) continue;    // no need to square 1
  2209          decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]
  2210          } /*i*/ // 32 bits
  2211  
  2212        // complete internal overflow or underflow processing
  2213        if (status & (DEC_Overflow|DEC_Underflow)) {
  2214          #if DECSUBSET
  2215          // If subset, and power was negative, reverse the kind of -erflow
  2216          // [1/x not yet done]
  2217          if (!set->extended && decNumberIsNegative(rhs)) {
  2218            if (status & DEC_Overflow)
  2219              status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
  2220             else { // trickier -- Underflow may or may not be set
  2221              status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]
  2222              status|=DEC_Overflow;
  2223              }
  2224            }
  2225          #endif
  2226          dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign
  2227          // round subnormals [to set.digits rather than aset.digits]
  2228          // or set overflow result similarly as required
  2229          decFinalize(dac, set, &residue, &status);
  2230          decNumberCopy(res, dac);   // copy to result (is now OK length)
  2231          break;
  2232          }
  2233  
  2234        #if DECSUBSET
  2235        if (!set->extended &&                  // subset math
  2236            decNumberIsNegative(rhs)) {        // was a **-n [hence digits>0]
  2237          // so divide result into 1 [dac=1/dac]
  2238          decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
  2239          }
  2240        #endif
  2241        } // rhs integer path
  2242  
  2243      // reduce result to the requested length and copy to result
  2244      decCopyFit(res, dac, set, &residue, &status);
  2245      decFinish(res, set, &residue, &status);  // final cleanup
  2246      #if DECSUBSET
  2247      if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros
  2248      #endif
  2249      } while(0);                         // end protected
  2250  
  2251    if (allocdac!=NULL) free(allocdac);   // drop any storage used
  2252    if (allocinv!=NULL) free(allocinv);   // ..
  2253    #if DECSUBSET
  2254    if (alloclhs!=NULL) free(alloclhs);   // ..
  2255    if (allocrhs!=NULL) free(allocrhs);   // ..
  2256    #endif
  2257    if (status!=0) decStatus(res, status, set);
  2258    #if DECCHECK
  2259    decCheckInexact(res, set);
  2260    #endif
  2261    return res;
  2262    } // decNumberPower
  2263  
  2264  /* ------------------------------------------------------------------ */
  2265  /* decNumberQuantize -- force exponent to requested value             */
  2266  /*                                                                    */
  2267  /*   This computes C = op(A, B), where op adjusts the coefficient     */
  2268  /*   of C (by rounding or shifting) such that the exponent (-scale)   */
  2269  /*   of C has exponent of B.  The numerical value of C will equal A,  */
  2270  /*   except for the effects of any rounding that occurred.            */
  2271  /*                                                                    */
  2272  /*   res is C, the result.  C may be A or B                           */
  2273  /*   lhs is A, the number to adjust                                   */
  2274  /*   rhs is B, the number with exponent to match                      */
  2275  /*   set is the context                                               */
  2276  /*                                                                    */
  2277  /* C must have space for set->digits digits.                          */
  2278  /*                                                                    */
  2279  /* Unless there is an error or the result is infinite, the exponent   */
  2280  /* after the operation is guaranteed to be equal to that of B.        */
  2281  /* ------------------------------------------------------------------ */
  2282  decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
  2283                                const decNumber *rhs, decContext *set) {
  2284    uInt status=0;                        // accumulator
  2285    decQuantizeOp(res, lhs, rhs, set, 1, &status);
  2286    if (status!=0) decStatus(res, status, set);
  2287    return res;
  2288    } // decNumberQuantize
  2289  
  2290  /* ------------------------------------------------------------------ */
  2291  /* decNumberReduce -- remove trailing zeros                           */
  2292  /*                                                                    */
  2293  /*   This computes C = 0 + A, and normalizes the result               */
  2294  /*                                                                    */
  2295  /*   res is C, the result.  C may be A                                */
  2296  /*   rhs is A                                                         */
  2297  /*   set is the context                                               */
  2298  /*                                                                    */
  2299  /* C must have space for set->digits digits.                          */
  2300  /* ------------------------------------------------------------------ */
  2301  // Previously known as Normalize
  2302  decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
  2303                                 decContext *set) {
  2304    return decNumberReduce(res, rhs, set);
  2305    } // decNumberNormalize
  2306  
  2307  decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
  2308                              decContext *set) {
  2309    #if DECSUBSET
  2310    decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
  2311    #endif
  2312    uInt status=0;                   // as usual
  2313    Int  residue=0;                  // as usual
  2314    Int  dropped;                    // work
  2315  
  2316    #if DECCHECK
  2317    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2318    #endif
  2319  
  2320    do {                             // protect allocated storage
  2321      #if DECSUBSET
  2322      if (!set->extended) {
  2323        // reduce operand and set lostDigits status, as needed
  2324        if (rhs->digits>set->digits) {
  2325          allocrhs=decRoundOperand(rhs, set, &status);
  2326          if (allocrhs==NULL) break;
  2327          rhs=allocrhs;
  2328          }
  2329        }
  2330      #endif
  2331      // [following code does not require input rounding]
  2332  
  2333      // Infinities copy through; NaNs need usual treatment
  2334      if (decNumberIsNaN(rhs)) {
  2335        decNaNs(res, rhs, NULL, set, &status);
  2336        break;
  2337        }
  2338  
  2339      // reduce result to the requested length and copy to result
  2340      decCopyFit(res, rhs, set, &residue, &status); // copy & round
  2341      decFinish(res, set, &residue, &status);       // cleanup/set flags
  2342      decTrim(res, set, 1, 0, &dropped);            // normalize in place
  2343                                                    // [may clamp]
  2344      } while(0);                              // end protected
  2345  
  2346    #if DECSUBSET
  2347    if (allocrhs !=NULL) free(allocrhs);       // ..
  2348    #endif
  2349    if (status!=0) decStatus(res, status, set);// then report status
  2350    return res;
  2351    } // decNumberReduce
  2352  
  2353  /* ------------------------------------------------------------------ */
  2354  /* decNumberRescale -- force exponent to requested value              */
  2355  /*                                                                    */
  2356  /*   This computes C = op(A, B), where op adjusts the coefficient     */
  2357  /*   of C (by rounding or shifting) such that the exponent (-scale)   */
  2358  /*   of C has the value B.  The numerical value of C will equal A,    */
  2359  /*   except for the effects of any rounding that occurred.            */
  2360  /*                                                                    */
  2361  /*   res is C, the result.  C may be A or B                           */
  2362  /*   lhs is A, the number to adjust                                   */
  2363  /*   rhs is B, the requested exponent                                 */
  2364  /*   set is the context                                               */
  2365  /*                                                                    */
  2366  /* C must have space for set->digits digits.                          */
  2367  /*                                                                    */
  2368  /* Unless there is an error or the result is infinite, the exponent   */
  2369  /* after the operation is guaranteed to be equal to B.                */
  2370  /* ------------------------------------------------------------------ */
  2371  decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
  2372                               const decNumber *rhs, decContext *set) {
  2373    uInt status=0;                        // accumulator
  2374    decQuantizeOp(res, lhs, rhs, set, 0, &status);
  2375    if (status!=0) decStatus(res, status, set);
  2376    return res;
  2377    } // decNumberRescale
  2378  
  2379  /* ------------------------------------------------------------------ */
  2380  /* decNumberRemainder -- divide and return remainder                  */
  2381  /*                                                                    */
  2382  /*   This computes C = A % B                                          */
  2383  /*                                                                    */
  2384  /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
  2385  /*   lhs is A                                                         */
  2386  /*   rhs is B                                                         */
  2387  /*   set is the context                                               */
  2388  /*                                                                    */
  2389  /* C must have space for set->digits digits.                          */
  2390  /* ------------------------------------------------------------------ */
  2391  decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
  2392                                 const decNumber *rhs, decContext *set) {
  2393    uInt status=0;                        // accumulator
  2394    decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
  2395    if (status!=0) decStatus(res, status, set);
  2396    #if DECCHECK
  2397    decCheckInexact(res, set);
  2398    #endif
  2399    return res;
  2400    } // decNumberRemainder
  2401  
  2402  /* ------------------------------------------------------------------ */
  2403  /* decNumberRemainderNear -- divide and return remainder from nearest */
  2404  /*                                                                    */
  2405  /*   This computes C = A % B, where % is the IEEE remainder operator  */
  2406  /*                                                                    */
  2407  /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
  2408  /*   lhs is A                                                         */
  2409  /*   rhs is B                                                         */
  2410  /*   set is the context                                               */
  2411  /*                                                                    */
  2412  /* C must have space for set->digits digits.                          */
  2413  /* ------------------------------------------------------------------ */
  2414  decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
  2415                                     const decNumber *rhs, decContext *set) {
  2416    uInt status=0;                        // accumulator
  2417    decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
  2418    if (status!=0) decStatus(res, status, set);
  2419    #if DECCHECK
  2420    decCheckInexact(res, set);
  2421    #endif
  2422    return res;
  2423    } // decNumberRemainderNear
  2424  
  2425  /* ------------------------------------------------------------------ */
  2426  /* decNumberRotate -- rotate the coefficient of a Number left/right   */
  2427  /*                                                                    */
  2428  /*   This computes C = A rot B  (in base ten and rotating set->digits */
  2429  /*   digits).                                                         */
  2430  /*                                                                    */
  2431  /*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
  2432  /*   lhs is A                                                         */
  2433  /*   rhs is B, the number of digits to rotate (-ve to right)          */
  2434  /*   set is the context                                               */
  2435  /*                                                                    */
  2436  /* The digits of the coefficient of A are rotated to the left (if B   */
  2437  /* is positive) or to the right (if B is negative) without adjusting  */
  2438  /* the exponent or the sign of A.  If lhs->digits is less than        */
  2439  /* set->digits the coefficient is padded with zeros on the left       */
  2440  /* before the rotate.  Any leading zeros in the result are removed    */
  2441  /* as usual.                                                          */
  2442  /*                                                                    */
  2443  /* B must be an integer (q=0) and in the range -set->digits through   */
  2444  /* +set->digits.                                                      */
  2445  /* C must have space for set->digits digits.                          */
  2446  /* NaNs are propagated as usual.  Infinities are unaffected (but      */
  2447  /* B must be valid).  No status is set unless B is invalid or an      */
  2448  /* operand is an sNaN.                                                */
  2449  /* ------------------------------------------------------------------ */
  2450  decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
  2451                             const decNumber *rhs, decContext *set) {
  2452    uInt status=0;              // accumulator
  2453    Int  rotate;                // rhs as an Int
  2454  
  2455    #if DECCHECK
  2456    if (decCheckOperands(res, lhs, rhs, set)) return res;
  2457    #endif
  2458  
  2459    // NaNs propagate as normal
  2460    if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2461      decNaNs(res, lhs, rhs, set, &status);
  2462     // rhs must be an integer
  2463     else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2464      status=DEC_Invalid_operation;
  2465     else { // both numeric, rhs is an integer
  2466      rotate=decGetInt(rhs);                   // [cannot fail]
  2467      if (rotate==BADINT                       // something bad ..
  2468       || rotate==BIGODD || rotate==BIGEVEN    // .. very big ..
  2469       || abs(rotate)>set->digits)             // .. or out of range
  2470        status=DEC_Invalid_operation;
  2471       else {                                  // rhs is OK
  2472        decNumberCopy(res, lhs);
  2473        // convert -ve rotate to equivalent positive rotation
  2474        if (rotate<0) rotate=set->digits+rotate;
  2475        if (rotate!=0 && rotate!=set->digits   // zero or full rotation
  2476         && !decNumberIsInfinite(res)) {       // lhs was infinite
  2477          // left-rotate to do; 0 < rotate < set->digits
  2478          uInt units, shift;                   // work
  2479          uInt msudigits;                      // digits in result msu
  2480          Unit *msu=res->lsu+D2U(res->digits)-1;    // current msu
  2481          Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu
  2482          for (msu++; msu<=msumax; msu++) *msu=0;   // ensure high units=0
  2483          res->digits=set->digits;                  // now full-length
  2484          msudigits=MSUDIGITS(res->digits);         // actual digits in msu
  2485  
  2486          // rotation here is done in-place, in three steps
  2487          // 1. shift all to least up to one unit to unit-align final
  2488          //    lsd [any digits shifted out are rotated to the left,
  2489          //    abutted to the original msd (which may require split)]
  2490          //
  2491          //    [if there are no whole units left to rotate, the
  2492          //    rotation is now complete]
  2493          //
  2494          // 2. shift to least, from below the split point only, so that
  2495          //    the final msd is in the right place in its Unit [any
  2496          //    digits shifted out will fit exactly in the current msu,
  2497          //    left aligned, no split required]
  2498          //
  2499          // 3. rotate all the units by reversing left part, right
  2500          //    part, and then whole
  2501          //
  2502          // example: rotate right 8 digits (2 units + 2), DECDPUN=3.
  2503          //
  2504          //   start: 00a bcd efg hij klm npq
  2505          //
  2506          //      1a  000 0ab cde fgh|ijk lmn [pq saved]
  2507          //      1b  00p qab cde fgh|ijk lmn
  2508          //
  2509          //      2a  00p qab cde fgh|00i jkl [mn saved]
  2510          //      2b  mnp qab cde fgh|00i jkl
  2511          //
  2512          //      3a  fgh cde qab mnp|00i jkl
  2513          //      3b  fgh cde qab mnp|jkl 00i
  2514          //      3c  00i jkl mnp qab cde fgh
  2515  
  2516          // Step 1: amount to shift is the partial right-rotate count
  2517          rotate=set->digits-rotate;      // make it right-rotate
  2518          units=rotate/DECDPUN;           // whole units to rotate
  2519          shift=rotate%DECDPUN;           // left-over digits count
  2520          if (shift>0) {                  // not an exact number of units
  2521            uInt save=res->lsu[0]%powers[shift];    // save low digit(s)
  2522            decShiftToLeast(res->lsu, D2U(res->digits), shift);
  2523            if (shift>msudigits) {        // msumax-1 needs >0 digits
  2524              uInt rem=save%powers[shift-msudigits];// split save
  2525              *msumax=(Unit)(save/powers[shift-msudigits]); // and insert
  2526              *(msumax-1)=*(msumax-1)
  2527                         +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..
  2528              }
  2529             else { // all fits in msumax
  2530              *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]
  2531              }
  2532            } // digits shift needed
  2533  
  2534          // If whole units to rotate...
  2535          if (units>0) {                  // some to do
  2536            // Step 2: the units to touch are the whole ones in rotate,
  2537            //   if any, and the shift is DECDPUN-msudigits (which may be
  2538            //   0, again)
  2539            shift=DECDPUN-msudigits;
  2540            if (shift>0) {                // not an exact number of units
  2541              uInt save=res->lsu[0]%powers[shift];  // save low digit(s)
  2542              decShiftToLeast(res->lsu, units, shift);
  2543              *msumax=*msumax+(Unit)(save*powers[msudigits]);
  2544              } // partial shift needed
  2545  
  2546            // Step 3: rotate the units array using triple reverse
  2547            // (reversing is easy and fast)
  2548            decReverse(res->lsu+units, msumax);     // left part
  2549            decReverse(res->lsu, res->lsu+units-1); // right part
  2550            decReverse(res->lsu, msumax);           // whole
  2551            } // whole units to rotate
  2552          // the rotation may have left an undetermined number of zeros
  2553          // on the left, so true length needs to be calculated
  2554          res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
  2555          } // rotate needed
  2556        } // rhs OK
  2557      } // numerics
  2558    if (status!=0) decStatus(res, status, set);
  2559    return res;
  2560    } // decNumberRotate
  2561  
  2562  /* ------------------------------------------------------------------ */
  2563  /* decNumberSameQuantum -- test for equal exponents                   */
  2564  /*                                                                    */
  2565  /*   res is the result number, which will contain either 0 or 1       */
  2566  /*   lhs is a number to test                                          */
  2567  /*   rhs is the second (usually a pattern)                            */
  2568  /*                                                                    */
  2569  /* No errors are possible and no context is needed.                   */
  2570  /* ------------------------------------------------------------------ */
  2571  decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
  2572                                   const decNumber *rhs) {
  2573    Unit ret=0;                      // return value
  2574  
  2575    #if DECCHECK
  2576    if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
  2577    #endif
  2578  
  2579    if (SPECIALARGS) {
  2580      if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
  2581       else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
  2582       // [anything else with a special gives 0]
  2583      }
  2584     else if (lhs->exponent==rhs->exponent) ret=1;
  2585  
  2586    decNumberZero(res);              // OK to overwrite an operand now
  2587    *res->lsu=ret;
  2588    return res;
  2589    } // decNumberSameQuantum
  2590  
  2591  /* ------------------------------------------------------------------ */
  2592  /* decNumberScaleB -- multiply by a power of 10                       */
  2593  /*                                                                    */
  2594  /* This computes C = A x 10**B where B is an integer (q=0) with       */
  2595  /* maximum magnitude 2*(emax+digits)                                  */
  2596  /*                                                                    */
  2597  /*   res is C, the result.  C may be A or B                           */
  2598  /*   lhs is A, the number to adjust                                   */
  2599  /*   rhs is B, the requested power of ten to use                      */
  2600  /*   set is the context                                               */
  2601  /*                                                                    */
  2602  /* C must have space for set->digits digits.                          */
  2603  /*                                                                    */
  2604  /* The result may underflow or overflow.                              */
  2605  /* ------------------------------------------------------------------ */
  2606  decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
  2607                              const decNumber *rhs, decContext *set) {
  2608    Int  reqexp;                // requested exponent change [B]
  2609    uInt status=0;              // accumulator
  2610    Int  residue;               // work
  2611  
  2612    #if DECCHECK
  2613    if (decCheckOperands(res, lhs, rhs, set)) return res;
  2614    #endif
  2615  
  2616    // Handle special values except lhs infinite
  2617    if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2618      decNaNs(res, lhs, rhs, set, &status);
  2619      // rhs must be an integer
  2620     else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2621      status=DEC_Invalid_operation;
  2622     else {
  2623      // lhs is a number; rhs is a finite with q==0
  2624      reqexp=decGetInt(rhs);                   // [cannot fail]
  2625      // maximum range is larger than getInt can handle, so this is
  2626      // more restrictive than the specification
  2627      if (reqexp==BADINT                       // something bad ..
  2628       || reqexp==BIGODD || reqexp==BIGEVEN    // it was huge
  2629       || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range
  2630        status=DEC_Invalid_operation;
  2631       else {                                  // rhs is OK
  2632        decNumberCopy(res, lhs);               // all done if infinite lhs
  2633        if (!decNumberIsInfinite(res)) {       // prepare to scale
  2634          Int exp=res->exponent;               // save for overflow test
  2635          res->exponent+=reqexp;               // adjust the exponent
  2636          if (((exp^reqexp)>=0)                // same sign ...
  2637           && ((exp^res->exponent)<0)) {       // .. but result had different
  2638            // the calculation overflowed, so force right treatment
  2639            if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;
  2640             else      res->exponent=DEC_MAX_EMAX+1;
  2641            }
  2642          residue=0;
  2643          decFinalize(res, set, &residue, &status); // final check
  2644          } // finite LHS
  2645        } // rhs OK
  2646      } // rhs finite
  2647    if (status!=0) decStatus(res, status, set);
  2648    return res;
  2649    } // decNumberScaleB
  2650  
  2651  /* ------------------------------------------------------------------ */
  2652  /* decNumberShift -- shift the coefficient of a Number left or right  */
  2653  /*                                                                    */
  2654  /*   This computes C = A << B or C = A >> -B  (in base ten).          */
  2655  /*                                                                    */
  2656  /*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
  2657  /*   lhs is A                                                         */
  2658  /*   rhs is B, the number of digits to shift (-ve to right)           */
  2659  /*   set is the context                                               */
  2660  /*                                                                    */
  2661  /* The digits of the coefficient of A are shifted to the left (if B   */
  2662  /* is positive) or to the right (if B is negative) without adjusting  */
  2663  /* the exponent or the sign of A.                                     */
  2664  /*                                                                    */
  2665  /* B must be an integer (q=0) and in the range -set->digits through   */
  2666  /* +set->digits.                                                      */
  2667  /* C must have space for set->digits digits.                          */
  2668  /* NaNs are propagated as usual.  Infinities are unaffected (but      */
  2669  /* B must be valid).  No status is set unless B is invalid or an      */
  2670  /* operand is an sNaN.                                                */
  2671  /* ------------------------------------------------------------------ */
  2672  decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
  2673                             const decNumber *rhs, decContext *set) {
  2674    uInt status=0;              // accumulator
  2675    Int  shift;                 // rhs as an Int
  2676  
  2677    #if DECCHECK
  2678    if (decCheckOperands(res, lhs, rhs, set)) return res;
  2679    #endif
  2680  
  2681    // NaNs propagate as normal
  2682    if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
  2683      decNaNs(res, lhs, rhs, set, &status);
  2684     // rhs must be an integer
  2685     else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
  2686      status=DEC_Invalid_operation;
  2687     else { // both numeric, rhs is an integer
  2688      shift=decGetInt(rhs);                    // [cannot fail]
  2689      if (shift==BADINT                        // something bad ..
  2690       || shift==BIGODD || shift==BIGEVEN      // .. very big ..
  2691       || abs(shift)>set->digits)              // .. or out of range
  2692        status=DEC_Invalid_operation;
  2693       else {                                  // rhs is OK
  2694        decNumberCopy(res, lhs);
  2695        if (shift!=0 && !decNumberIsInfinite(res)) { // something to do
  2696          if (shift>0) {                       // to left
  2697            if (shift==set->digits) {          // removing all
  2698              *res->lsu=0;                     // so place 0
  2699              res->digits=1;                   // ..
  2700              }
  2701             else {                            //
  2702              // first remove leading digits if necessary
  2703              if (res->digits+shift>set->digits) {
  2704                decDecap(res, res->digits+shift-set->digits);
  2705                // that updated res->digits; may have gone to 1 (for a
  2706                // single digit or for zero
  2707                }
  2708              if (res->digits>1 || *res->lsu)  // if non-zero..
  2709                res->digits=decShiftToMost(res->lsu, res->digits, shift);
  2710              } // partial left
  2711            } // left
  2712           else { // to right
  2713            if (-shift>=res->digits) {         // discarding all
  2714              *res->lsu=0;                     // so place 0
  2715              res->digits=1;                   // ..
  2716              }
  2717             else {
  2718              decShiftToLeast(res->lsu, D2U(res->digits), -shift);
  2719              res->digits-=(-shift);
  2720              }
  2721            } // to right
  2722          } // non-0 non-Inf shift
  2723        } // rhs OK
  2724      } // numerics
  2725    if (status!=0) decStatus(res, status, set);
  2726    return res;
  2727    } // decNumberShift
  2728  
  2729  /* ------------------------------------------------------------------ */
  2730  /* decNumberSquareRoot -- square root operator                        */
  2731  /*                                                                    */
  2732  /*   This computes C = squareroot(A)                                  */
  2733  /*                                                                    */
  2734  /*   res is C, the result.  C may be A                                */
  2735  /*   rhs is A                                                         */
  2736  /*   set is the context; note that rounding mode has no effect        */
  2737  /*                                                                    */
  2738  /* C must have space for set->digits digits.                          */
  2739  /* ------------------------------------------------------------------ */
  2740  /* This uses the following varying-precision algorithm in:            */
  2741  /*                                                                    */
  2742  /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
  2743  /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
  2744  /*   pp229-237, ACM, September 1985.                                  */
  2745  /*                                                                    */
  2746  /* The square-root is calculated using Newton's method, after which   */
  2747  /* a check is made to ensure the result is correctly rounded.         */
  2748  /*                                                                    */
  2749  /* % [Reformatted original Numerical Turing source code follows.]     */
  2750  /* function sqrt(x : real) : real                                     */
  2751  /* % sqrt(x) returns the properly rounded approximation to the square */
  2752  /* % root of x, in the precision of the calling environment, or it    */
  2753  /* % fails if x < 0.                                                  */
  2754  /* % t e hull and a abrham, august, 1984                              */
  2755  /* if x <= 0 then                                                     */
  2756  /*   if x < 0 then                                                    */
  2757  /*     assert false                                                   */
  2758  /*   else                                                             */
  2759  /*     result 0                                                       */
  2760  /*   end if                                                           */
  2761  /* end if                                                             */
  2762  /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
  2763  /* var e := getexp(x)     % exponent part of x                        */
  2764  /* var approx : real                                                  */
  2765  /* if e mod 2 = 0  then                                               */
  2766  /*   approx := .259 + .819 * f   % approx to root of f                */
  2767  /* else                                                               */
  2768  /*   f := f/l0                   % adjustments                        */
  2769  /*   e := e + 1                  %   for odd                          */
  2770  /*   approx := .0819 + 2.59 * f  %   exponent                         */
  2771  /* end if                                                             */
  2772  /*                                                                    */
  2773  /* var p:= 3                                                          */
  2774  /* const maxp := currentprecision + 2                                 */
  2775  /* loop                                                               */
  2776  /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
  2777  /*   precision p                                                      */
  2778  /*   approx := .5 * (approx + f/approx)                               */
  2779  /*   exit when p = maxp                                               */
  2780  /* end loop                                                           */
  2781  /*                                                                    */
  2782  /* % approx is now within 1 ulp of the properly rounded square root   */
  2783  /* % of f; to ensure proper rounding, compare squares of (approx -    */
  2784  /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
  2785  /* p := currentprecision                                              */
  2786  /* begin                                                              */
  2787  /*   precision p + 2                                                  */
  2788  /*   const approxsubhalf := approx - setexp(.5, -p)                   */
  2789  /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
  2790  /*     approx := approx - setexp(.l, -p + 1)                          */
  2791  /*   else                                                             */
  2792  /*     const approxaddhalf := approx + setexp(.5, -p)                 */
  2793  /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
  2794  /*       approx := approx + setexp(.l, -p + 1)                        */
  2795  /*     end if                                                         */
  2796  /*   end if                                                           */
  2797  /* end                                                                */
  2798  /* result setexp(approx, e div 2)  % fix exponent                     */
  2799  /* end sqrt                                                           */
  2800  /* ------------------------------------------------------------------ */
  2801  decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
  2802                                  decContext *set) {
  2803    decContext workset, approxset;   // work contexts
  2804    decNumber dzero;                 // used for constant zero
  2805    Int  maxp;                       // largest working precision
  2806    Int  workp;                      // working precision
  2807    Int  residue=0;                  // rounding residue
  2808    uInt status=0, ignore=0;         // status accumulators
  2809    uInt rstatus;                    // ..
  2810    Int  exp;                        // working exponent
  2811    Int  ideal;                      // ideal (preferred) exponent
  2812    Int  needbytes;                  // work
  2813    Int  dropped;                    // ..
  2814  
  2815    #if DECSUBSET
  2816    decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
  2817    #endif
  2818    // buffer for f [needs +1 in case DECBUFFER 0]
  2819    decNumber buff[D2N(DECBUFFER+1)];
  2820    // buffer for a [needs +2 to match likely maxp]
  2821    decNumber bufa[D2N(DECBUFFER+2)];
  2822    // buffer for temporary, b [must be same size as a]
  2823    decNumber bufb[D2N(DECBUFFER+2)];
  2824    decNumber *allocbuff=NULL;       // -> allocated buff, iff allocated
  2825    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
  2826    decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
  2827    decNumber *f=buff;               // reduced fraction
  2828    decNumber *a=bufa;               // approximation to result
  2829    decNumber *b=bufb;               // intermediate result
  2830    // buffer for temporary variable, up to 3 digits
  2831    decNumber buft[D2N(3)];
  2832    decNumber *t=buft;               // up-to-3-digit constant or work
  2833  
  2834    #if DECCHECK
  2835    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  2836    #endif
  2837  
  2838    do {                             // protect allocated storage
  2839      #if DECSUBSET
  2840      if (!set->extended) {
  2841        // reduce operand and set lostDigits status, as needed
  2842        if (rhs->digits>set->digits) {
  2843          allocrhs=decRoundOperand(rhs, set, &status);
  2844          if (allocrhs==NULL) break;
  2845          // [Note: 'f' allocation below could reuse this buffer if
  2846          // used, but as this is rare they are kept separate for clarity.]
  2847          rhs=allocrhs;
  2848          }
  2849        }
  2850      #endif
  2851      // [following code does not require input rounding]
  2852  
  2853      // handle infinities and NaNs
  2854      if (SPECIALARG) {
  2855        if (decNumberIsInfinite(rhs)) {         // an infinity
  2856          if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
  2857           else decNumberCopy(res, rhs);        // +Infinity
  2858          }
  2859         else decNaNs(res, rhs, NULL, set, &status); // a NaN
  2860        break;
  2861        }
  2862  
  2863      // calculate the ideal (preferred) exponent [floor(exp/2)]
  2864      // [It would be nicer to write: ideal=rhs->exponent>>1, but this
  2865      // generates a compiler warning.  Generated code is the same.]
  2866      ideal=(rhs->exponent&~1)/2;         // target
  2867  
  2868      // handle zeros
  2869      if (ISZERO(rhs)) {
  2870        decNumberCopy(res, rhs);          // could be 0 or -0
  2871        res->exponent=ideal;              // use the ideal [safe]
  2872        // use decFinish to clamp any out-of-range exponent, etc.
  2873        decFinish(res, set, &residue, &status);
  2874        break;
  2875        }
  2876  
  2877      // any other -x is an oops
  2878      if (decNumberIsNegative(rhs)) {
  2879        status|=DEC_Invalid_operation;
  2880        break;
  2881        }
  2882  
  2883      // space is needed for three working variables
  2884      //   f -- the same precision as the RHS, reduced to 0.01->0.99...
  2885      //   a -- Hull's approximation -- precision, when assigned, is
  2886      //        currentprecision+1 or the input argument precision,
  2887      //        whichever is larger (+2 for use as temporary)
  2888      //   b -- intermediate temporary result (same size as a)
  2889      // if any is too long for local storage, then allocate
  2890      workp=MAXI(set->digits+1, rhs->digits);  // actual rounding precision
  2891      workp=MAXI(workp, 7);                    // at least 7 for low cases
  2892      maxp=workp+2;                            // largest working precision
  2893  
  2894      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  2895      if (needbytes>(Int)sizeof(buff)) {
  2896        allocbuff=(decNumber *)malloc(needbytes);
  2897        if (allocbuff==NULL) {  // hopeless -- abandon
  2898          status|=DEC_Insufficient_storage;
  2899          break;}
  2900        f=allocbuff;            // use the allocated space
  2901        }
  2902      // a and b both need to be able to hold a maxp-length number
  2903      needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
  2904      if (needbytes>(Int)sizeof(bufa)) {            // [same applies to b]
  2905        allocbufa=(decNumber *)malloc(needbytes);
  2906        allocbufb=(decNumber *)malloc(needbytes);
  2907        if (allocbufa==NULL || allocbufb==NULL) {   // hopeless
  2908          status|=DEC_Insufficient_storage;
  2909          break;}
  2910        a=allocbufa;            // use the allocated spaces
  2911        b=allocbufb;            // ..
  2912        }
  2913  
  2914      // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1
  2915      decNumberCopy(f, rhs);
  2916      exp=f->exponent+f->digits;               // adjusted to Hull rules
  2917      f->exponent=-(f->digits);                // to range
  2918  
  2919      // set up working context
  2920      decContextDefault(&workset, DEC_INIT_DECIMAL64);
  2921      workset.emax=DEC_MAX_EMAX;
  2922      workset.emin=DEC_MIN_EMIN;
  2923  
  2924      // [Until further notice, no error is possible and status bits
  2925      // (Rounded, etc.) should be ignored, not accumulated.]
  2926  
  2927      // Calculate initial approximation, and allow for odd exponent
  2928      workset.digits=workp;                    // p for initial calculation
  2929      t->bits=0; t->digits=3;
  2930      a->bits=0; a->digits=3;
  2931      if ((exp & 1)==0) {                      // even exponent
  2932        // Set t=0.259, a=0.819
  2933        t->exponent=-3;
  2934        a->exponent=-3;
  2935        #if DECDPUN>=3
  2936          t->lsu[0]=259;
  2937          a->lsu[0]=819;
  2938        #elif DECDPUN==2
  2939          t->lsu[0]=59; t->lsu[1]=2;
  2940          a->lsu[0]=19; a->lsu[1]=8;
  2941        #else
  2942          t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
  2943          a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
  2944        #endif
  2945        }
  2946       else {                                  // odd exponent
  2947        // Set t=0.0819, a=2.59
  2948        f->exponent--;                         // f=f/10
  2949        exp++;                                 // e=e+1
  2950        t->exponent=-4;
  2951        a->exponent=-2;
  2952        #if DECDPUN>=3
  2953          t->lsu[0]=819;
  2954          a->lsu[0]=259;
  2955        #elif DECDPUN==2
  2956          t->lsu[0]=19; t->lsu[1]=8;
  2957          a->lsu[0]=59; a->lsu[1]=2;
  2958        #else
  2959          t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
  2960          a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
  2961        #endif
  2962        }
  2963  
  2964      decMultiplyOp(a, a, f, &workset, &ignore);    // a=a*f
  2965      decAddOp(a, a, t, &workset, 0, &ignore);      // ..+t
  2966      // [a is now the initial approximation for sqrt(f), calculated with
  2967      // currentprecision, which is also a's precision.]
  2968  
  2969      // the main calculation loop
  2970      decNumberZero(&dzero);                   // make 0
  2971      decNumberZero(t);                        // set t = 0.5
  2972      t->lsu[0]=5;                             // ..
  2973      t->exponent=-1;                          // ..
  2974      workset.digits=3;                        // initial p
  2975      for (; workset.digits<maxp;) {
  2976        // set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]
  2977        workset.digits=MINI(workset.digits*2-2, maxp);
  2978        // a = 0.5 * (a + f/a)
  2979        // [calculated at p then rounded to currentprecision]
  2980        decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a
  2981        decAddOp(b, b, a, &workset, 0, &ignore);         // b=b+a
  2982        decMultiplyOp(a, b, t, &workset, &ignore);       // a=b*0.5
  2983        } // loop
  2984  
  2985      // Here, 0.1 <= a < 1 [Hull], and a has maxp digits
  2986      // now reduce to length, etc.; this needs to be done with a
  2987      // having the correct exponent so as to handle subnormals
  2988      // correctly
  2989      approxset=*set;                          // get emin, emax, etc.
  2990      approxset.round=DEC_ROUND_HALF_EVEN;
  2991      a->exponent+=exp/2;                      // set correct exponent
  2992      rstatus=0;                               // clear status
  2993      residue=0;                               // .. and accumulator
  2994      decCopyFit(a, a, &approxset, &residue, &rstatus);  // reduce (if needed)
  2995      decFinish(a, &approxset, &residue, &rstatus);      // clean and finalize
  2996  
  2997      // Overflow was possible if the input exponent was out-of-range,
  2998      // in which case quit
  2999      if (rstatus&DEC_Overflow) {
  3000        status=rstatus;                        // use the status as-is
  3001        decNumberCopy(res, a);                 // copy to result
  3002        break;
  3003        }
  3004  
  3005      // Preserve status except Inexact/Rounded
  3006      status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
  3007  
  3008      // Carry out the Hull correction
  3009      a->exponent-=exp/2;                      // back to 0.1->1
  3010  
  3011      // a is now at final precision and within 1 ulp of the properly
  3012      // rounded square root of f; to ensure proper rounding, compare
  3013      // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.
  3014      // Here workset.digits=maxp and t=0.5, and a->digits determines
  3015      // the ulp
  3016      workset.digits--;                             // maxp-1 is OK now
  3017      t->exponent=-a->digits-1;                     // make 0.5 ulp
  3018      decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp
  3019      workset.round=DEC_ROUND_UP;
  3020      decMultiplyOp(b, b, b, &workset, &ignore);    // b = mulru(b, b)
  3021      decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed
  3022      if (decNumberIsNegative(b)) {                 // f < b [i.e., b > f]
  3023        // this is the more common adjustment, though both are rare
  3024        t->exponent++;                              // make 1.0 ulp
  3025        t->lsu[0]=1;                                // ..
  3026        decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp
  3027        // assign to approx [round to length]
  3028        approxset.emin-=exp/2;                      // adjust to match a
  3029        approxset.emax-=exp/2;
  3030        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  3031        }
  3032       else {
  3033        decAddOp(b, a, t, &workset, 0, &ignore);    // b = a + 0.5 ulp
  3034        workset.round=DEC_ROUND_DOWN;
  3035        decMultiplyOp(b, b, b, &workset, &ignore);  // b = mulrd(b, b)
  3036        decCompareOp(b, b, f, &workset, COMPARE, &ignore);   // b ? f
  3037        if (decNumberIsNegative(b)) {               // b < f
  3038          t->exponent++;                            // make 1.0 ulp
  3039          t->lsu[0]=1;                              // ..
  3040          decAddOp(a, a, t, &workset, 0, &ignore);  // a = a + 1 ulp
  3041          // assign to approx [round to length]
  3042          approxset.emin-=exp/2;                    // adjust to match a
  3043          approxset.emax-=exp/2;
  3044          decAddOp(a, &dzero, a, &approxset, 0, &ignore);
  3045          }
  3046        }
  3047      // [no errors are possible in the above, and rounding/inexact during
  3048      // estimation are irrelevant, so status was not accumulated]
  3049  
  3050      // Here, 0.1 <= a < 1  (still), so adjust back
  3051      a->exponent+=exp/2;                      // set correct exponent
  3052  
  3053      // count droppable zeros [after any subnormal rounding] by
  3054      // trimming a copy
  3055      decNumberCopy(b, a);
  3056      decTrim(b, set, 1, 1, &dropped);         // [drops trailing zeros]
  3057  
  3058      // Set Inexact and Rounded.  The answer can only be exact if
  3059      // it is short enough so that squaring it could fit in workp
  3060      // digits, so this is the only (relatively rare) condition that
  3061      // a careful check is needed
  3062      if (b->digits*2-1 > workp) {             // cannot fit
  3063        status|=DEC_Inexact|DEC_Rounded;
  3064        }
  3065       else {                                  // could be exact/unrounded
  3066        uInt mstatus=0;                        // local status
  3067        decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply
  3068        if (mstatus&DEC_Overflow) {            // result just won't fit
  3069          status|=DEC_Inexact|DEC_Rounded;
  3070          }
  3071         else {                                // plausible
  3072          decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs
  3073          if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal
  3074           else {                              // is Exact
  3075            // here, dropped is the count of trailing zeros in 'a'
  3076            // use closest exponent to ideal...
  3077            Int todrop=ideal-a->exponent;      // most that can be dropped
  3078            if (todrop<0) status|=DEC_Rounded; // ideally would add 0s
  3079             else {                            // unrounded
  3080              // there are some to drop, but emax may not allow all
  3081              Int maxexp=set->emax-set->digits+1;
  3082              Int maxdrop=maxexp-a->exponent;
  3083              if (todrop>maxdrop && set->clamp) { // apply clamping
  3084                todrop=maxdrop;
  3085                status|=DEC_Clamped;
  3086                }
  3087              if (dropped<todrop) {            // clamp to those available
  3088                todrop=dropped;
  3089                status|=DEC_Clamped;
  3090                }
  3091              if (todrop>0) {                  // have some to drop
  3092                decShiftToLeast(a->lsu, D2U(a->digits), todrop);
  3093                a->exponent+=todrop;           // maintain numerical value
  3094                a->digits-=todrop;             // new length
  3095                }
  3096              }
  3097            }
  3098          }
  3099        }
  3100  
  3101      // double-check Underflow, as perhaps the result could not have
  3102      // been subnormal (initial argument too big), or it is now Exact
  3103      if (status&DEC_Underflow) {
  3104        Int ae=rhs->exponent+rhs->digits-1;    // adjusted exponent
  3105        // check if truly subnormal
  3106        #if DECEXTFLAG                         // DEC_Subnormal too
  3107          if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
  3108        #else
  3109          if (ae>=set->emin*2) status&=~DEC_Underflow;
  3110        #endif
  3111        // check if truly inexact
  3112        if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
  3113        }
  3114  
  3115      decNumberCopy(res, a);                   // a is now the result
  3116      } while(0);                              // end protected
  3117  
  3118    if (allocbuff!=NULL) free(allocbuff);      // drop any storage used
  3119    if (allocbufa!=NULL) free(allocbufa);      // ..
  3120    if (allocbufb!=NULL) free(allocbufb);      // ..
  3121    #if DECSUBSET
  3122    if (allocrhs !=NULL) free(allocrhs);       // ..
  3123    #endif
  3124    if (status!=0) decStatus(res, status, set);// then report status
  3125    #if DECCHECK
  3126    decCheckInexact(res, set);
  3127    #endif
  3128    return res;
  3129    } // decNumberSquareRoot
  3130  
  3131  /* ------------------------------------------------------------------ */
  3132  /* decNumberSubtract -- subtract two Numbers                          */
  3133  /*                                                                    */
  3134  /*   This computes C = A - B                                          */
  3135  /*                                                                    */
  3136  /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
  3137  /*   lhs is A                                                         */
  3138  /*   rhs is B                                                         */
  3139  /*   set is the context                                               */
  3140  /*                                                                    */
  3141  /* C must have space for set->digits digits.                          */
  3142  /* ------------------------------------------------------------------ */
  3143  decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
  3144                                const decNumber *rhs, decContext *set) {
  3145    uInt status=0;                        // accumulator
  3146  
  3147    decAddOp(res, lhs, rhs, set, DECNEG, &status);
  3148    if (status!=0) decStatus(res, status, set);
  3149    #if DECCHECK
  3150    decCheckInexact(res, set);
  3151    #endif
  3152    return res;
  3153    } // decNumberSubtract
  3154  
  3155  /* ------------------------------------------------------------------ */
  3156  /* decNumberToIntegralExact -- round-to-integral-value with InExact   */
  3157  /* decNumberToIntegralValue -- round-to-integral-value                */
  3158  /*                                                                    */
  3159  /*   res is the result                                                */
  3160  /*   rhs is input number                                              */
  3161  /*   set is the context                                               */
  3162  /*                                                                    */
  3163  /* res must have space for any value of rhs.                          */
  3164  /*                                                                    */
  3165  /* This implements the IEEE special operators and therefore treats    */
  3166  /* special values as valid.  For finite numbers it returns            */
  3167  /* rescale(rhs, 0) if rhs->exponent is <0.                            */
  3168  /* Otherwise the result is rhs (so no error is possible, except for   */
  3169  /* sNaN).                                                             */
  3170  /*                                                                    */
  3171  /* The context is used for rounding mode and status after sNaN, but   */
  3172  /* the digits setting is ignored.  The Exact version will signal      */
  3173  /* Inexact if the result differs numerically from rhs; the other      */
  3174  /* never signals Inexact.                                             */
  3175  /* ------------------------------------------------------------------ */
  3176  decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
  3177                                       decContext *set) {
  3178    decNumber dn;
  3179    decContext workset;              // working context
  3180    uInt status=0;                   // accumulator
  3181  
  3182    #if DECCHECK
  3183    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  3184    #endif
  3185  
  3186    // handle infinities and NaNs
  3187    if (SPECIALARG) {
  3188      if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity
  3189       else decNaNs(res, rhs, NULL, set, &status); // a NaN
  3190      }
  3191     else { // finite
  3192      // have a finite number; no error possible (res must be big enough)
  3193      if (rhs->exponent>=0) return decNumberCopy(res, rhs);
  3194      // that was easy, but if negative exponent there is work to do...
  3195      workset=*set;                  // clone rounding, etc.
  3196      workset.digits=rhs->digits;    // no length rounding
  3197      workset.traps=0;               // no traps
  3198      decNumberZero(&dn);            // make a number with exponent 0
  3199      decNumberQuantize(res, rhs, &dn, &workset);
  3200      status|=workset.status;
  3201      }
  3202    if (status!=0) decStatus(res, status, set);
  3203    return res;
  3204    } // decNumberToIntegralExact
  3205  
  3206  decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
  3207                                       decContext *set) {
  3208    decContext workset=*set;         // working context
  3209    workset.traps=0;                 // no traps
  3210    decNumberToIntegralExact(res, rhs, &workset);
  3211    // this never affects set, except for sNaNs; NaN will have been set
  3212    // or propagated already, so no need to call decStatus
  3213    set->status|=workset.status&DEC_Invalid_operation;
  3214    return res;
  3215    } // decNumberToIntegralValue
  3216  
  3217  /* ------------------------------------------------------------------ */
  3218  /* decNumberXor -- XOR two Numbers, digitwise                         */
  3219  /*                                                                    */
  3220  /*   This computes C = A ^ B                                          */
  3221  /*                                                                    */
  3222  /*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
  3223  /*   lhs is A                                                         */
  3224  /*   rhs is B                                                         */
  3225  /*   set is the context (used for result length and error report)     */
  3226  /*                                                                    */
  3227  /* C must have space for set->digits digits.                          */
  3228  /*                                                                    */
  3229  /* Logical function restrictions apply (see above); a NaN is          */
  3230  /* returned with Invalid_operation if a restriction is violated.      */
  3231  /* ------------------------------------------------------------------ */
  3232  decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
  3233                           const decNumber *rhs, decContext *set) {
  3234    const Unit *ua, *ub;                  // -> operands
  3235    const Unit *msua, *msub;              // -> operand msus
  3236    Unit  *uc, *msuc;                     // -> result and its msu
  3237    Int   msudigs;                        // digits in res msu
  3238    #if DECCHECK
  3239    if (decCheckOperands(res, lhs, rhs, set)) return res;
  3240    #endif
  3241  
  3242    if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
  3243     || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
  3244      decStatus(res, DEC_Invalid_operation, set);
  3245      return res;
  3246      }
  3247    // operands are valid
  3248    ua=lhs->lsu;                          // bottom-up
  3249    ub=rhs->lsu;                          // ..
  3250    uc=res->lsu;                          // ..
  3251    msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
  3252    msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
  3253    msuc=uc+D2U(set->digits)-1;           // -> msu of result
  3254    msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
  3255    for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
  3256      Unit a, b;                          // extract units
  3257      if (ua>msua) a=0;
  3258       else a=*ua;
  3259      if (ub>msub) b=0;
  3260       else b=*ub;
  3261      *uc=0;                              // can now write back
  3262      if (a|b) {                          // maybe 1 bits to examine
  3263        Int i, j;
  3264        // This loop could be unrolled and/or use BIN2BCD tables
  3265        for (i=0; i<DECDPUN; i++) {
  3266          if ((a^b)&1) *uc=*uc+(Unit)powers[i];     // effect XOR
  3267          j=a%10;
  3268          a=a/10;
  3269          j|=b%10;
  3270          b=b/10;
  3271          if (j>1) {
  3272            decStatus(res, DEC_Invalid_operation, set);
  3273            return res;
  3274            }
  3275          if (uc==msuc && i==msudigs-1) break;      // just did final digit
  3276          } // each digit
  3277        } // non-zero
  3278      } // each unit
  3279    // [here uc-1 is the msu of the result]
  3280    res->digits=decGetDigits(res->lsu, uc-res->lsu);
  3281    res->exponent=0;                      // integer
  3282    res->bits=0;                          // sign=0
  3283    return res;  // [no status to set]
  3284    } // decNumberXor
  3285  
  3286  
  3287  /* ================================================================== */
  3288  /* Utility routines                                                   */
  3289  /* ================================================================== */
  3290  
  3291  /* ------------------------------------------------------------------ */
  3292  /* decNumberClass -- return the decClass of a decNumber               */
  3293  /*   dn -- the decNumber to test                                      */
  3294  /*   set -- the context to use for Emin                               */
  3295  /*   returns the decClass enum                                        */
  3296  /* ------------------------------------------------------------------ */
  3297  enum decClass decNumberClass(const decNumber *dn, decContext *set) {
  3298    if (decNumberIsSpecial(dn)) {
  3299      if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
  3300      if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
  3301      // must be an infinity
  3302      if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
  3303      return DEC_CLASS_POS_INF;
  3304      }
  3305    // is finite
  3306    if (decNumberIsNormal(dn, set)) { // most common
  3307      if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
  3308      return DEC_CLASS_POS_NORMAL;
  3309      }
  3310    // is subnormal or zero
  3311    if (decNumberIsZero(dn)) {    // most common
  3312      if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
  3313      return DEC_CLASS_POS_ZERO;
  3314      }
  3315    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
  3316    return DEC_CLASS_POS_SUBNORMAL;
  3317    } // decNumberClass
  3318  
  3319  /* ------------------------------------------------------------------ */
  3320  /* decNumberClassToString -- convert decClass to a string             */
  3321  /*                                                                    */
  3322  /*  eclass is a valid decClass                                        */
  3323  /*  returns a constant string describing the class (max 13+1 chars)   */
  3324  /* ------------------------------------------------------------------ */
  3325  const char *decNumberClassToString(enum decClass eclass) {
  3326    if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
  3327    if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
  3328    if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
  3329    if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
  3330    if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
  3331    if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
  3332    if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
  3333    if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
  3334    if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
  3335    if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
  3336    return DEC_ClassString_UN;           // Unknown
  3337    } // decNumberClassToString
  3338  
  3339  /* ------------------------------------------------------------------ */
  3340  /* decNumberCopy -- copy a number                                     */
  3341  /*                                                                    */
  3342  /*   dest is the target decNumber                                     */
  3343  /*   src  is the source decNumber                                     */
  3344  /*   returns dest                                                     */
  3345  /*                                                                    */
  3346  /* (dest==src is allowed and is a no-op)                              */
  3347  /* All fields are updated as required.  This is a utility operation,  */
  3348  /* so special values are unchanged and no error is possible.          */
  3349  /* ------------------------------------------------------------------ */
  3350  decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
  3351  
  3352    #if DECCHECK
  3353    if (src==NULL) return decNumberZero(dest);
  3354    #endif
  3355  
  3356    if (dest==src) return dest;                // no copy required
  3357  
  3358    // Use explicit assignments here as structure assignment could copy
  3359    // more than just the lsu (for small DECDPUN).  This would not affect
  3360    // the value of the results, but could disturb test harness spill
  3361    // checking.
  3362    dest->bits=src->bits;
  3363    dest->exponent=src->exponent;
  3364    dest->digits=src->digits;
  3365    dest->lsu[0]=src->lsu[0];
  3366    if (src->digits>DECDPUN) {                 // more Units to come
  3367      const Unit *smsup, *s;                   // work
  3368      Unit  *d;                                // ..
  3369      // memcpy for the remaining Units would be safe as they cannot
  3370      // overlap.  However, this explicit loop is faster in short cases.
  3371      d=dest->lsu+1;                           // -> first destination
  3372      smsup=src->lsu+D2U(src->digits);         // -> source msu+1
  3373      for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
  3374      }
  3375    return dest;
  3376    } // decNumberCopy
  3377  
  3378  /* ------------------------------------------------------------------ */
  3379  /* decNumberCopyAbs -- quiet absolute value operator                  */
  3380  /*                                                                    */
  3381  /*   This sets C = abs(A)                                             */
  3382  /*                                                                    */
  3383  /*   res is C, the result.  C may be A                                */
  3384  /*   rhs is A                                                         */
  3385  /*                                                                    */
  3386  /* C must have space for set->digits digits.                          */
  3387  /* No exception or error can occur; this is a quiet bitwise operation.*/
  3388  /* See also decNumberAbs for a checking version of this.              */
  3389  /* ------------------------------------------------------------------ */
  3390  decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
  3391    #if DECCHECK
  3392    if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3393    #endif
  3394    decNumberCopy(res, rhs);
  3395    res->bits&=~DECNEG;                   // turn off sign
  3396    return res;
  3397    } // decNumberCopyAbs
  3398  
  3399  /* ------------------------------------------------------------------ */
  3400  /* decNumberCopyNegate -- quiet negate value operator                 */
  3401  /*                                                                    */
  3402  /*   This sets C = negate(A)                                          */
  3403  /*                                                                    */
  3404  /*   res is C, the result.  C may be A                                */
  3405  /*   rhs is A                                                         */
  3406  /*                                                                    */
  3407  /* C must have space for set->digits digits.                          */
  3408  /* No exception or error can occur; this is a quiet bitwise operation.*/
  3409  /* See also decNumberMinus for a checking version of this.            */
  3410  /* ------------------------------------------------------------------ */
  3411  decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
  3412    #if DECCHECK
  3413    if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3414    #endif
  3415    decNumberCopy(res, rhs);
  3416    res->bits^=DECNEG;                    // invert the sign
  3417    return res;
  3418    } // decNumberCopyNegate
  3419  
  3420  /* ------------------------------------------------------------------ */
  3421  /* decNumberCopySign -- quiet copy and set sign operator              */
  3422  /*                                                                    */
  3423  /*   This sets C = A with the sign of B                               */
  3424  /*                                                                    */
  3425  /*   res is C, the result.  C may be A                                */
  3426  /*   lhs is A                                                         */
  3427  /*   rhs is B                                                         */
  3428  /*                                                                    */
  3429  /* C must have space for set->digits digits.                          */
  3430  /* No exception or error can occur; this is a quiet bitwise operation.*/
  3431  /* ------------------------------------------------------------------ */
  3432  decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
  3433                                const decNumber *rhs) {
  3434    uByte sign;                           // rhs sign
  3435    #if DECCHECK
  3436    if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
  3437    #endif
  3438    sign=rhs->bits & DECNEG;              // save sign bit
  3439    decNumberCopy(res, lhs);
  3440    res->bits&=~DECNEG;                   // clear the sign
  3441    res->bits|=sign;                      // set from rhs
  3442    return res;
  3443    } // decNumberCopySign
  3444  
  3445  /* ------------------------------------------------------------------ */
  3446  /* decNumberGetBCD -- get the coefficient in BCD8                     */
  3447  /*   dn is the source decNumber                                       */
  3448  /*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
  3449  /*     most-significant at offset 0                                   */
  3450  /*   returns bcd                                                      */
  3451  /*                                                                    */
  3452  /* bcd must have at least dn->digits bytes.  No error is possible; if */
  3453  /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
  3454  /* ------------------------------------------------------------------ */
  3455  uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
  3456    uByte *ub=bcd+dn->digits-1;      // -> lsd
  3457    const Unit *up=dn->lsu;          // Unit pointer, -> lsu
  3458  
  3459    #if DECDPUN==1                   // trivial simple copy
  3460      for (; ub>=bcd; ub--, up++) *ub=*up;
  3461    #else                            // chopping needed
  3462      uInt u=*up;                    // work
  3463      uInt cut=DECDPUN;              // downcounter through unit
  3464      for (; ub>=bcd; ub--) {
  3465        *ub=(uByte)(u%10);           // [*6554 trick inhibits, here]
  3466        u=u/10;
  3467        cut--;
  3468        if (cut>0) continue;         // more in this unit
  3469        up++;
  3470        u=*up;
  3471        cut=DECDPUN;
  3472        }
  3473    #endif
  3474    return bcd;
  3475    } // decNumberGetBCD
  3476  
  3477  /* ------------------------------------------------------------------ */
  3478  /* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
  3479  /*   dn is the target decNumber                                       */
  3480  /*   bcd is the uInt array that will source n BCD bytes, most-        */
  3481  /*     significant at offset 0                                        */
  3482  /*   n is the number of digits in the source BCD array (bcd)          */
  3483  /*   returns dn                                                       */
  3484  /*                                                                    */
  3485  /* dn must have space for at least n digits.  No error is possible;   */
  3486  /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
  3487  /* and bcd[0] zero.                                                   */
  3488  /* ------------------------------------------------------------------ */
  3489  decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
  3490    Unit *up=dn->lsu+D2U(dn->digits)-1;   // -> msu [target pointer]
  3491    const uByte *ub=bcd;                  // -> source msd
  3492  
  3493    #if DECDPUN==1                        // trivial simple copy
  3494      for (; ub<bcd+n; ub++, up--) *up=*ub;
  3495    #else                                 // some assembly needed
  3496      // calculate how many digits in msu, and hence first cut
  3497      Int cut=MSUDIGITS(n);               // [faster than remainder]
  3498      for (;up>=dn->lsu; up--) {          // each Unit from msu
  3499        *up=0;                            // will take <=DECDPUN digits
  3500        for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
  3501        cut=DECDPUN;                      // next Unit has all digits
  3502        }
  3503    #endif
  3504    dn->digits=n;                         // set digit count
  3505    return dn;
  3506    } // decNumberSetBCD
  3507  
  3508  /* ------------------------------------------------------------------ */
  3509  /* decNumberIsNormal -- test normality of a decNumber                 */
  3510  /*   dn is the decNumber to test                                      */
  3511  /*   set is the context to use for Emin                               */
  3512  /*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
  3513  /* ------------------------------------------------------------------ */
  3514  Int decNumberIsNormal(const decNumber *dn, decContext *set) {
  3515    Int ae;                               // adjusted exponent
  3516    #if DECCHECK
  3517    if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3518    #endif
  3519  
  3520    if (decNumberIsSpecial(dn)) return 0; // not finite
  3521    if (decNumberIsZero(dn)) return 0;    // not non-zero
  3522  
  3523    ae=dn->exponent+dn->digits-1;         // adjusted exponent
  3524    if (ae<set->emin) return 0;           // is subnormal
  3525    return 1;
  3526    } // decNumberIsNormal
  3527  
  3528  /* ------------------------------------------------------------------ */
  3529  /* decNumberIsSubnormal -- test subnormality of a decNumber           */
  3530  /*   dn is the decNumber to test                                      */
  3531  /*   set is the context to use for Emin                               */
  3532  /*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
  3533  /* ------------------------------------------------------------------ */
  3534  Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
  3535    Int ae;                               // adjusted exponent
  3536    #if DECCHECK
  3537    if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
  3538    #endif
  3539  
  3540    if (decNumberIsSpecial(dn)) return 0; // not finite
  3541    if (decNumberIsZero(dn)) return 0;    // not non-zero
  3542  
  3543    ae=dn->exponent+dn->digits-1;         // adjusted exponent
  3544    if (ae<set->emin) return 1;           // is subnormal
  3545    return 0;
  3546    } // decNumberIsSubnormal
  3547  
  3548  /* ------------------------------------------------------------------ */
  3549  /* decNumberTrim -- remove insignificant zeros                        */
  3550  /*                                                                    */
  3551  /*   dn is the number to trim                                         */
  3552  /*   returns dn                                                       */
  3553  /*                                                                    */
  3554  /* All fields are updated as required.  This is a utility operation,  */
  3555  /* so special values are unchanged and no error is possible.  The     */
  3556  /* zeros are removed unconditionally.                                 */
  3557  /* ------------------------------------------------------------------ */
  3558  decNumber * decNumberTrim(decNumber *dn) {
  3559    Int  dropped;                    // work
  3560    decContext set;                  // ..
  3561    #if DECCHECK
  3562    if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
  3563    #endif
  3564    decContextDefault(&set, DEC_INIT_BASE);    // clamp=0
  3565    return decTrim(dn, &set, 0, 1, &dropped);
  3566    } // decNumberTrim
  3567  
  3568  /* ------------------------------------------------------------------ */
  3569  /* decNumberVersion -- return the name and version of this module     */
  3570  /*                                                                    */
  3571  /* No error is possible.                                              */
  3572  /* ------------------------------------------------------------------ */
  3573  const char * decNumberVersion(void) {
  3574    return DECVERSION;
  3575    } // decNumberVersion
  3576  
  3577  /* ------------------------------------------------------------------ */
  3578  /* decNumberZero -- set a number to 0                                 */
  3579  /*                                                                    */
  3580  /*   dn is the number to set, with space for one digit                */
  3581  /*   returns dn                                                       */
  3582  /*                                                                    */
  3583  /* No error is possible.                                              */
  3584  /* ------------------------------------------------------------------ */
  3585  // Memset is not used as it is much slower in some environments.
  3586  decNumber * decNumberZero(decNumber *dn) {
  3587  
  3588    #if DECCHECK
  3589    if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  3590    #endif
  3591  
  3592    dn->bits=0;
  3593    dn->exponent=0;
  3594    dn->digits=1;
  3595    dn->lsu[0]=0;
  3596    return dn;
  3597    } // decNumberZero
  3598  
  3599  /* ================================================================== */
  3600  /* Local routines                                                     */
  3601  /* ================================================================== */
  3602  
  3603  /* ------------------------------------------------------------------ */
  3604  /* decToString -- lay out a number into a string                      */
  3605  /*                                                                    */
  3606  /*   dn     is the number to lay out                                  */
  3607  /*   string is where to lay out the number                            */
  3608  /*   eng    is 1 if Engineering, 0 if Scientific                      */
  3609  /*                                                                    */
  3610  /* string must be at least dn->digits+14 characters long              */
  3611  /* No error is possible.                                              */
  3612  /*                                                                    */
  3613  /* Note that this routine can generate a -0 or 0.000.  These are      */
  3614  /* never generated in subset to-number or arithmetic, but can occur   */
  3615  /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
  3616  /* ------------------------------------------------------------------ */
  3617  // If DECCHECK is enabled the string "?" is returned if a number is
  3618  // invalid.
  3619  static void decToString(const decNumber *dn, char *string, Flag eng) {
  3620    Int exp=dn->exponent;       // local copy
  3621    Int e;                      // E-part value
  3622    Int pre;                    // digits before the '.'
  3623    Int cut;                    // for counting digits in a Unit
  3624    char *c=string;             // work [output pointer]
  3625    const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]
  3626    uInt u, pow;                // work
  3627  
  3628    #if DECCHECK
  3629    if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
  3630      strcpy(string, "?");
  3631      return;}
  3632    #endif
  3633  
  3634    if (decNumberIsNegative(dn)) {   // Negatives get a minus
  3635      *c='-';
  3636      c++;
  3637      }
  3638    if (dn->bits&DECSPECIAL) {       // Is a special value
  3639      if (decNumberIsInfinite(dn)) {
  3640        strcpy(c,   "Inf");
  3641        strcpy(c+3, "inity");
  3642        return;}
  3643      // a NaN
  3644      if (dn->bits&DECSNAN) {        // signalling NaN
  3645        *c='s';
  3646        c++;
  3647        }
  3648      strcpy(c, "NaN");
  3649      c+=3;                          // step past
  3650      // if not a clean non-zero coefficient, that's all there is in a
  3651      // NaN string
  3652      if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
  3653      // [drop through to add integer]
  3654      }
  3655  
  3656    // calculate how many digits in msu, and hence first cut
  3657    cut=MSUDIGITS(dn->digits);       // [faster than remainder]
  3658    cut--;                           // power of ten for digit
  3659  
  3660    if (exp==0) {                    // simple integer [common fastpath]
  3661      for (;up>=dn->lsu; up--) {     // each Unit from msu
  3662        u=*up;                       // contains DECDPUN digits to lay out
  3663        for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
  3664        cut=DECDPUN-1;               // next Unit has all digits
  3665        }
  3666      *c='\0';                       // terminate the string
  3667      return;}
  3668  
  3669    /* non-0 exponent -- assume plain form */
  3670    pre=dn->digits+exp;              // digits before '.'
  3671    e=0;                             // no E
  3672    if ((exp>0) || (pre<-5)) {       // need exponential form
  3673      e=exp+dn->digits-1;            // calculate E value
  3674      pre=1;                         // assume one digit before '.'
  3675      if (eng && (e!=0)) {           // engineering: may need to adjust
  3676        Int adj;                     // adjustment
  3677        // The C remainder operator is undefined for negative numbers, so
  3678        // a positive remainder calculation must be used here
  3679        if (e<0) {
  3680          adj=(-e)%3;
  3681          if (adj!=0) adj=3-adj;
  3682          }
  3683         else { // e>0
  3684          adj=e%3;
  3685          }
  3686        e=e-adj;
  3687        // if dealing with zero still produce an exponent which is a
  3688        // multiple of three, as expected, but there will only be the
  3689        // one zero before the E, still.  Otherwise note the padding.
  3690        if (!ISZERO(dn)) pre+=adj;
  3691         else {  // is zero
  3692          if (adj!=0) {              // 0.00Esnn needed
  3693            e=e+3;
  3694            pre=-(2-adj);
  3695            }
  3696          } // zero
  3697        } // eng
  3698      } // need exponent
  3699  
  3700    /* lay out the digits of the coefficient, adding 0s and . as needed */
  3701    u=*up;
  3702    if (pre>0) {                     // xxx.xxx or xx00 (engineering) form
  3703      Int n=pre;
  3704      for (; pre>0; pre--, c++, cut--) {
  3705        if (cut<0) {                 // need new Unit
  3706          if (up==dn->lsu) break;    // out of input digits (pre>digits)
  3707          up--;
  3708          cut=DECDPUN-1;
  3709          u=*up;
  3710          }
  3711        TODIGIT(u, cut, c, pow);
  3712        }
  3713      if (n<dn->digits) {            // more to come, after '.'
  3714        *c='.'; c++;
  3715        for (;; c++, cut--) {
  3716          if (cut<0) {               // need new Unit
  3717            if (up==dn->lsu) break;  // out of input digits
  3718            up--;
  3719            cut=DECDPUN-1;
  3720            u=*up;
  3721            }
  3722          TODIGIT(u, cut, c, pow);
  3723          }
  3724        }
  3725       else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed
  3726      }
  3727     else {                          // 0.xxx or 0.000xxx form
  3728      *c='0'; c++;
  3729      *c='.'; c++;
  3730      for (; pre<0; pre++, c++) *c='0';   // add any 0's after '.'
  3731      for (; ; c++, cut--) {
  3732        if (cut<0) {                 // need new Unit
  3733          if (up==dn->lsu) break;    // out of input digits
  3734          up--;
  3735          cut=DECDPUN-1;
  3736          u=*up;
  3737          }
  3738        TODIGIT(u, cut, c, pow);
  3739        }
  3740      }
  3741  
  3742    /* Finally add the E-part, if needed.  It will never be 0, has a
  3743       base maximum and minimum of +999999999 through -999999999, but
  3744       could range down to -1999999998 for anormal numbers */
  3745    if (e!=0) {
  3746      Flag had=0;               // 1=had non-zero
  3747      *c='E'; c++;
  3748      *c='+'; c++;              // assume positive
  3749      u=e;                      // ..
  3750      if (e<0) {
  3751        *(c-1)='-';             // oops, need -
  3752        u=-e;                   // uInt, please
  3753        }
  3754      // lay out the exponent [_itoa or equivalent is not ANSI C]
  3755      for (cut=9; cut>=0; cut--) {
  3756        TODIGIT(u, cut, c, pow);
  3757        if (*c=='0' && !had) continue;    // skip leading zeros
  3758        had=1;                            // had non-0
  3759        c++;                              // step for next
  3760        } // cut
  3761      }
  3762    *c='\0';          // terminate the string (all paths)
  3763    return;
  3764    } // decToString
  3765  
  3766  /* ------------------------------------------------------------------ */
  3767  /* decAddOp -- add/subtract operation                                 */
  3768  /*                                                                    */
  3769  /*   This computes C = A + B                                          */
  3770  /*                                                                    */
  3771  /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
  3772  /*   lhs is A                                                         */
  3773  /*   rhs is B                                                         */
  3774  /*   set is the context                                               */
  3775  /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
  3776  /*   status accumulates status for the caller                         */
  3777  /*                                                                    */
  3778  /* C must have space for set->digits digits.                          */
  3779  /* Inexact in status must be 0 for correct Exact zero sign in result  */
  3780  /* ------------------------------------------------------------------ */
  3781  /* If possible, the coefficient is calculated directly into C.        */
  3782  /* However, if:                                                       */
  3783  /*   -- a digits+1 calculation is needed because the numbers are      */
  3784  /*      unaligned and span more than set->digits digits               */
  3785  /*   -- a carry to digits+1 digits looks possible                     */
  3786  /*   -- C is the same as A or B, and the result would destructively   */
  3787  /*      overlap the A or B coefficient                                */
  3788  /* then the result must be calculated into a temporary buffer.  In    */
  3789  /* this case a local (stack) buffer is used if possible, and only if  */
  3790  /* too long for that does malloc become the final resort.             */
  3791  /*                                                                    */
  3792  /* Misalignment is handled as follows:                                */
  3793  /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
  3794  /*   BPad: Apply the padding by a combination of shifting (whole      */
  3795  /*         units) and multiplication (part units).                    */
  3796  /*                                                                    */
  3797  /* Addition, especially x=x+1, is speed-critical.                     */
  3798  /* The static buffer is larger than might be expected to allow for    */
  3799  /* calls from higher-level funtions (notable exp).                    */
  3800  /* ------------------------------------------------------------------ */
  3801  static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
  3802                              const decNumber *rhs, decContext *set,
  3803                              uByte negate, uInt *status) {
  3804    #if DECSUBSET
  3805    decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
  3806    decNumber *allocrhs=NULL;        // .., rhs
  3807    #endif
  3808    Int   rhsshift;                  // working shift (in Units)
  3809    Int   maxdigits;                 // longest logical length
  3810    Int   mult;                      // multiplier
  3811    Int   residue;                   // rounding accumulator
  3812    uByte bits;                      // result bits
  3813    Flag  diffsign;                  // non-0 if arguments have different sign
  3814    Unit  *acc;                      // accumulator for result
  3815    Unit  accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many
  3816                                     // allocations when called from
  3817                                     // other operations, notable exp]
  3818    Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
  3819    Int   reqdigits=set->digits;     // local copy; requested DIGITS
  3820    Int   padding;                   // work
  3821  
  3822    #if DECCHECK
  3823    if (decCheckOperands(res, lhs, rhs, set)) return res;
  3824    #endif
  3825  
  3826    do {                             // protect allocated storage
  3827      #if DECSUBSET
  3828      if (!set->extended) {
  3829        // reduce operands and set lostDigits status, as needed
  3830        if (lhs->digits>reqdigits) {
  3831          alloclhs=decRoundOperand(lhs, set, status);
  3832          if (alloclhs==NULL) break;
  3833          lhs=alloclhs;
  3834          }
  3835        if (rhs->digits>reqdigits) {
  3836          allocrhs=decRoundOperand(rhs, set, status);
  3837          if (allocrhs==NULL) break;
  3838          rhs=allocrhs;
  3839          }
  3840        }
  3841      #endif
  3842      // [following code does not require input rounding]
  3843  
  3844      // note whether signs differ [used all paths]
  3845      diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
  3846  
  3847      // handle infinities and NaNs
  3848      if (SPECIALARGS) {                  // a special bit set
  3849        if (SPECIALARGS & (DECSNAN | DECNAN))  // a NaN
  3850          decNaNs(res, lhs, rhs, set, status);
  3851         else { // one or two infinities
  3852          if (decNumberIsInfinite(lhs)) { // LHS is infinity
  3853            // two infinities with different signs is invalid
  3854            if (decNumberIsInfinite(rhs) && diffsign) {
  3855              *status|=DEC_Invalid_operation;
  3856              break;
  3857              }
  3858            bits=lhs->bits & DECNEG;      // get sign from LHS
  3859            }
  3860           else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity
  3861          bits|=DECINF;
  3862          decNumberZero(res);
  3863          res->bits=bits;                 // set +/- infinity
  3864          } // an infinity
  3865        break;
  3866        }
  3867  
  3868      // Quick exit for add 0s; return the non-0, modified as need be
  3869      if (ISZERO(lhs)) {
  3870        Int adjust;                       // work
  3871        Int lexp=lhs->exponent;           // save in case LHS==RES
  3872        bits=lhs->bits;                   // ..
  3873        residue=0;                        // clear accumulator
  3874        decCopyFit(res, rhs, set, &residue, status); // copy (as needed)
  3875        res->bits^=negate;                // flip if rhs was negated
  3876        #if DECSUBSET
  3877        if (set->extended) {              // exponents on zeros count
  3878        #endif
  3879          // exponent will be the lower of the two
  3880          adjust=lexp-res->exponent;      // adjustment needed [if -ve]
  3881          if (ISZERO(res)) {              // both 0: special IEEE 754 rules
  3882            if (adjust<0) res->exponent=lexp;  // set exponent
  3883            // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0
  3884            if (diffsign) {
  3885              if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
  3886               else res->bits=DECNEG;     // preserve 0 sign
  3887              }
  3888            }
  3889           else { // non-0 res
  3890            if (adjust<0) {     // 0-padding needed
  3891              if ((res->digits-adjust)>set->digits) {
  3892                adjust=res->digits-set->digits;     // to fit exactly
  3893                *status|=DEC_Rounded;               // [but exact]
  3894                }
  3895              res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3896              res->exponent+=adjust;                // set the exponent.
  3897              }
  3898            } // non-0 res
  3899        #if DECSUBSET
  3900          } // extended
  3901        #endif
  3902        decFinish(res, set, &residue, status);      // clean and finalize
  3903        break;}
  3904  
  3905      if (ISZERO(rhs)) {                  // [lhs is non-zero]
  3906        Int adjust;                       // work
  3907        Int rexp=rhs->exponent;           // save in case RHS==RES
  3908        bits=rhs->bits;                   // be clean
  3909        residue=0;                        // clear accumulator
  3910        decCopyFit(res, lhs, set, &residue, status); // copy (as needed)
  3911        #if DECSUBSET
  3912        if (set->extended) {              // exponents on zeros count
  3913        #endif
  3914          // exponent will be the lower of the two
  3915          // [0-0 case handled above]
  3916          adjust=rexp-res->exponent;      // adjustment needed [if -ve]
  3917          if (adjust<0) {     // 0-padding needed
  3918            if ((res->digits-adjust)>set->digits) {
  3919              adjust=res->digits-set->digits;     // to fit exactly
  3920              *status|=DEC_Rounded;               // [but exact]
  3921              }
  3922            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  3923            res->exponent+=adjust;                // set the exponent.
  3924            }
  3925        #if DECSUBSET
  3926          } // extended
  3927        #endif
  3928        decFinish(res, set, &residue, status);      // clean and finalize
  3929        break;}
  3930  
  3931      // [NB: both fastpath and mainpath code below assume these cases
  3932      // (notably 0-0) have already been handled]
  3933  
  3934      // calculate the padding needed to align the operands
  3935      padding=rhs->exponent-lhs->exponent;
  3936  
  3937      // Fastpath cases where the numbers are aligned and normal, the RHS
  3938      // is all in one unit, no operand rounding is needed, and no carry,
  3939      // lengthening, or borrow is needed
  3940      if (padding==0
  3941          && rhs->digits<=DECDPUN
  3942          && rhs->exponent>=set->emin     // [some normals drop through]
  3943          && rhs->exponent<=set->emax-set->digits+1 // [could clamp]
  3944          && rhs->digits<=reqdigits
  3945          && lhs->digits<=reqdigits) {
  3946        Int partial=*lhs->lsu;
  3947        if (!diffsign) {                  // adding
  3948          partial+=*rhs->lsu;
  3949          if ((partial<=DECDPUNMAX)       // result fits in unit
  3950           && (lhs->digits>=DECDPUN ||    // .. and no digits-count change
  3951               partial<(Int)powers[lhs->digits])) { // ..
  3952            if (res!=lhs) decNumberCopy(res, lhs);  // not in place
  3953            *res->lsu=(Unit)partial;      // [copy could have overwritten RHS]
  3954            break;
  3955            }
  3956          // else drop out for careful add
  3957          }
  3958         else {                           // signs differ
  3959          partial-=*rhs->lsu;
  3960          if (partial>0) { // no borrow needed, and non-0 result
  3961            if (res!=lhs) decNumberCopy(res, lhs);  // not in place
  3962            *res->lsu=(Unit)partial;
  3963            // this could have reduced digits [but result>0]
  3964            res->digits=decGetDigits(res->lsu, D2U(res->digits));
  3965            break;
  3966            }
  3967          // else drop out for careful subtract
  3968          }
  3969        }
  3970  
  3971      // Now align (pad) the lhs or rhs so they can be added or
  3972      // subtracted, as necessary.  If one number is much larger than
  3973      // the other (that is, if in plain form there is a least one
  3974      // digit between the lowest digit of one and the highest of the
  3975      // other) padding with up to DIGITS-1 trailing zeros may be
  3976      // needed; then apply rounding (as exotic rounding modes may be
  3977      // affected by the residue).
  3978      rhsshift=0;               // rhs shift to left (padding) in Units
  3979      bits=lhs->bits;           // assume sign is that of LHS
  3980      mult=1;                   // likely multiplier
  3981  
  3982      // [if padding==0 the operands are aligned; no padding is needed]
  3983      if (padding!=0) {
  3984        // some padding needed; always pad the RHS, as any required
  3985        // padding can then be effected by a simple combination of
  3986        // shifts and a multiply
  3987        Flag swapped=0;
  3988        if (padding<0) {                  // LHS needs the padding
  3989          const decNumber *t;
  3990          padding=-padding;               // will be +ve
  3991          bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS
  3992          t=lhs; lhs=rhs; rhs=t;
  3993          swapped=1;
  3994          }
  3995  
  3996        // If, after pad, rhs would be longer than lhs by digits+1 or
  3997        // more then lhs cannot affect the answer, except as a residue,
  3998        // so only need to pad up to a length of DIGITS+1.
  3999        if (rhs->digits+padding > lhs->digits+reqdigits+1) {
  4000          // The RHS is sufficient
  4001          // for residue use the relative sign indication...
  4002          Int shift=reqdigits-rhs->digits;     // left shift needed
  4003          residue=1;                           // residue for rounding
  4004          if (diffsign) residue=-residue;      // signs differ
  4005          // copy, shortening if necessary
  4006          decCopyFit(res, rhs, set, &residue, status);
  4007          // if it was already shorter, then need to pad with zeros
  4008          if (shift>0) {
  4009            res->digits=decShiftToMost(res->lsu, res->digits, shift);
  4010            res->exponent-=shift;              // adjust the exponent.
  4011            }
  4012          // flip the result sign if unswapped and rhs was negated
  4013          if (!swapped) res->bits^=negate;
  4014          decFinish(res, set, &residue, status);    // done
  4015          break;}
  4016  
  4017        // LHS digits may affect result
  4018        rhsshift=D2U(padding+1)-1;        // this much by Unit shift ..
  4019        mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication
  4020        } // padding needed
  4021  
  4022      if (diffsign) mult=-mult;           // signs differ
  4023  
  4024      // determine the longer operand
  4025      maxdigits=rhs->digits+padding;      // virtual length of RHS
  4026      if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  4027  
  4028      // Decide on the result buffer to use; if possible place directly
  4029      // into result.
  4030      acc=res->lsu;                       // assume add direct to result
  4031      // If destructive overlap, or the number is too long, or a carry or
  4032      // borrow to DIGITS+1 might be possible, a buffer must be used.
  4033      // [Might be worth more sophisticated tests when maxdigits==reqdigits]
  4034      if ((maxdigits>=reqdigits)          // is, or could be, too large
  4035       || (res==rhs && rhsshift>0)) {     // destructive overlap
  4036        // buffer needed, choose it; units for maxdigits digits will be
  4037        // needed, +1 Unit for carry or borrow
  4038        Int need=D2U(maxdigits)+1;
  4039        acc=accbuff;                      // assume use local buffer
  4040        if (need*sizeof(Unit)>sizeof(accbuff)) {
  4041          // printf("malloc add %ld %ld\n", need, sizeof(accbuff));
  4042          allocacc=(Unit *)malloc(need*sizeof(Unit));
  4043          if (allocacc==NULL) {           // hopeless -- abandon
  4044            *status|=DEC_Insufficient_storage;
  4045            break;}
  4046          acc=allocacc;
  4047          }
  4048        }
  4049  
  4050      res->bits=(uByte)(bits&DECNEG);     // it's now safe to overwrite..
  4051      res->exponent=lhs->exponent;        // .. operands (even if aliased)
  4052  
  4053      #if DECTRACE
  4054        decDumpAr('A', lhs->lsu, D2U(lhs->digits));
  4055        decDumpAr('B', rhs->lsu, D2U(rhs->digits));
  4056        printf("  :h: %ld %ld\n", rhsshift, mult);
  4057      #endif
  4058  
  4059      // add [A+B*m] or subtract [A+B*(-m)]
  4060      res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
  4061                                rhs->lsu, D2U(rhs->digits),
  4062                                rhsshift, acc, mult)
  4063                 *DECDPUN;           // [units -> digits]
  4064      if (res->digits<0) {           // borrowed...
  4065        res->digits=-res->digits;
  4066        res->bits^=DECNEG;           // flip the sign
  4067        }
  4068      #if DECTRACE
  4069        decDumpAr('+', acc, D2U(res->digits));
  4070      #endif
  4071  
  4072      // If a buffer was used the result must be copied back, possibly
  4073      // shortening.  (If no buffer was used then the result must have
  4074      // fit, so can't need rounding and residue must be 0.)
  4075      residue=0;                     // clear accumulator
  4076      if (acc!=res->lsu) {
  4077        #if DECSUBSET
  4078        if (set->extended) {         // round from first significant digit
  4079        #endif
  4080          // remove leading zeros that were added due to rounding up to
  4081          // integral Units -- before the test for rounding.
  4082          if (res->digits>reqdigits)
  4083            res->digits=decGetDigits(acc, D2U(res->digits));
  4084          decSetCoeff(res, set, acc, res->digits, &residue, status);
  4085        #if DECSUBSET
  4086          }
  4087         else { // subset arithmetic rounds from original significant digit
  4088          // May have an underestimate.  This only occurs when both
  4089          // numbers fit in DECDPUN digits and are padding with a
  4090          // negative multiple (-10, -100...) and the top digit(s) become
  4091          // 0.  (This only matters when using X3.274 rules where the
  4092          // leading zero could be included in the rounding.)
  4093          if (res->digits<maxdigits) {
  4094            *(acc+D2U(res->digits))=0; // ensure leading 0 is there
  4095            res->digits=maxdigits;
  4096            }
  4097           else {
  4098            // remove leading zeros that added due to rounding up to
  4099            // integral Units (but only those in excess of the original
  4100            // maxdigits length, unless extended) before test for rounding.
  4101            if (res->digits>reqdigits) {
  4102              res->digits=decGetDigits(acc, D2U(res->digits));
  4103              if (res->digits<maxdigits) res->digits=maxdigits;
  4104              }
  4105            }
  4106          decSetCoeff(res, set, acc, res->digits, &residue, status);
  4107          // Now apply rounding if needed before removing leading zeros.
  4108          // This is safe because subnormals are not a possibility
  4109          if (residue!=0) {
  4110            decApplyRound(res, set, residue, status);
  4111            residue=0;                 // did what needed to be done
  4112            }
  4113          } // subset
  4114        #endif
  4115        } // used buffer
  4116  
  4117      // strip leading zeros [these were left on in case of subset subtract]
  4118      res->digits=decGetDigits(res->lsu, D2U(res->digits));
  4119  
  4120      // apply checks and rounding
  4121      decFinish(res, set, &residue, status);
  4122  
  4123      // "When the sum of two operands with opposite signs is exactly
  4124      // zero, the sign of that sum shall be '+' in all rounding modes
  4125      // except round toward -Infinity, in which mode that sign shall be
  4126      // '-'."  [Subset zeros also never have '-', set by decFinish.]
  4127      if (ISZERO(res) && diffsign
  4128       #if DECSUBSET
  4129       && set->extended
  4130       #endif
  4131       && (*status&DEC_Inexact)==0) {
  4132        if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   // sign -
  4133                                    else res->bits&=~DECNEG;  // sign +
  4134        }
  4135      } while(0);                              // end protected
  4136  
  4137    if (allocacc!=NULL) free(allocacc);        // drop any storage used
  4138    #if DECSUBSET
  4139    if (allocrhs!=NULL) free(allocrhs);        // ..
  4140    if (alloclhs!=NULL) free(alloclhs);        // ..
  4141    #endif
  4142    return res;
  4143    } // decAddOp
  4144  
  4145  /* ------------------------------------------------------------------ */
  4146  /* decDivideOp -- division operation                                  */
  4147  /*                                                                    */
  4148  /*  This routine performs the calculations for all four division      */
  4149  /*  operators (divide, divideInteger, remainder, remainderNear).      */
  4150  /*                                                                    */
  4151  /*  C=A op B                                                          */
  4152  /*                                                                    */
  4153  /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
  4154  /*   lhs is A                                                         */
  4155  /*   rhs is B                                                         */
  4156  /*   set is the context                                               */
  4157  /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
  4158  /*   status is the usual accumulator                                  */
  4159  /*                                                                    */
  4160  /* C must have space for set->digits digits.                          */
  4161  /*                                                                    */
  4162  /* ------------------------------------------------------------------ */
  4163  /*   The underlying algorithm of this routine is the same as in the   */
  4164  /*   1981 S/370 implementation, that is, non-restoring long division  */
  4165  /*   with bi-unit (rather than bi-digit) estimation for each unit     */
  4166  /*   multiplier.  In this pseudocode overview, complications for the  */
  4167  /*   Remainder operators and division residues for exact rounding are */
  4168  /*   omitted for clarity.                                             */
  4169  /*                                                                    */
  4170  /*     Prepare operands and handle special values                     */
  4171  /*     Test for x/0 and then 0/x                                      */
  4172  /*     Exp =Exp1 - Exp2                                               */
  4173  /*     Exp =Exp +len(var1) -len(var2)                                 */
  4174  /*     Sign=Sign1 * Sign2                                             */
  4175  /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
  4176  /*     Pad Var2 to same length as Var1                                */
  4177  /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
  4178  /*     have=0                                                         */
  4179  /*     Do until (have=digits+1 OR residue=0)                          */
  4180  /*       if exp<0 then if integer divide/residue then leave           */
  4181  /*       this_unit=0                                                  */
  4182  /*       Do forever                                                   */
  4183  /*          compare numbers                                           */
  4184  /*          if <0 then leave inner_loop                               */
  4185  /*          if =0 then (* quick exit without subtract *) do           */
  4186  /*             this_unit=this_unit+1; output this_unit                */
  4187  /*             leave outer_loop; end                                  */
  4188  /*          Compare lengths of numbers (mantissae):                   */
  4189  /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
  4190  /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
  4191  /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
  4192  /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
  4193  /*          if mult=0 then mult=1                                     */
  4194  /*          this_unit=this_unit+mult                                  */
  4195  /*          subtract                                                  */
  4196  /*          end inner_loop                                            */
  4197  /*        if have\=0 | this_unit\=0 then do                           */
  4198  /*          output this_unit                                          */
  4199  /*          have=have+1; end                                          */
  4200  /*        var2=var2/10                                                */
  4201  /*        exp=exp-1                                                   */
  4202  /*        end outer_loop                                              */
  4203  /*     exp=exp+1   -- set the proper exponent                         */
  4204  /*     if have=0 then generate answer=0                               */
  4205  /*     Return (Result is defined by Var1)                             */
  4206  /*                                                                    */
  4207  /* ------------------------------------------------------------------ */
  4208  /* Two working buffers are needed during the division; one (digits+   */
  4209  /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
  4210  /* long subtractions.  These are acc and var1 respectively.           */
  4211  /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
  4212  /* The static buffers may be larger than might be expected to allow   */
  4213  /* for calls from higher-level funtions (notable exp).                */
  4214  /* ------------------------------------------------------------------ */
  4215  static decNumber * decDivideOp(decNumber *res,
  4216                                 const decNumber *lhs, const decNumber *rhs,
  4217                                 decContext *set, Flag op, uInt *status) {
  4218    #if DECSUBSET
  4219    decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
  4220    decNumber *allocrhs=NULL;        // .., rhs
  4221    #endif
  4222    Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer
  4223    Unit  *acc=accbuff;              // -> accumulator array for result
  4224    Unit  *allocacc=NULL;            // -> allocated buffer, iff allocated
  4225    Unit  *accnext;                  // -> where next digit will go
  4226    Int   acclength;                 // length of acc needed [Units]
  4227    Int   accunits;                  // count of units accumulated
  4228    Int   accdigits;                 // count of digits accumulated
  4229  
  4230    Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  // buffer for var1
  4231    Unit  *var1=varbuff;             // -> var1 array for long subtraction
  4232    Unit  *varalloc=NULL;            // -> allocated buffer, iff used
  4233    Unit  *msu1;                     // -> msu of var1
  4234  
  4235    const Unit *var2;                // -> var2 array
  4236    const Unit *msu2;                // -> msu of var2
  4237    Int   msu2plus;                  // msu2 plus one [does not vary]
  4238    eInt  msu2pair;                  // msu2 pair plus one [does not vary]
  4239  
  4240    Int   var1units, var2units;      // actual lengths
  4241    Int   var2ulen;                  // logical length (units)
  4242    Int   var1initpad=0;             // var1 initial padding (digits)
  4243    Int   maxdigits;                 // longest LHS or required acc length
  4244    Int   mult;                      // multiplier for subtraction
  4245    Unit  thisunit;                  // current unit being accumulated
  4246    Int   residue;                   // for rounding
  4247    Int   reqdigits=set->digits;     // requested DIGITS
  4248    Int   exponent;                  // working exponent
  4249    Int   maxexponent=0;             // DIVIDE maximum exponent if unrounded
  4250    uByte bits;                      // working sign
  4251    Unit  *target;                   // work
  4252    const Unit *source;              // ..
  4253    uInt  const *pow;                // ..
  4254    Int   shift, cut;                // ..
  4255    #if DECSUBSET
  4256    Int   dropped;                   // work
  4257    #endif
  4258  
  4259    #if DECCHECK
  4260    if (decCheckOperands(res, lhs, rhs, set)) return res;
  4261    #endif
  4262  
  4263    do {                             // protect allocated storage
  4264      #if DECSUBSET
  4265      if (!set->extended) {
  4266        // reduce operands and set lostDigits status, as needed
  4267        if (lhs->digits>reqdigits) {
  4268          alloclhs=decRoundOperand(lhs, set, status);
  4269          if (alloclhs==NULL) break;
  4270          lhs=alloclhs;
  4271          }
  4272        if (rhs->digits>reqdigits) {
  4273          allocrhs=decRoundOperand(rhs, set, status);
  4274          if (allocrhs==NULL) break;
  4275          rhs=allocrhs;
  4276          }
  4277        }
  4278      #endif
  4279      // [following code does not require input rounding]
  4280  
  4281      bits=(lhs->bits^rhs->bits)&DECNEG;  // assumed sign for divisions
  4282  
  4283      // handle infinities and NaNs
  4284      if (SPECIALARGS) {                  // a special bit set
  4285        if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
  4286          decNaNs(res, lhs, rhs, set, status);
  4287          break;
  4288          }
  4289        // one or two infinities
  4290        if (decNumberIsInfinite(lhs)) {   // LHS (dividend) is infinite
  4291          if (decNumberIsInfinite(rhs) || // two infinities are invalid ..
  4292              op & (REMAINDER | REMNEAR)) { // as is remainder of infinity
  4293            *status|=DEC_Invalid_operation;
  4294            break;
  4295            }
  4296          // [Note that infinity/0 raises no exceptions]
  4297          decNumberZero(res);
  4298          res->bits=bits|DECINF;          // set +/- infinity
  4299          break;
  4300          }
  4301         else {                           // RHS (divisor) is infinite
  4302          residue=0;
  4303          if (op&(REMAINDER|REMNEAR)) {
  4304            // result is [finished clone of] lhs
  4305            decCopyFit(res, lhs, set, &residue, status);
  4306            }
  4307           else {  // a division
  4308            decNumberZero(res);
  4309            res->bits=bits;               // set +/- zero
  4310            // for DIVIDEINT the exponent is always 0.  For DIVIDE, result
  4311            // is a 0 with infinitely negative exponent, clamped to minimum
  4312            if (op&DIVIDE) {
  4313              res->exponent=set->emin-set->digits+1;
  4314              *status|=DEC_Clamped;
  4315              }
  4316            }
  4317          decFinish(res, set, &residue, status);
  4318          break;
  4319          }
  4320        }
  4321  
  4322      // handle 0 rhs (x/0)
  4323      if (ISZERO(rhs)) {                  // x/0 is always exceptional
  4324        if (ISZERO(lhs)) {
  4325          decNumberZero(res);             // [after lhs test]
  4326          *status|=DEC_Division_undefined;// 0/0 will become NaN
  4327          }
  4328         else {
  4329          decNumberZero(res);
  4330          if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
  4331           else {
  4332            *status|=DEC_Division_by_zero; // x/0
  4333            res->bits=bits|DECINF;         // .. is +/- Infinity
  4334            }
  4335          }
  4336        break;}
  4337  
  4338      // handle 0 lhs (0/x)
  4339      if (ISZERO(lhs)) {                  // 0/x [x!=0]
  4340        #if DECSUBSET
  4341        if (!set->extended) decNumberZero(res);
  4342         else {
  4343        #endif
  4344          if (op&DIVIDE) {
  4345            residue=0;
  4346            exponent=lhs->exponent-rhs->exponent; // ideal exponent
  4347            decNumberCopy(res, lhs);      // [zeros always fit]
  4348            res->bits=bits;               // sign as computed
  4349            res->exponent=exponent;       // exponent, too
  4350            decFinalize(res, set, &residue, status);   // check exponent
  4351            }
  4352           else if (op&DIVIDEINT) {
  4353            decNumberZero(res);           // integer 0
  4354            res->bits=bits;               // sign as computed
  4355            }
  4356           else {                         // a remainder
  4357            exponent=rhs->exponent;       // [save in case overwrite]
  4358            decNumberCopy(res, lhs);      // [zeros always fit]
  4359            if (exponent<res->exponent) res->exponent=exponent; // use lower
  4360            }
  4361        #if DECSUBSET
  4362          }
  4363        #endif
  4364        break;}
  4365  
  4366      // Precalculate exponent.  This starts off adjusted (and hence fits
  4367      // in 31 bits) and becomes the usual unadjusted exponent as the
  4368      // division proceeds.  The order of evaluation is important, here,
  4369      // to avoid wrap.
  4370      exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
  4371  
  4372      // If the working exponent is -ve, then some quick exits are
  4373      // possible because the quotient is known to be <1
  4374      // [for REMNEAR, it needs to be < -1, as -0.5 could need work]
  4375      if (exponent<0 && !(op==DIVIDE)) {
  4376        if (op&DIVIDEINT) {
  4377          decNumberZero(res);                  // integer part is 0
  4378          #if DECSUBSET
  4379          if (set->extended)
  4380          #endif
  4381            res->bits=bits;                    // set +/- zero
  4382          break;}
  4383        // fastpath remainders so long as the lhs has the smaller
  4384        // (or equal) exponent
  4385        if (lhs->exponent<=rhs->exponent) {
  4386          if (op&REMAINDER || exponent<-1) {
  4387            // It is REMAINDER or safe REMNEAR; result is [finished
  4388            // clone of] lhs  (r = x - 0*y)
  4389            residue=0;
  4390            decCopyFit(res, lhs, set, &residue, status);
  4391            decFinish(res, set, &residue, status);
  4392            break;
  4393            }
  4394          // [unsafe REMNEAR drops through]
  4395          }
  4396        } // fastpaths
  4397  
  4398      /* Long (slow) division is needed; roll up the sleeves... */
  4399  
  4400      // The accumulator will hold the quotient of the division.
  4401      // If it needs to be too long for stack storage, then allocate.
  4402      acclength=D2U(reqdigits+DECDPUN);   // in Units
  4403      if (acclength*sizeof(Unit)>sizeof(accbuff)) {
  4404        // printf("malloc dvacc %ld units\n", acclength);
  4405        allocacc=(Unit *)malloc(acclength*sizeof(Unit));
  4406        if (allocacc==NULL) {             // hopeless -- abandon
  4407          *status|=DEC_Insufficient_storage;
  4408          break;}
  4409        acc=allocacc;                     // use the allocated space
  4410        }
  4411  
  4412      // var1 is the padded LHS ready for subtractions.
  4413      // If it needs to be too long for stack storage, then allocate.
  4414      // The maximum units needed for var1 (long subtraction) is:
  4415      // Enough for
  4416      //     (rhs->digits+reqdigits-1) -- to allow full slide to right
  4417      // or  (lhs->digits)             -- to allow for long lhs
  4418      // whichever is larger
  4419      //   +1                -- for rounding of slide to right
  4420      //   +1                -- for leading 0s
  4421      //   +1                -- for pre-adjust if a remainder or DIVIDEINT
  4422      // [Note: unused units do not participate in decUnitAddSub data]
  4423      maxdigits=rhs->digits+reqdigits-1;
  4424      if (lhs->digits>maxdigits) maxdigits=lhs->digits;
  4425      var1units=D2U(maxdigits)+2;
  4426      // allocate a guard unit above msu1 for REMAINDERNEAR
  4427      if (!(op&DIVIDE)) var1units++;
  4428      if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
  4429        // printf("malloc dvvar %ld units\n", var1units+1);
  4430        varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
  4431        if (varalloc==NULL) {             // hopeless -- abandon
  4432          *status|=DEC_Insufficient_storage;
  4433          break;}
  4434        var1=varalloc;                    // use the allocated space
  4435        }
  4436  
  4437      // Extend the lhs and rhs to full long subtraction length.  The lhs
  4438      // is truly extended into the var1 buffer, with 0 padding, so a
  4439      // subtract in place is always possible.  The rhs (var2) has
  4440      // virtual padding (implemented by decUnitAddSub).
  4441      // One guard unit was allocated above msu1 for rem=rem+rem in
  4442      // REMAINDERNEAR.
  4443      msu1=var1+var1units-1;              // msu of var1
  4444      source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array
  4445      for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
  4446      for (; target>=var1; target--) *target=0;
  4447  
  4448      // rhs (var2) is left-aligned with var1 at the start
  4449      var2ulen=var1units;                 // rhs logical length (units)
  4450      var2units=D2U(rhs->digits);         // rhs actual length (units)
  4451      var2=rhs->lsu;                      // -> rhs array
  4452      msu2=var2+var2units-1;              // -> msu of var2 [never changes]
  4453      // now set up the variables which will be used for estimating the
  4454      // multiplication factor.  If these variables are not exact, add
  4455      // 1 to make sure that the multiplier is never overestimated.
  4456      msu2plus=*msu2;                     // it's value ..
  4457      if (var2units>1) msu2plus++;        // .. +1 if any more
  4458      msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..
  4459      if (var2units>1) {                  // .. [else treat 2nd as 0]
  4460        msu2pair+=*(msu2-1);              // ..
  4461        if (var2units>2) msu2pair++;      // .. +1 if any more
  4462        }
  4463  
  4464      // The calculation is working in units, which may have leading zeros,
  4465      // but the exponent was calculated on the assumption that they are
  4466      // both left-aligned.  Adjust the exponent to compensate: add the
  4467      // number of leading zeros in var1 msu and subtract those in var2 msu.
  4468      // [This is actually done by counting the digits and negating, as
  4469      // lead1=DECDPUN-digits1, and similarly for lead2.]
  4470      for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
  4471      for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
  4472  
  4473      // Now, if doing an integer divide or remainder, ensure that
  4474      // the result will be Unit-aligned.  To do this, shift the var1
  4475      // accumulator towards least if need be.  (It's much easier to
  4476      // do this now than to reassemble the residue afterwards, if
  4477      // doing a remainder.)  Also ensure the exponent is not negative.
  4478      if (!(op&DIVIDE)) {
  4479        Unit *u;                          // work
  4480        // save the initial 'false' padding of var1, in digits
  4481        var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
  4482        // Determine the shift to do.
  4483        if (exponent<0) cut=-exponent;
  4484         else cut=DECDPUN-exponent%DECDPUN;
  4485        decShiftToLeast(var1, var1units, cut);
  4486        exponent+=cut;                    // maintain numerical value
  4487        var1initpad-=cut;                 // .. and reduce padding
  4488        // clean any most-significant units which were just emptied
  4489        for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
  4490        } // align
  4491       else { // is DIVIDE
  4492        maxexponent=lhs->exponent-rhs->exponent;    // save
  4493        // optimization: if the first iteration will just produce 0,
  4494        // preadjust to skip it [valid for DIVIDE only]
  4495        if (*msu1<*msu2) {
  4496          var2ulen--;                     // shift down
  4497          exponent-=DECDPUN;              // update the exponent
  4498          }
  4499        }
  4500  
  4501      // ---- start the long-division loops ------------------------------
  4502      accunits=0;                         // no units accumulated yet
  4503      accdigits=0;                        // .. or digits
  4504      accnext=acc+acclength-1;            // -> msu of acc [NB: allows digits+1]
  4505      for (;;) {                          // outer forever loop
  4506        thisunit=0;                       // current unit assumed 0
  4507        // find the next unit
  4508        for (;;) {                        // inner forever loop
  4509          // strip leading zero units [from either pre-adjust or from
  4510          // subtract last time around].  Leave at least one unit.
  4511          for (; *msu1==0 && msu1>var1; msu1--) var1units--;
  4512  
  4513          if (var1units<var2ulen) break;       // var1 too low for subtract
  4514          if (var1units==var2ulen) {           // unit-by-unit compare needed
  4515            // compare the two numbers, from msu
  4516            const Unit *pv1, *pv2;
  4517            Unit v2;                           // units to compare
  4518            pv2=msu2;                          // -> msu
  4519            for (pv1=msu1; ; pv1--, pv2--) {
  4520              // v1=*pv1 -- always OK
  4521              v2=0;                            // assume in padding
  4522              if (pv2>=var2) v2=*pv2;          // in range
  4523              if (*pv1!=v2) break;             // no longer the same
  4524              if (pv1==var1) break;            // done; leave pv1 as is
  4525              }
  4526            // here when all inspected or a difference seen
  4527            if (*pv1<v2) break;                // var1 too low to subtract
  4528            if (*pv1==v2) {                    // var1 == var2
  4529              // reach here if var1 and var2 are identical; subtraction
  4530              // would increase digit by one, and the residue will be 0 so
  4531              // the calculation is done; leave the loop with residue=0.
  4532              thisunit++;                      // as though subtracted
  4533              *var1=0;                         // set var1 to 0
  4534              var1units=1;                     // ..
  4535              break;  // from inner
  4536              } // var1 == var2
  4537            // *pv1>v2.  Prepare for real subtraction; the lengths are equal
  4538            // Estimate the multiplier (there's always a msu1-1)...
  4539            // Bring in two units of var2 to provide a good estimate.
  4540            mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
  4541            } // lengths the same
  4542           else { // var1units > var2ulen, so subtraction is safe
  4543            // The var2 msu is one unit towards the lsu of the var1 msu,
  4544            // so only one unit for var2 can be used.
  4545            mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
  4546            }
  4547          if (mult==0) mult=1;                 // must always be at least 1
  4548          // subtraction needed; var1 is > var2
  4549          thisunit=(Unit)(thisunit+mult);      // accumulate
  4550          // subtract var1-var2, into var1; only the overlap needs
  4551          // processing, as this is an in-place calculation
  4552          shift=var2ulen-var2units;
  4553          #if DECTRACE
  4554            decDumpAr('1', &var1[shift], var1units-shift);
  4555            decDumpAr('2', var2, var2units);
  4556            printf("m=%ld\n", -mult);
  4557          #endif
  4558          decUnitAddSub(&var1[shift], var1units-shift,
  4559                        var2, var2units, 0,
  4560                        &var1[shift], -mult);
  4561          #if DECTRACE
  4562            decDumpAr('#', &var1[shift], var1units-shift);
  4563          #endif
  4564          // var1 now probably has leading zeros; these are removed at the
  4565          // top of the inner loop.
  4566          } // inner loop
  4567  
  4568        // The next unit has been calculated in full; unless it's a
  4569        // leading zero, add to acc
  4570        if (accunits!=0 || thisunit!=0) {      // is first or non-zero
  4571          *accnext=thisunit;                   // store in accumulator
  4572          // account exactly for the new digits
  4573          if (accunits==0) {
  4574            accdigits++;                       // at least one
  4575            for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
  4576            }
  4577           else accdigits+=DECDPUN;
  4578          accunits++;                          // update count
  4579          accnext--;                           // ready for next
  4580          if (accdigits>reqdigits) break;      // have enough digits
  4581          }
  4582  
  4583        // if the residue is zero, the operation is done (unless divide
  4584        // or divideInteger and still not enough digits yet)
  4585        if (*var1==0 && var1units==1) {        // residue is 0
  4586          if (op&(REMAINDER|REMNEAR)) break;
  4587          if ((op&DIVIDE) && (exponent<=maxexponent)) break;
  4588          // [drop through if divideInteger]
  4589          }
  4590        // also done enough if calculating remainder or integer
  4591        // divide and just did the last ('units') unit
  4592        if (exponent==0 && !(op&DIVIDE)) break;
  4593  
  4594        // to get here, var1 is less than var2, so divide var2 by the per-
  4595        // Unit power of ten and go for the next digit
  4596        var2ulen--;                            // shift down
  4597        exponent-=DECDPUN;                     // update the exponent
  4598        } // outer loop
  4599  
  4600      // ---- division is complete ---------------------------------------
  4601      // here: acc      has at least reqdigits+1 of good results (or fewer
  4602      //                if early stop), starting at accnext+1 (its lsu)
  4603      //       var1     has any residue at the stopping point
  4604      //       accunits is the number of digits collected in acc
  4605      if (accunits==0) {             // acc is 0
  4606        accunits=1;                  // show have a unit ..
  4607        accdigits=1;                 // ..
  4608        *accnext=0;                  // .. whose value is 0
  4609        }
  4610       else accnext++;               // back to last placed
  4611      // accnext now -> lowest unit of result
  4612  
  4613      residue=0;                     // assume no residue
  4614      if (op&DIVIDE) {
  4615        // record the presence of any residue, for rounding
  4616        if (*var1!=0 || var1units>1) residue=1;
  4617         else { // no residue
  4618          // Had an exact division; clean up spurious trailing 0s.
  4619          // There will be at most DECDPUN-1, from the final multiply,
  4620          // and then only if the result is non-0 (and even) and the
  4621          // exponent is 'loose'.
  4622          #if DECDPUN>1
  4623          Unit lsu=*accnext;
  4624          if (!(lsu&0x01) && (lsu!=0)) {
  4625            // count the trailing zeros
  4626            Int drop=0;
  4627            for (;; drop++) {    // [will terminate because lsu!=0]
  4628              if (exponent>=maxexponent) break;     // don't chop real 0s
  4629              #if DECDPUN<=4
  4630                if ((lsu-QUOT10(lsu, drop+1)
  4631                    *powers[drop+1])!=0) break;     // found non-0 digit
  4632              #else
  4633                if (lsu%powers[drop+1]!=0) break;   // found non-0 digit
  4634              #endif
  4635              exponent++;
  4636              }
  4637            if (drop>0) {
  4638              accunits=decShiftToLeast(accnext, accunits, drop);
  4639              accdigits=decGetDigits(accnext, accunits);
  4640              accunits=D2U(accdigits);
  4641              // [exponent was adjusted in the loop]
  4642              }
  4643            } // neither odd nor 0
  4644          #endif
  4645          } // exact divide
  4646        } // divide
  4647       else /* op!=DIVIDE */ {
  4648        // check for coefficient overflow
  4649        if (accdigits+exponent>reqdigits) {
  4650          *status|=DEC_Division_impossible;
  4651          break;
  4652          }
  4653        if (op & (REMAINDER|REMNEAR)) {
  4654          // [Here, the exponent will be 0, because var1 was adjusted
  4655          // appropriately.]
  4656          Int postshift;                       // work
  4657          Flag wasodd=0;                       // integer was odd
  4658          Unit *quotlsu;                       // for save
  4659          Int  quotdigits;                     // ..
  4660  
  4661          bits=lhs->bits;                      // remainder sign is always as lhs
  4662  
  4663          // Fastpath when residue is truly 0 is worthwhile [and
  4664          // simplifies the code below]
  4665          if (*var1==0 && var1units==1) {      // residue is 0
  4666            Int exp=lhs->exponent;             // save min(exponents)
  4667            if (rhs->exponent<exp) exp=rhs->exponent;
  4668            decNumberZero(res);                // 0 coefficient
  4669            #if DECSUBSET
  4670            if (set->extended)
  4671            #endif
  4672            res->exponent=exp;                 // .. with proper exponent
  4673            res->bits=(uByte)(bits&DECNEG);          // [cleaned]
  4674            decFinish(res, set, &residue, status);   // might clamp
  4675            break;
  4676            }
  4677          // note if the quotient was odd
  4678          if (*accnext & 0x01) wasodd=1;       // acc is odd
  4679          quotlsu=accnext;                     // save in case need to reinspect
  4680          quotdigits=accdigits;                // ..
  4681  
  4682          // treat the residue, in var1, as the value to return, via acc
  4683          // calculate the unused zero digits.  This is the smaller of:
  4684          //   var1 initial padding (saved above)
  4685          //   var2 residual padding, which happens to be given by:
  4686          postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
  4687          // [the 'exponent' term accounts for the shifts during divide]
  4688          if (var1initpad<postshift) postshift=var1initpad;
  4689  
  4690          // shift var1 the requested amount, and adjust its digits
  4691          var1units=decShiftToLeast(var1, var1units, postshift);
  4692          accnext=var1;
  4693          accdigits=decGetDigits(var1, var1units);
  4694          accunits=D2U(accdigits);
  4695  
  4696          exponent=lhs->exponent;         // exponent is smaller of lhs & rhs
  4697          if (rhs->exponent<exponent) exponent=rhs->exponent;
  4698  
  4699          // Now correct the result if doing remainderNear; if it
  4700          // (looking just at coefficients) is > rhs/2, or == rhs/2 and
  4701          // the integer was odd then the result should be rem-rhs.
  4702          if (op&REMNEAR) {
  4703            Int compare, tarunits;        // work
  4704            Unit *up;                     // ..
  4705            // calculate remainder*2 into the var1 buffer (which has
  4706            // 'headroom' of an extra unit and hence enough space)
  4707            // [a dedicated 'double' loop would be faster, here]
  4708            tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
  4709                                   0, accnext, 1);
  4710            // decDumpAr('r', accnext, tarunits);
  4711  
  4712            // Here, accnext (var1) holds tarunits Units with twice the
  4713            // remainder's coefficient, which must now be compared to the
  4714            // RHS.  The remainder's exponent may be smaller than the RHS's.
  4715            compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
  4716                                   rhs->exponent-exponent);
  4717            if (compare==BADINT) {             // deep trouble
  4718              *status|=DEC_Insufficient_storage;
  4719              break;}
  4720  
  4721            // now restore the remainder by dividing by two; the lsu
  4722            // is known to be even.
  4723            for (up=accnext; up<accnext+tarunits; up++) {
  4724              Int half;              // half to add to lower unit
  4725              half=*up & 0x01;
  4726              *up/=2;                // [shift]
  4727              if (!half) continue;
  4728              *(up-1)+=(DECDPUNMAX+1)/2;
  4729              }
  4730            // [accunits still describes the original remainder length]
  4731  
  4732            if (compare>0 || (compare==0 && wasodd)) { // adjustment needed
  4733              Int exp, expunits, exprem;       // work
  4734              // This is effectively causing round-up of the quotient,
  4735              // so if it was the rare case where it was full and all
  4736              // nines, it would overflow and hence division-impossible
  4737              // should be raised
  4738              Flag allnines=0;                 // 1 if quotient all nines
  4739              if (quotdigits==reqdigits) {     // could be borderline
  4740                for (up=quotlsu; ; up++) {
  4741                  if (quotdigits>DECDPUN) {
  4742                    if (*up!=DECDPUNMAX) break;// non-nines
  4743                    }
  4744                   else {                      // this is the last Unit
  4745                    if (*up==powers[quotdigits]-1) allnines=1;
  4746                    break;
  4747                    }
  4748                  quotdigits-=DECDPUN;         // checked those digits
  4749                  } // up
  4750                } // borderline check
  4751              if (allnines) {
  4752                *status|=DEC_Division_impossible;
  4753                break;}
  4754  
  4755              // rem-rhs is needed; the sign will invert.  Again, var1
  4756              // can safely be used for the working Units array.
  4757              exp=rhs->exponent-exponent;      // RHS padding needed
  4758              // Calculate units and remainder from exponent.
  4759              expunits=exp/DECDPUN;
  4760              exprem=exp%DECDPUN;
  4761              // subtract [A+B*(-m)]; the result will always be negative
  4762              accunits=-decUnitAddSub(accnext, accunits,
  4763                                      rhs->lsu, D2U(rhs->digits),
  4764                                      expunits, accnext, -(Int)powers[exprem]);
  4765              accdigits=decGetDigits(accnext, accunits); // count digits exactly
  4766              accunits=D2U(accdigits);    // and recalculate the units for copy
  4767              // [exponent is as for original remainder]
  4768              bits^=DECNEG;               // flip the sign
  4769              }
  4770            } // REMNEAR
  4771          } // REMAINDER or REMNEAR
  4772        } // not DIVIDE
  4773  
  4774      // Set exponent and bits
  4775      res->exponent=exponent;
  4776      res->bits=(uByte)(bits&DECNEG);          // [cleaned]
  4777  
  4778      // Now the coefficient.
  4779      decSetCoeff(res, set, accnext, accdigits, &residue, status);
  4780  
  4781      decFinish(res, set, &residue, status);   // final cleanup
  4782  
  4783      #if DECSUBSET
  4784      // If a divide then strip trailing zeros if subset [after round]
  4785      if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
  4786      #endif
  4787      } while(0);                              // end protected
  4788  
  4789    if (varalloc!=NULL) free(varalloc);   // drop any storage used
  4790    if (allocacc!=NULL) free(allocacc);   // ..
  4791    #if DECSUBSET
  4792    if (allocrhs!=NULL) free(allocrhs);   // ..
  4793    if (alloclhs!=NULL) free(alloclhs);   // ..
  4794    #endif
  4795    return res;
  4796    } // decDivideOp
  4797  
  4798  /* ------------------------------------------------------------------ */
  4799  /* decMultiplyOp -- multiplication operation                          */
  4800  /*                                                                    */
  4801  /*  This routine performs the multiplication C=A x B.                 */
  4802  /*                                                                    */
  4803  /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
  4804  /*   lhs is A                                                         */
  4805  /*   rhs is B                                                         */
  4806  /*   set is the context                                               */
  4807  /*   status is the usual accumulator                                  */
  4808  /*                                                                    */
  4809  /* C must have space for set->digits digits.                          */
  4810  /*                                                                    */
  4811  /* ------------------------------------------------------------------ */
  4812  /* 'Classic' multiplication is used rather than Karatsuba, as the     */
  4813  /* latter would give only a minor improvement for the short numbers   */
  4814  /* expected to be handled most (and uses much more memory).           */
  4815  /*                                                                    */
  4816  /* There are two major paths here: the general-purpose ('old code')   */
  4817  /* path which handles all DECDPUN values, and a fastpath version      */
  4818  /* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
  4819  /* than two calls to decUnitAddSub would be made.                     */
  4820  /*                                                                    */
  4821  /* The fastpath version lumps units together into 8-digit or 9-digit  */
  4822  /* chunks, and also uses a lazy carry strategy to minimise expensive  */
  4823  /* 64-bit divisions.  The chunks are then broken apart again into     */
  4824  /* units for continuing processing.  Despite this overhead, the       */
  4825  /* fastpath can speed up some 16-digit operations by 10x (and much    */
  4826  /* more for higher-precision calculations).                           */
  4827  /*                                                                    */
  4828  /* A buffer always has to be used for the accumulator; in the         */
  4829  /* fastpath, buffers are also always needed for the chunked copies of */
  4830  /* of the operand coefficients.                                       */
  4831  /* Static buffers are larger than needed just for multiply, to allow  */
  4832  /* for calls from other operations (notably exp).                     */
  4833  /* ------------------------------------------------------------------ */
  4834  #define FASTMUL (DECUSE64 && DECDPUN<5)
  4835  static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
  4836                                   const decNumber *rhs, decContext *set,
  4837                                   uInt *status) {
  4838    Int    accunits;                 // Units of accumulator in use
  4839    Int    exponent;                 // work
  4840    Int    residue=0;                // rounding residue
  4841    uByte  bits;                     // result sign
  4842    Unit  *acc;                      // -> accumulator Unit array
  4843    Int    needbytes;                // size calculator
  4844    void  *allocacc=NULL;            // -> allocated accumulator, iff allocated
  4845    Unit  accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,
  4846                                     // *4 for calls from other operations)
  4847    const Unit *mer, *mermsup;       // work
  4848    Int   madlength;                 // Units in multiplicand
  4849    Int   shift;                     // Units to shift multiplicand by
  4850  
  4851    #if FASTMUL
  4852      // if DECDPUN is 1 or 3 work in base 10**9, otherwise
  4853      // (DECDPUN is 2 or 4) then work in base 10**8
  4854      #if DECDPUN & 1                // odd
  4855        #define FASTBASE 1000000000  // base
  4856        #define FASTDIGS          9  // digits in base
  4857        #define FASTLAZY         18  // carry resolution point [1->18]
  4858      #else
  4859        #define FASTBASE  100000000
  4860        #define FASTDIGS          8
  4861        #define FASTLAZY       1844  // carry resolution point [1->1844]
  4862      #endif
  4863      // three buffers are used, two for chunked copies of the operands
  4864      // (base 10**8 or base 10**9) and one base 2**64 accumulator with
  4865      // lazy carry evaluation
  4866      uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
  4867      uInt  *zlhi=zlhibuff;                 // -> lhs array
  4868      uInt  *alloclhi=NULL;                 // -> allocated buffer, iff allocated
  4869      uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
  4870      uInt  *zrhi=zrhibuff;                 // -> rhs array
  4871      uInt  *allocrhi=NULL;                 // -> allocated buffer, iff allocated
  4872      uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)
  4873      // [allocacc is shared for both paths, as only one will run]
  4874      uLong *zacc=zaccbuff;          // -> accumulator array for exact result
  4875      #if DECDPUN==1
  4876      Int    zoff;                   // accumulator offset
  4877      #endif
  4878      uInt  *lip, *rip;              // item pointers
  4879      uInt  *lmsi, *rmsi;            // most significant items
  4880      Int    ilhs, irhs, iacc;       // item counts in the arrays
  4881      Int    lazy;                   // lazy carry counter
  4882      uLong  lcarry;                 // uLong carry
  4883      uInt   carry;                  // carry (NB not uLong)
  4884      Int    count;                  // work
  4885      const  Unit *cup;              // ..
  4886      Unit  *up;                     // ..
  4887      uLong *lp;                     // ..
  4888      Int    p;                      // ..
  4889    #endif
  4890  
  4891    #if DECSUBSET
  4892      decNumber *alloclhs=NULL;      // -> allocated buffer, iff allocated
  4893      decNumber *allocrhs=NULL;      // -> allocated buffer, iff allocated
  4894    #endif
  4895  
  4896    #if DECCHECK
  4897    if (decCheckOperands(res, lhs, rhs, set)) return res;
  4898    #endif
  4899  
  4900    // precalculate result sign
  4901    bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
  4902  
  4903    // handle infinities and NaNs
  4904    if (SPECIALARGS) {               // a special bit set
  4905      if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
  4906        decNaNs(res, lhs, rhs, set, status);
  4907        return res;}
  4908      // one or two infinities; Infinity * 0 is invalid
  4909      if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
  4910        ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
  4911        *status|=DEC_Invalid_operation;
  4912        return res;}
  4913      decNumberZero(res);
  4914      res->bits=bits|DECINF;         // infinity
  4915      return res;}
  4916  
  4917    // For best speed, as in DMSRCN [the original Rexx numerics
  4918    // module], use the shorter number as the multiplier (rhs) and
  4919    // the longer as the multiplicand (lhs) to minimise the number of
  4920    // adds (partial products)
  4921    if (lhs->digits<rhs->digits) {   // swap...
  4922      const decNumber *hold=lhs;
  4923      lhs=rhs;
  4924      rhs=hold;
  4925      }
  4926  
  4927    do {                             // protect allocated storage
  4928      #if DECSUBSET
  4929      if (!set->extended) {
  4930        // reduce operands and set lostDigits status, as needed
  4931        if (lhs->digits>set->digits) {
  4932          alloclhs=decRoundOperand(lhs, set, status);
  4933          if (alloclhs==NULL) break;
  4934          lhs=alloclhs;
  4935          }
  4936        if (rhs->digits>set->digits) {
  4937          allocrhs=decRoundOperand(rhs, set, status);
  4938          if (allocrhs==NULL) break;
  4939          rhs=allocrhs;
  4940          }
  4941        }
  4942      #endif
  4943      // [following code does not require input rounding]
  4944  
  4945      #if FASTMUL                    // fastpath can be used
  4946      // use the fast path if there are enough digits in the shorter
  4947      // operand to make the setup and takedown worthwhile
  4948      #define NEEDTWO (DECDPUN*2)    // within two decUnitAddSub calls
  4949      if (rhs->digits>NEEDTWO) {     // use fastpath...
  4950        // calculate the number of elements in each array
  4951        ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]
  4952        irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..
  4953        iacc=ilhs+irhs;
  4954  
  4955        // allocate buffers if required, as usual
  4956        needbytes=ilhs*sizeof(uInt);
  4957        if (needbytes>(Int)sizeof(zlhibuff)) {
  4958          alloclhi=(uInt *)malloc(needbytes);
  4959          zlhi=alloclhi;}
  4960        needbytes=irhs*sizeof(uInt);
  4961        if (needbytes>(Int)sizeof(zrhibuff)) {
  4962          allocrhi=(uInt *)malloc(needbytes);
  4963          zrhi=allocrhi;}
  4964  
  4965        // Allocating the accumulator space needs a special case when
  4966        // DECDPUN=1 because when converting the accumulator to Units
  4967        // after the multiplication each 8-byte item becomes 9 1-byte
  4968        // units.  Therefore iacc extra bytes are needed at the front
  4969        // (rounded up to a multiple of 8 bytes), and the uLong
  4970        // accumulator starts offset the appropriate number of units
  4971        // to the right to avoid overwrite during the unchunking.
  4972        needbytes=iacc*sizeof(uLong);
  4973        #if DECDPUN==1
  4974        zoff=(iacc+7)/8;        // items to offset by
  4975        needbytes+=zoff*8;
  4976        #endif
  4977        if (needbytes>(Int)sizeof(zaccbuff)) {
  4978          allocacc=(uLong *)malloc(needbytes);
  4979          zacc=(uLong *)allocacc;}
  4980        if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
  4981          *status|=DEC_Insufficient_storage;
  4982          break;}
  4983  
  4984        acc=(Unit *)zacc;       // -> target Unit array
  4985        #if DECDPUN==1
  4986        zacc+=zoff;             // start uLong accumulator to right
  4987        #endif
  4988  
  4989        // assemble the chunked copies of the left and right sides
  4990        for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
  4991          for (p=0, *lip=0; p<FASTDIGS && count>0;
  4992               p+=DECDPUN, cup++, count-=DECDPUN)
  4993            *lip+=*cup*powers[p];
  4994        lmsi=lip-1;     // save -> msi
  4995        for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
  4996          for (p=0, *rip=0; p<FASTDIGS && count>0;
  4997               p+=DECDPUN, cup++, count-=DECDPUN)
  4998            *rip+=*cup*powers[p];
  4999        rmsi=rip-1;     // save -> msi
  5000  
  5001        // zero the accumulator
  5002        for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
  5003  
  5004        /* Start the multiplication */
  5005        // Resolving carries can dominate the cost of accumulating the
  5006        // partial products, so this is only done when necessary.
  5007        // Each uLong item in the accumulator can hold values up to
  5008        // 2**64-1, and each partial product can be as large as
  5009        // (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to
  5010        // itself 18.4 times in a uLong without overflowing, so during
  5011        // the main calculation resolution is carried out every 18th
  5012        // add -- every 162 digits.  Similarly, when FASTDIGS=8, the
  5013        // partial products can be added to themselves 1844.6 times in
  5014        // a uLong without overflowing, so intermediate carry
  5015        // resolution occurs only every 14752 digits.  Hence for common
  5016        // short numbers usually only the one final carry resolution
  5017        // occurs.
  5018        // (The count is set via FASTLAZY to simplify experiments to
  5019        // measure the value of this approach: a 35% improvement on a
  5020        // [34x34] multiply.)
  5021        lazy=FASTLAZY;                         // carry delay count
  5022        for (rip=zrhi; rip<=rmsi; rip++) {     // over each item in rhs
  5023          lp=zacc+(rip-zrhi);                  // where to add the lhs
  5024          for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs
  5025            *lp+=(uLong)(*lip)*(*rip);         // [this should in-line]
  5026            } // lip loop
  5027          lazy--;
  5028          if (lazy>0 && rip!=rmsi) continue;
  5029          lazy=FASTLAZY;                       // reset delay count
  5030          // spin up the accumulator resolving overflows
  5031          for (lp=zacc; lp<zacc+iacc; lp++) {
  5032            if (*lp<FASTBASE) continue;        // it fits
  5033            lcarry=*lp/FASTBASE;               // top part [slow divide]
  5034            // lcarry can exceed 2**32-1, so check again; this check
  5035            // and occasional extra divide (slow) is well worth it, as
  5036            // it allows FASTLAZY to be increased to 18 rather than 4
  5037            // in the FASTDIGS=9 case
  5038            if (lcarry<FASTBASE) carry=(uInt)lcarry;  // [usual]
  5039             else { // two-place carry [fairly rare]
  5040              uInt carry2=(uInt)(lcarry/FASTBASE);    // top top part
  5041              *(lp+2)+=carry2;                        // add to item+2
  5042              *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]
  5043              carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]
  5044              }
  5045            *(lp+1)+=carry;                    // add to item above [inline]
  5046            *lp-=((uLong)FASTBASE*carry);      // [inline]
  5047            } // carry resolution
  5048          } // rip loop
  5049  
  5050        // The multiplication is complete; time to convert back into
  5051        // units.  This can be done in-place in the accumulator and in
  5052        // 32-bit operations, because carries were resolved after the
  5053        // final add.  This needs N-1 divides and multiplies for
  5054        // each item in the accumulator (which will become up to N
  5055        // units, where 2<=N<=9).
  5056        for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
  5057          uInt item=(uInt)*lp;                 // decapitate to uInt
  5058          for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
  5059            uInt part=item/(DECDPUNMAX+1);
  5060            *up=(Unit)(item-(part*(DECDPUNMAX+1)));
  5061            item=part;
  5062            } // p
  5063          *up=(Unit)item; up++;                // [final needs no division]
  5064          } // lp
  5065        accunits=up-acc;                       // count of units
  5066        }
  5067       else { // here to use units directly, without chunking ['old code']
  5068      #endif
  5069  
  5070        // if accumulator will be too long for local storage, then allocate
  5071        acc=accbuff;                 // -> assume buffer for accumulator
  5072        needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
  5073        if (needbytes>(Int)sizeof(accbuff)) {
  5074          allocacc=(Unit *)malloc(needbytes);
  5075          if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
  5076          acc=(Unit *)allocacc;                // use the allocated space
  5077          }
  5078  
  5079        /* Now the main long multiplication loop */
  5080        // Unlike the equivalent in the IBM Java implementation, there
  5081        // is no advantage in calculating from msu to lsu.  So, do it
  5082        // by the book, as it were.
  5083        // Each iteration calculates ACC=ACC+MULTAND*MULT
  5084        accunits=1;                  // accumulator starts at '0'
  5085        *acc=0;                      // .. (lsu=0)
  5086        shift=0;                     // no multiplicand shift at first
  5087        madlength=D2U(lhs->digits);  // this won't change
  5088        mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier
  5089  
  5090        for (mer=rhs->lsu; mer<mermsup; mer++) {
  5091          // Here, *mer is the next Unit in the multiplier to use
  5092          // If non-zero [optimization] add it...
  5093          if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
  5094                                              lhs->lsu, madlength, 0,
  5095                                              &acc[shift], *mer)
  5096                                              + shift;
  5097           else { // extend acc with a 0; it will be used shortly
  5098            *(acc+accunits)=0;       // [this avoids length of <=0 later]
  5099            accunits++;
  5100            }
  5101          // multiply multiplicand by 10**DECDPUN for next Unit to left
  5102          shift++;                   // add this for 'logical length'
  5103          } // n
  5104      #if FASTMUL
  5105        } // unchunked units
  5106      #endif
  5107      // common end-path
  5108      #if DECTRACE
  5109        decDumpAr('*', acc, accunits);         // Show exact result
  5110      #endif
  5111  
  5112      // acc now contains the exact result of the multiplication,
  5113      // possibly with a leading zero unit; build the decNumber from
  5114      // it, noting if any residue
  5115      res->bits=bits;                          // set sign
  5116      res->digits=decGetDigits(acc, accunits); // count digits exactly
  5117  
  5118      // There can be a 31-bit wrap in calculating the exponent.
  5119      // This can only happen if both input exponents are negative and
  5120      // both their magnitudes are large.  If there was a wrap, set a
  5121      // safe very negative exponent, from which decFinalize() will
  5122      // raise a hard underflow shortly.
  5123      exponent=lhs->exponent+rhs->exponent;    // calculate exponent
  5124      if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
  5125        exponent=-2*DECNUMMAXE;                // force underflow
  5126      res->exponent=exponent;                  // OK to overwrite now
  5127  
  5128  
  5129      // Set the coefficient.  If any rounding, residue records
  5130      decSetCoeff(res, set, acc, res->digits, &residue, status);
  5131      decFinish(res, set, &residue, status);   // final cleanup
  5132      } while(0);                         // end protected
  5133  
  5134    if (allocacc!=NULL) free(allocacc);   // drop any storage used
  5135    #if DECSUBSET
  5136    if (allocrhs!=NULL) free(allocrhs);   // ..
  5137    if (alloclhs!=NULL) free(alloclhs);   // ..
  5138    #endif
  5139    #if FASTMUL
  5140    if (allocrhi!=NULL) free(allocrhi);   // ..
  5141    if (alloclhi!=NULL) free(alloclhi);   // ..
  5142    #endif
  5143    return res;
  5144    } // decMultiplyOp
  5145  
  5146  /* ------------------------------------------------------------------ */
  5147  /* decExpOp -- effect exponentiation                                  */
  5148  /*                                                                    */
  5149  /*   This computes C = exp(A)                                         */
  5150  /*                                                                    */
  5151  /*   res is C, the result.  C may be A                                */
  5152  /*   rhs is A                                                         */
  5153  /*   set is the context; note that rounding mode has no effect        */
  5154  /*                                                                    */
  5155  /* C must have space for set->digits digits. status is updated but    */
  5156  /* not set.                                                           */
  5157  /*                                                                    */
  5158  /* Restrictions:                                                      */
  5159  /*                                                                    */
  5160  /*   digits, emax, and -emin in the context must be less than         */
  5161  /*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
  5162  /*   bounds or a zero.  This is an internal routine, so these         */
  5163  /*   restrictions are contractual and not enforced.                   */
  5164  /*                                                                    */
  5165  /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
  5166  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  5167  /* error in rare cases.                                               */
  5168  /*                                                                    */
  5169  /* Finite results will always be full precision and Inexact, except   */
  5170  /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
  5171  /* ------------------------------------------------------------------ */
  5172  /* This approach used here is similar to the algorithm described in   */
  5173  /*                                                                    */
  5174  /*   Variable Precision Exponential Function, T. E. Hull and          */
  5175  /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
  5176  /*   pp79-91, ACM, June 1986.                                         */
  5177  /*                                                                    */
  5178  /* with the main difference being that the iterations in the series   */
  5179  /* evaluation are terminated dynamically (which does not require the  */
  5180  /* extra variable-precision variables which are expensive in this     */
  5181  /* context).                                                          */
  5182  /*                                                                    */
  5183  /* The error analysis in Hull & Abrham's paper applies except for the */
  5184  /* round-off error accumulation during the series evaluation.  This   */
  5185  /* code does not precalculate the number of iterations and so cannot  */
  5186  /* use Horner's scheme.  Instead, the accumulation is done at double- */
  5187  /* precision, which ensures that the additions of the terms are exact */
  5188  /* and do not accumulate round-off (and any round-off errors in the   */
  5189  /* terms themselves move 'to the right' faster than they can          */
  5190  /* accumulate).  This code also extends the calculation by allowing,  */
  5191  /* in the spirit of other decNumber operators, the input to be more   */
  5192  /* precise than the result (the precision used is based on the more   */
  5193  /* precise of the input or requested result).                         */
  5194  /*                                                                    */
  5195  /* Implementation notes:                                              */
  5196  /*                                                                    */
  5197  /* 1. This is separated out as decExpOp so it can be called from      */
  5198  /*    other Mathematical functions (notably Ln) with a wider range    */
  5199  /*    than normal.  In particular, it can handle the slightly wider   */
  5200  /*    (double) range needed by Ln (which has to be able to calculate  */
  5201  /*    exp(-x) where x can be the tiniest number (Ntiny).              */
  5202  /*                                                                    */
  5203  /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
  5204  /*    iterations by appoximately a third with additional (although    */
  5205  /*    diminishing) returns as the range is reduced to even smaller    */
  5206  /*    fractions.  However, h (the power of 10 used to correct the     */
  5207  /*    result at the end, see below) must be kept <=8 as otherwise     */
  5208  /*    the final result cannot be computed.  Hence the leverage is a   */
  5209  /*    sliding value (8-h), where potentially the range is reduced     */
  5210  /*    more for smaller values.                                        */
  5211  /*                                                                    */
  5212  /*    The leverage that can be applied in this way is severely        */
  5213  /*    limited by the cost of the raise-to-the power at the end,       */
  5214  /*    which dominates when the number of iterations is small (less    */
  5215  /*    than ten) or when rhs is short.  As an example, the adjustment  */
  5216  /*    x**10,000,000 needs 31 multiplications, all but one full-width. */
  5217  /*                                                                    */
  5218  /* 3. The restrictions (especially precision) could be raised with    */
  5219  /*    care, but the full decNumber range seems very hard within the   */
  5220  /*    32-bit limits.                                                  */
  5221  /*                                                                    */
  5222  /* 4. The working precisions for the static buffers are twice the     */
  5223  /*    obvious size to allow for calls from decNumberPower.            */
  5224  /* ------------------------------------------------------------------ */
  5225  decNumber * decExpOp(decNumber *res, const decNumber *rhs,
  5226                           decContext *set, uInt *status) {
  5227    uInt ignore=0;                   // working status
  5228    Int h;                           // adjusted exponent for 0.xxxx
  5229    Int p;                           // working precision
  5230    Int residue;                     // rounding residue
  5231    uInt needbytes;                  // for space calculations
  5232    const decNumber *x=rhs;          // (may point to safe copy later)
  5233    decContext aset, tset, dset;     // working contexts
  5234    Int comp;                        // work
  5235  
  5236    // the argument is often copied to normalize it, so (unusually) it
  5237    // is treated like other buffers, using DECBUFFER, +1 in case
  5238    // DECBUFFER is 0
  5239    decNumber bufr[D2N(DECBUFFER*2+1)];
  5240    decNumber *allocrhs=NULL;        // non-NULL if rhs buffer allocated
  5241  
  5242    // the working precision will be no more than set->digits+8+1
  5243    // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER
  5244    // is 0 (and twice that for the accumulator)
  5245  
  5246    // buffer for t, term (working precision plus)
  5247    decNumber buft[D2N(DECBUFFER*2+9+1)];
  5248    decNumber *allocbuft=NULL;       // -> allocated buft, iff allocated
  5249    decNumber *t=buft;               // term
  5250    // buffer for a, accumulator (working precision * 2), at least 9
  5251    decNumber bufa[D2N(DECBUFFER*4+18+1)];
  5252    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
  5253    decNumber *a=bufa;               // accumulator
  5254    // decNumber for the divisor term; this needs at most 9 digits
  5255    // and so can be fixed size [16 so can use standard context]
  5256    decNumber bufd[D2N(16)];
  5257    decNumber *d=bufd;               // divisor
  5258    decNumber numone;                // constant 1
  5259  
  5260    #if DECCHECK
  5261    Int iterations=0;                // for later sanity check
  5262    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  5263    #endif
  5264  
  5265    do {                                  // protect allocated storage
  5266      if (SPECIALARG) {                   // handle infinities and NaNs
  5267        if (decNumberIsInfinite(rhs)) {   // an infinity
  5268          if (decNumberIsNegative(rhs))   // -Infinity -> +0
  5269            decNumberZero(res);
  5270           else decNumberCopy(res, rhs);  // +Infinity -> self
  5271          }
  5272         else decNaNs(res, rhs, NULL, set, status); // a NaN
  5273        break;}
  5274  
  5275      if (ISZERO(rhs)) {                  // zeros -> exact 1
  5276        decNumberZero(res);               // make clean 1
  5277        *res->lsu=1;                      // ..
  5278        break;}                           // [no status to set]
  5279  
  5280      // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path
  5281      // positive and negative tiny cases which will result in inexact
  5282      // 1.  This also allows the later add-accumulate to always be
  5283      // exact (because its length will never be more than twice the
  5284      // working precision).
  5285      // The comparator (tiny) needs just one digit, so use the
  5286      // decNumber d for it (reused as the divisor, etc., below); its
  5287      // exponent is such that if x is positive it will have
  5288      // set->digits-1 zeros between the decimal point and the digit,
  5289      // which is 4, and if x is negative one more zero there as the
  5290      // more precise result will be of the form 0.9999999 rather than
  5291      // 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0
  5292      // or 0.00000004 if digits=7 and x<0.  If RHS not larger than
  5293      // this then the result will be 1.000000
  5294      decNumberZero(d);                   // clean
  5295      *d->lsu=4;                          // set 4 ..
  5296      d->exponent=-set->digits;           // * 10**(-d)
  5297      if (decNumberIsNegative(rhs)) d->exponent--;  // negative case
  5298      comp=decCompare(d, rhs, 1);         // signless compare
  5299      if (comp==BADINT) {
  5300        *status|=DEC_Insufficient_storage;
  5301        break;}
  5302      if (comp>=0) {                      // rhs < d
  5303        Int shift=set->digits-1;
  5304        decNumberZero(res);               // set 1
  5305        *res->lsu=1;                      // ..
  5306        res->digits=decShiftToMost(res->lsu, 1, shift);
  5307        res->exponent=-shift;                  // make 1.0000...
  5308        *status|=DEC_Inexact | DEC_Rounded;    // .. inexactly
  5309        break;} // tiny
  5310  
  5311      // set up the context to be used for calculating a, as this is
  5312      // used on both paths below
  5313      decContextDefault(&aset, DEC_INIT_DECIMAL64);
  5314      // accumulator bounds are as requested (could underflow)
  5315      aset.emax=set->emax;                // usual bounds
  5316      aset.emin=set->emin;                // ..
  5317      aset.clamp=0;                       // and no concrete format
  5318  
  5319      // calculate the adjusted (Hull & Abrham) exponent (where the
  5320      // decimal point is just to the left of the coefficient msd)
  5321      h=rhs->exponent+rhs->digits;
  5322      // if h>8 then 10**h cannot be calculated safely; however, when
  5323      // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at
  5324      // least 6.59E+4342944, so (due to the restriction on Emax/Emin)
  5325      // overflow (or underflow to 0) is guaranteed -- so this case can
  5326      // be handled by simply forcing the appropriate excess
  5327      if (h>8) {                          // overflow/underflow
  5328        // set up here so Power call below will over or underflow to
  5329        // zero; set accumulator to either 2 or 0.02
  5330        // [stack buffer for a is always big enough for this]
  5331        decNumberZero(a);
  5332        *a->lsu=2;                        // not 1 but < exp(1)
  5333        if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02
  5334        h=8;                              // clamp so 10**h computable
  5335        p=9;                              // set a working precision
  5336        }
  5337       else {                             // h<=8
  5338        Int maxlever=(rhs->digits>8?1:0);
  5339        // [could/should increase this for precisions >40 or so, too]
  5340  
  5341        // if h is 8, cannot normalize to a lower upper limit because
  5342        // the final result will not be computable (see notes above),
  5343        // but leverage can be applied whenever h is less than 8.
  5344        // Apply as much as possible, up to a MAXLEVER digits, which
  5345        // sets the tradeoff against the cost of the later a**(10**h).
  5346        // As h is increased, the working precision below also
  5347        // increases to compensate for the "constant digits at the
  5348        // front" effect.
  5349        Int lever=MINI(8-h, maxlever);    // leverage attainable
  5350        Int use=-rhs->digits-lever;       // exponent to use for RHS
  5351        h+=lever;                         // apply leverage selected
  5352        if (h<0) {                        // clamp
  5353          use+=h;                         // [may end up subnormal]
  5354          h=0;
  5355          }
  5356        // Take a copy of RHS if it needs normalization (true whenever x>=1)
  5357        if (rhs->exponent!=use) {
  5358          decNumber *newrhs=bufr;         // assume will fit on stack
  5359          needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
  5360          if (needbytes>sizeof(bufr)) {   // need malloc space
  5361            allocrhs=(decNumber *)malloc(needbytes);
  5362            if (allocrhs==NULL) {         // hopeless -- abandon
  5363              *status|=DEC_Insufficient_storage;
  5364              break;}
  5365            newrhs=allocrhs;              // use the allocated space
  5366            }
  5367          decNumberCopy(newrhs, rhs);     // copy to safe space
  5368          newrhs->exponent=use;           // normalize; now <1
  5369          x=newrhs;                       // ready for use
  5370          // decNumberShow(x);
  5371          }
  5372  
  5373        // Now use the usual power series to evaluate exp(x).  The
  5374        // series starts as 1 + x + x^2/2 ... so prime ready for the
  5375        // third term by setting the term variable t=x, the accumulator
  5376        // a=1, and the divisor d=2.
  5377  
  5378        // First determine the working precision.  From Hull & Abrham
  5379        // this is set->digits+h+2.  However, if x is 'over-precise' we
  5380        // need to allow for all its digits to potentially participate
  5381        // (consider an x where all the excess digits are 9s) so in
  5382        // this case use x->digits+h+2
  5383        p=MAXI(x->digits, set->digits)+h+2;    // [h<=8]
  5384  
  5385        // a and t are variable precision, and depend on p, so space
  5386        // must be allocated for them if necessary
  5387  
  5388        // the accumulator needs to be able to hold 2p digits so that
  5389        // the additions on the second and subsequent iterations are
  5390        // sufficiently exact.
  5391        needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
  5392        if (needbytes>sizeof(bufa)) {     // need malloc space
  5393          allocbufa=(decNumber *)malloc(needbytes);
  5394          if (allocbufa==NULL) {          // hopeless -- abandon
  5395            *status|=DEC_Insufficient_storage;
  5396            break;}
  5397          a=allocbufa;                    // use the allocated space
  5398          }
  5399        // the term needs to be able to hold p digits (which is
  5400        // guaranteed to be larger than x->digits, so the initial copy
  5401        // is safe); it may also be used for the raise-to-power
  5402        // calculation below, which needs an extra two digits
  5403        needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
  5404        if (needbytes>sizeof(buft)) {     // need malloc space
  5405          allocbuft=(decNumber *)malloc(needbytes);
  5406          if (allocbuft==NULL) {          // hopeless -- abandon
  5407            *status|=DEC_Insufficient_storage;
  5408            break;}
  5409          t=allocbuft;                    // use the allocated space
  5410          }
  5411  
  5412        decNumberCopy(t, x);              // term=x
  5413        decNumberZero(a); *a->lsu=1;      // accumulator=1
  5414        decNumberZero(d); *d->lsu=2;      // divisor=2
  5415        decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment
  5416  
  5417        // set up the contexts for calculating a, t, and d
  5418        decContextDefault(&tset, DEC_INIT_DECIMAL64);
  5419        dset=tset;
  5420        // accumulator bounds are set above, set precision now
  5421        aset.digits=p*2;                  // double
  5422        // term bounds avoid any underflow or overflow
  5423        tset.digits=p;
  5424        tset.emin=DEC_MIN_EMIN;           // [emax is plenty]
  5425        // [dset.digits=16, etc., are sufficient]
  5426  
  5427        // finally ready to roll
  5428        for (;;) {
  5429          #if DECCHECK
  5430          iterations++;
  5431          #endif
  5432          // only the status from the accumulation is interesting
  5433          // [but it should remain unchanged after first add]
  5434          decAddOp(a, a, t, &aset, 0, status);           // a=a+t
  5435          decMultiplyOp(t, t, x, &tset, &ignore);        // t=t*x
  5436          decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  // t=t/d
  5437          // the iteration ends when the term cannot affect the result,
  5438          // if rounded to p digits, which is when its value is smaller
  5439          // than the accumulator by p+1 digits.  There must also be
  5440          // full precision in a.
  5441          if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
  5442              && (a->digits>=p)) break;
  5443          decAddOp(d, d, &numone, &dset, 0, &ignore);    // d=d+1
  5444          } // iterate
  5445  
  5446        #if DECCHECK
  5447        // just a sanity check; comment out test to show always
  5448        if (iterations>p+3)
  5449          printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5450                 (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
  5451        #endif
  5452        } // h<=8
  5453  
  5454      // apply postconditioning: a=a**(10**h) -- this is calculated
  5455      // at a slightly higher precision than Hull & Abrham suggest
  5456      if (h>0) {
  5457        Int seenbit=0;               // set once a 1-bit is seen
  5458        Int i;                       // counter
  5459        Int n=powers[h];             // always positive
  5460        aset.digits=p+2;             // sufficient precision
  5461        // avoid the overhead and many extra digits of decNumberPower
  5462        // as all that is needed is the short 'multipliers' loop; here
  5463        // accumulate the answer into t
  5464        decNumberZero(t); *t->lsu=1; // acc=1
  5465        for (i=1;;i++){              // for each bit [top bit ignored]
  5466          // abandon if have had overflow or terminal underflow
  5467          if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?
  5468            if (*status&DEC_Overflow || ISZERO(t)) break;}
  5469          n=n<<1;                    // move next bit to testable position
  5470          if (n<0) {                 // top bit is set
  5471            seenbit=1;               // OK, have a significant bit
  5472            decMultiplyOp(t, t, a, &aset, status); // acc=acc*x
  5473            }
  5474          if (i==31) break;          // that was the last bit
  5475          if (!seenbit) continue;    // no need to square 1
  5476          decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]
  5477          } /*i*/ // 32 bits
  5478        // decNumberShow(t);
  5479        a=t;                         // and carry on using t instead of a
  5480        }
  5481  
  5482      // Copy and round the result to res
  5483      residue=1;                          // indicate dirt to right ..
  5484      if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
  5485      aset.digits=set->digits;            // [use default rounding]
  5486      decCopyFit(res, a, &aset, &residue, status); // copy & shorten
  5487      decFinish(res, set, &residue, status);       // cleanup/set flags
  5488      } while(0);                         // end protected
  5489  
  5490    if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
  5491    if (allocbufa!=NULL) free(allocbufa); // ..
  5492    if (allocbuft!=NULL) free(allocbuft); // ..
  5493    // [status is handled by caller]
  5494    return res;
  5495    } // decExpOp
  5496  
  5497  /* ------------------------------------------------------------------ */
  5498  /* Initial-estimate natural logarithm table                           */
  5499  /*                                                                    */
  5500  /*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
  5501  /*           The result is a 4-digit encode of the coefficient (c=the */
  5502  /*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
  5503  /*           exponent (e=the bottom 2 bits encoding 0-3)              */
  5504  /*                                                                    */
  5505  /*           The resulting value is given by:                         */
  5506  /*                                                                    */
  5507  /*             v = -c * 10**(-e-3)                                    */
  5508  /*                                                                    */
  5509  /*           where e and c are extracted from entry k = LNnn[x-10]    */
  5510  /*           where x is truncated (NB) into the range 10 through 99,  */
  5511  /*           and then c = k>>2 and e = k&3.                           */
  5512  /* ------------------------------------------------------------------ */
  5513  const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
  5514    6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
  5515    5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
  5516   39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
  5517   29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
  5518   22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
  5519   15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
  5520   10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
  5521    5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
  5522   10130,  6046, 20055};
  5523  
  5524  /* ------------------------------------------------------------------ */
  5525  /* decLnOp -- effect natural logarithm                                */
  5526  /*                                                                    */
  5527  /*   This computes C = ln(A)                                          */
  5528  /*                                                                    */
  5529  /*   res is C, the result.  C may be A                                */
  5530  /*   rhs is A                                                         */
  5531  /*   set is the context; note that rounding mode has no effect        */
  5532  /*                                                                    */
  5533  /* C must have space for set->digits digits.                          */
  5534  /*                                                                    */
  5535  /* Notable cases:                                                     */
  5536  /*   A<0 -> Invalid                                                   */
  5537  /*   A=0 -> -Infinity (Exact)                                         */
  5538  /*   A=+Infinity -> +Infinity (Exact)                                 */
  5539  /*   A=1 exactly -> 0 (Exact)                                         */
  5540  /*                                                                    */
  5541  /* Restrictions (as for Exp):                                         */
  5542  /*                                                                    */
  5543  /*   digits, emax, and -emin in the context must be less than         */
  5544  /*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
  5545  /*   bounds or a zero.  This is an internal routine, so these         */
  5546  /*   restrictions are contractual and not enforced.                   */
  5547  /*                                                                    */
  5548  /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
  5549  /* almost always be correctly rounded, but may be up to 1 ulp in      */
  5550  /* error in rare cases.                                               */
  5551  /* ------------------------------------------------------------------ */
  5552  /* The result is calculated using Newton's method, with each          */
  5553  /* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
  5554  /* Epperson 1989.                                                     */
  5555  /*                                                                    */
  5556  /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
  5557  /* This has to be calculated at the sum of the precision of x and the */
  5558  /* working precision.                                                 */
  5559  /*                                                                    */
  5560  /* Implementation notes:                                              */
  5561  /*                                                                    */
  5562  /* 1. This is separated out as decLnOp so it can be called from       */
  5563  /*    other Mathematical functions (e.g., Log 10) with a wider range  */
  5564  /*    than normal.  In particular, it can handle the slightly wider   */
  5565  /*    (+9+2) range needed by a power function.                        */
  5566  /*                                                                    */
  5567  /* 2. The speed of this function is about 10x slower than exp, as     */
  5568  /*    it typically needs 4-6 iterations for short numbers, and the    */
  5569  /*    extra precision needed adds a squaring effect, twice.           */
  5570  /*                                                                    */
  5571  /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
  5572  /*    as these are common requests.  ln(10) is used by log10(x).      */
  5573  /*                                                                    */
  5574  /* 4. An iteration might be saved by widening the LNnn table, and     */
  5575  /*    would certainly save at least one if it were made ten times     */
  5576  /*    bigger, too (for truncated fractions 0.100 through 0.999).      */
  5577  /*    However, for most practical evaluations, at least four or five  */
  5578  /*    iterations will be neede -- so this would only speed up by      */
  5579  /*    20-25% and that probably does not justify increasing the table  */
  5580  /*    size.                                                           */
  5581  /*                                                                    */
  5582  /* 5. The static buffers are larger than might be expected to allow   */
  5583  /*    for calls from decNumberPower.                                  */
  5584  /* ------------------------------------------------------------------ */
  5585  decNumber * decLnOp(decNumber *res, const decNumber *rhs,
  5586                      decContext *set, uInt *status) {
  5587    uInt ignore=0;                   // working status accumulator
  5588    uInt needbytes;                  // for space calculations
  5589    Int residue;                     // rounding residue
  5590    Int r;                           // rhs=f*10**r [see below]
  5591    Int p;                           // working precision
  5592    Int pp;                          // precision for iteration
  5593    Int t;                           // work
  5594  
  5595    // buffers for a (accumulator, typically precision+2) and b
  5596    // (adjustment calculator, same size)
  5597    decNumber bufa[D2N(DECBUFFER+12)];
  5598    decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
  5599    decNumber *a=bufa;               // accumulator/work
  5600    decNumber bufb[D2N(DECBUFFER*2+2)];
  5601    decNumber *allocbufb=NULL;       // -> allocated bufa, iff allocated
  5602    decNumber *b=bufb;               // adjustment/work
  5603  
  5604    decNumber  numone;               // constant 1
  5605    decNumber  cmp;                  // work
  5606    decContext aset, bset;           // working contexts
  5607  
  5608    #if DECCHECK
  5609    Int iterations=0;                // for later sanity check
  5610    if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
  5611    #endif
  5612  
  5613    do {                                  // protect allocated storage
  5614      if (SPECIALARG) {                   // handle infinities and NaNs
  5615        if (decNumberIsInfinite(rhs)) {   // an infinity
  5616          if (decNumberIsNegative(rhs))   // -Infinity -> error
  5617            *status|=DEC_Invalid_operation;
  5618           else decNumberCopy(res, rhs);  // +Infinity -> self
  5619          }
  5620         else decNaNs(res, rhs, NULL, set, status); // a NaN
  5621        break;}
  5622  
  5623      if (ISZERO(rhs)) {                  // +/- zeros -> -Infinity
  5624        decNumberZero(res);               // make clean
  5625        res->bits=DECINF|DECNEG;          // set - infinity
  5626        break;}                           // [no status to set]
  5627  
  5628      // Non-zero negatives are bad...
  5629      if (decNumberIsNegative(rhs)) {     // -x -> error
  5630        *status|=DEC_Invalid_operation;
  5631        break;}
  5632  
  5633      // Here, rhs is positive, finite, and in range
  5634  
  5635      // lookaside fastpath code for ln(2) and ln(10) at common lengths
  5636      if (rhs->exponent==0 && set->digits<=40) {
  5637        #if DECDPUN==1
  5638        if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)
  5639        #else
  5640        if (rhs->lsu[0]==10 && rhs->digits==2) {                  // ln(10)
  5641        #endif
  5642          aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5643          #define LN10 "2.302585092994045684017991454684364207601"
  5644          decNumberFromString(res, LN10, &aset);
  5645          *status|=(DEC_Inexact | DEC_Rounded); // is inexact
  5646          break;}
  5647        if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)
  5648          aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
  5649          #define LN2 "0.6931471805599453094172321214581765680755"
  5650          decNumberFromString(res, LN2, &aset);
  5651          *status|=(DEC_Inexact | DEC_Rounded);
  5652          break;}
  5653        } // integer and short
  5654  
  5655      // Determine the working precision.  This is normally the
  5656      // requested precision + 2, with a minimum of 9.  However, if
  5657      // the rhs is 'over-precise' then allow for all its digits to
  5658      // potentially participate (consider an rhs where all the excess
  5659      // digits are 9s) so in this case use rhs->digits+2.
  5660      p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
  5661  
  5662      // Allocate space for the accumulator and the high-precision
  5663      // adjustment calculator, if necessary.  The accumulator must
  5664      // be able to hold p digits, and the adjustment up to
  5665      // rhs->digits+p digits.  They are also made big enough for 16
  5666      // digits so that they can be used for calculating the initial
  5667      // estimate.
  5668      needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
  5669      if (needbytes>sizeof(bufa)) {     // need malloc space
  5670        allocbufa=(decNumber *)malloc(needbytes);
  5671        if (allocbufa==NULL) {          // hopeless -- abandon
  5672          *status|=DEC_Insufficient_storage;
  5673          break;}
  5674        a=allocbufa;                    // use the allocated space
  5675        }
  5676      pp=p+rhs->digits;
  5677      needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
  5678      if (needbytes>sizeof(bufb)) {     // need malloc space
  5679        allocbufb=(decNumber *)malloc(needbytes);
  5680        if (allocbufb==NULL) {          // hopeless -- abandon
  5681          *status|=DEC_Insufficient_storage;
  5682          break;}
  5683        b=allocbufb;                    // use the allocated space
  5684        }
  5685  
  5686      // Prepare an initial estimate in acc. Calculate this by
  5687      // considering the coefficient of x to be a normalized fraction,
  5688      // f, with the decimal point at far left and multiplied by
  5689      // 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and
  5690      //   ln(x) = ln(f) + ln(10)*r
  5691      // Get the initial estimate for ln(f) from a small lookup
  5692      // table (see above) indexed by the first two digits of f,
  5693      // truncated.
  5694  
  5695      decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended
  5696      r=rhs->exponent+rhs->digits;        // 'normalised' exponent
  5697      decNumberFromInt32(a, r);           // a=r
  5698      decNumberFromInt32(b, 2302585);     // b=ln(10) (2.302585)
  5699      b->exponent=-6;                     //  ..
  5700      decMultiplyOp(a, a, b, &aset, &ignore);  // a=a*b
  5701      // now get top two digits of rhs into b by simple truncate and
  5702      // force to integer
  5703      residue=0;                          // (no residue)
  5704      aset.digits=2; aset.round=DEC_ROUND_DOWN;
  5705      decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten
  5706      b->exponent=0;                      // make integer
  5707      t=decGetInt(b);                     // [cannot fail]
  5708      if (t<10) t=X10(t);                 // adjust single-digit b
  5709      t=LNnn[t-10];                       // look up ln(b)
  5710      decNumberFromInt32(b, t>>2);        // b=ln(b) coefficient
  5711      b->exponent=-(t&3)-3;               // set exponent
  5712      b->bits=DECNEG;                     // ln(0.10)->ln(0.99) always -ve
  5713      aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore
  5714      decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b
  5715      // the initial estimate is now in a, with up to 4 digits correct.
  5716      // When rhs is at or near Nmax the estimate will be low, so we
  5717      // will approach it from below, avoiding overflow when calling exp.
  5718  
  5719      decNumberZero(&numone); *numone.lsu=1;   // constant 1 for adjustment
  5720  
  5721      // accumulator bounds are as requested (could underflow, but
  5722      // cannot overflow)
  5723      aset.emax=set->emax;
  5724      aset.emin=set->emin;
  5725      aset.clamp=0;                       // no concrete format
  5726      // set up a context to be used for the multiply and subtract
  5727      bset=aset;
  5728      bset.emax=DEC_MAX_MATH*2;           // use double bounds for the
  5729      bset.emin=-DEC_MAX_MATH*2;          // adjustment calculation
  5730                                          // [see decExpOp call below]
  5731      // for each iteration double the number of digits to calculate,
  5732      // up to a maximum of p
  5733      pp=9;                               // initial precision
  5734      // [initially 9 as then the sequence starts 7+2, 16+2, and
  5735      // 34+2, which is ideal for standard-sized numbers]
  5736      aset.digits=pp;                     // working context
  5737      bset.digits=pp+rhs->digits;         // wider context
  5738      for (;;) {                          // iterate
  5739        #if DECCHECK
  5740        iterations++;
  5741        if (iterations>24) break;         // consider 9 * 2**24
  5742        #endif
  5743        // calculate the adjustment (exp(-a)*x-1) into b.  This is a
  5744        // catastrophic subtraction but it really is the difference
  5745        // from 1 that is of interest.
  5746        // Use the internal entry point to Exp as it allows the double
  5747        // range for calculating exp(-a) when a is the tiniest subnormal.
  5748        a->bits^=DECNEG;                  // make -a
  5749        decExpOp(b, a, &bset, &ignore);   // b=exp(-a)
  5750        a->bits^=DECNEG;                  // restore sign of a
  5751        // now multiply by rhs and subtract 1, at the wider precision
  5752        decMultiplyOp(b, b, rhs, &bset, &ignore);        // b=b*rhs
  5753        decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1
  5754  
  5755        // the iteration ends when the adjustment cannot affect the
  5756        // result by >=0.5 ulp (at the requested digits), which
  5757        // is when its value is smaller than the accumulator by
  5758        // set->digits+1 digits (or it is zero) -- this is a looser
  5759        // requirement than for Exp because all that happens to the
  5760        // accumulator after this is the final rounding (but note that
  5761        // there must also be full precision in a, or a=0).
  5762  
  5763        if (decNumberIsZero(b) ||
  5764            (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
  5765          if (a->digits==p) break;
  5766          if (decNumberIsZero(a)) {
  5767            decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?
  5768            if (cmp.lsu[0]==0) a->exponent=0;            // yes, exact 0
  5769             else *status|=(DEC_Inexact | DEC_Rounded);  // no, inexact
  5770            break;
  5771            }
  5772          // force padding if adjustment has gone to 0 before full length
  5773          if (decNumberIsZero(b)) b->exponent=a->exponent-p;
  5774          }
  5775  
  5776        // not done yet ...
  5777        decAddOp(a, a, b, &aset, 0, &ignore);  // a=a+b for next estimate
  5778        if (pp==p) continue;                   // precision is at maximum
  5779        // lengthen the next calculation
  5780        pp=pp*2;                               // double precision
  5781        if (pp>p) pp=p;                        // clamp to maximum
  5782        aset.digits=pp;                        // working context
  5783        bset.digits=pp+rhs->digits;            // wider context
  5784        } // Newton's iteration
  5785  
  5786      #if DECCHECK
  5787      // just a sanity check; remove the test to show always
  5788      if (iterations>24)
  5789        printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
  5790              (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
  5791      #endif
  5792  
  5793      // Copy and round the result to res
  5794      residue=1;                          // indicate dirt to right
  5795      if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
  5796      aset.digits=set->digits;            // [use default rounding]
  5797      decCopyFit(res, a, &aset, &residue, status); // copy & shorten
  5798      decFinish(res, set, &residue, status);       // cleanup/set flags
  5799      } while(0);                         // end protected
  5800  
  5801    if (allocbufa!=NULL) free(allocbufa); // drop any storage used
  5802    if (allocbufb!=NULL) free(allocbufb); // ..
  5803    // [status is handled by caller]
  5804    return res;
  5805    } // decLnOp
  5806  
  5807  /* ------------------------------------------------------------------ */
  5808  /* decQuantizeOp  -- force exponent to requested value                */
  5809  /*                                                                    */
  5810  /*   This computes C = op(A, B), where op adjusts the coefficient     */
  5811  /*   of C (by rounding or shifting) such that the exponent (-scale)   */
  5812  /*   of C has the value B or matches the exponent of B.               */
  5813  /*   The numerical value of C will equal A, except for the effects of */
  5814  /*   any rounding that occurred.                                      */
  5815  /*                                                                    */
  5816  /*   res is C, the result.  C may be A or B                           */
  5817  /*   lhs is A, the number to adjust                                   */
  5818  /*   rhs is B, the requested exponent                                 */
  5819  /*   set is the context                                               */
  5820  /*   quant is 1 for quantize or 0 for rescale                         */
  5821  /*   status is the status accumulator (this can be called without     */
  5822  /*          risk of control loss)                                     */
  5823  /*                                                                    */
  5824  /* C must have space for set->digits digits.                          */
  5825  /*                                                                    */
  5826  /* Unless there is an error or the result is infinite, the exponent   */
  5827  /* after the operation is guaranteed to be that requested.            */
  5828  /* ------------------------------------------------------------------ */
  5829  static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
  5830                                   const decNumber *rhs, decContext *set,
  5831                                   Flag quant, uInt *status) {
  5832    #if DECSUBSET
  5833    decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
  5834    decNumber *allocrhs=NULL;        // .., rhs
  5835    #endif
  5836    const decNumber *inrhs=rhs;      // save original rhs
  5837    Int   reqdigits=set->digits;     // requested DIGITS
  5838    Int   reqexp;                    // requested exponent [-scale]
  5839    Int   residue=0;                 // rounding residue
  5840    Int   etiny=set->emin-(reqdigits-1);
  5841  
  5842    #if DECCHECK
  5843    if (decCheckOperands(res, lhs, rhs, set)) return res;
  5844    #endif
  5845  
  5846    do {                             // protect allocated storage
  5847      #if DECSUBSET
  5848      if (!set->extended) {
  5849        // reduce operands and set lostDigits status, as needed
  5850        if (lhs->digits>reqdigits) {
  5851          alloclhs=decRoundOperand(lhs, set, status);
  5852          if (alloclhs==NULL) break;
  5853          lhs=alloclhs;
  5854          }
  5855        if (rhs->digits>reqdigits) { // [this only checks lostDigits]
  5856          allocrhs=decRoundOperand(rhs, set, status);
  5857          if (allocrhs==NULL) break;
  5858          rhs=allocrhs;
  5859          }
  5860        }
  5861      #endif
  5862      // [following code does not require input rounding]
  5863  
  5864      // Handle special values
  5865      if (SPECIALARGS) {
  5866        // NaNs get usual processing
  5867        if (SPECIALARGS & (DECSNAN | DECNAN))
  5868          decNaNs(res, lhs, rhs, set, status);
  5869        // one infinity but not both is bad
  5870        else if ((lhs->bits ^ rhs->bits) & DECINF)
  5871          *status|=DEC_Invalid_operation;
  5872        // both infinity: return lhs
  5873        else decNumberCopy(res, lhs);          // [nop if in place]
  5874        break;
  5875        }
  5876  
  5877      // set requested exponent
  5878      if (quant) reqexp=inrhs->exponent;  // quantize -- match exponents
  5879       else {                             // rescale -- use value of rhs
  5880        // Original rhs must be an integer that fits and is in range,
  5881        // which could be from -1999999997 to +999999999, thanks to
  5882        // subnormals
  5883        reqexp=decGetInt(inrhs);               // [cannot fail]
  5884        }
  5885  
  5886      #if DECSUBSET
  5887      if (!set->extended) etiny=set->emin;     // no subnormals
  5888      #endif
  5889  
  5890      if (reqexp==BADINT                       // bad (rescale only) or ..
  5891       || reqexp==BIGODD || reqexp==BIGEVEN    // very big (ditto) or ..
  5892       || (reqexp<etiny)                       // < lowest
  5893       || (reqexp>set->emax)) {                // > emax
  5894        *status|=DEC_Invalid_operation;
  5895        break;}
  5896  
  5897      // the RHS has been processed, so it can be overwritten now if necessary
  5898      if (ISZERO(lhs)) {                       // zero coefficient unchanged
  5899        decNumberCopy(res, lhs);               // [nop if in place]
  5900        res->exponent=reqexp;                  // .. just set exponent
  5901        #if DECSUBSET
  5902        if (!set->extended) res->bits=0;       // subset specification; no -0
  5903        #endif
  5904        }
  5905       else {                                  // non-zero lhs
  5906        Int adjust=reqexp-lhs->exponent;       // digit adjustment needed
  5907        // if adjusted coefficient will definitely not fit, give up now
  5908        if ((lhs->digits-adjust)>reqdigits) {
  5909          *status|=DEC_Invalid_operation;
  5910          break;
  5911          }
  5912  
  5913        if (adjust>0) {                        // increasing exponent
  5914          // this will decrease the length of the coefficient by adjust
  5915          // digits, and must round as it does so
  5916          decContext workset;                  // work
  5917          workset=*set;                        // clone rounding, etc.
  5918          workset.digits=lhs->digits-adjust;   // set requested length
  5919          // [note that the latter can be <1, here]
  5920          decCopyFit(res, lhs, &workset, &residue, status); // fit to result
  5921          decApplyRound(res, &workset, residue, status);    // .. and round
  5922          residue=0;                                        // [used]
  5923          // If just rounded a 999s case, exponent will be off by one;
  5924          // adjust back (after checking space), if so.
  5925          if (res->exponent>reqexp) {
  5926            // re-check needed, e.g., for quantize(0.9999, 0.001) under
  5927            // set->digits==3
  5928            if (res->digits==reqdigits) {      // cannot shift by 1
  5929              *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]
  5930              *status|=DEC_Invalid_operation;
  5931              break;
  5932              }
  5933            res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift
  5934            res->exponent--;                   // (re)adjust the exponent.
  5935            }
  5936          #if DECSUBSET
  5937          if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0
  5938          #endif
  5939          } // increase
  5940         else /* adjust<=0 */ {                // decreasing or = exponent
  5941          // this will increase the length of the coefficient by -adjust
  5942          // digits, by adding zero or more trailing zeros; this is
  5943          // already checked for fit, above
  5944          decNumberCopy(res, lhs);             // [it will fit]
  5945          // if padding needed (adjust<0), add it now...
  5946          if (adjust<0) {
  5947            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
  5948            res->exponent+=adjust;             // adjust the exponent
  5949            }
  5950          } // decrease
  5951        } // non-zero
  5952  
  5953      // Check for overflow [do not use Finalize in this case, as an
  5954      // overflow here is a "don't fit" situation]
  5955      if (res->exponent>set->emax-res->digits+1) {  // too big
  5956        *status|=DEC_Invalid_operation;
  5957        break;
  5958        }
  5959       else {
  5960        decFinalize(res, set, &residue, status);    // set subnormal flags
  5961        *status&=~DEC_Underflow;          // suppress Underflow [as per 754]
  5962        }
  5963      } while(0);                         // end protected
  5964  
  5965    #if DECSUBSET
  5966    if (allocrhs!=NULL) free(allocrhs);   // drop any storage used
  5967    if (alloclhs!=NULL) free(alloclhs);   // ..
  5968    #endif
  5969    return res;
  5970    } // decQuantizeOp
  5971  
  5972  /* ------------------------------------------------------------------ */
  5973  /* decCompareOp -- compare, min, or max two Numbers                   */
  5974  /*                                                                    */
  5975  /*   This computes C = A ? B and carries out one of four operations:  */
  5976  /*     COMPARE    -- returns the signum (as a number) giving the      */
  5977  /*                   result of a comparison unless one or both        */
  5978  /*                   operands is a NaN (in which case a NaN results)  */
  5979  /*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
  5980  /*                   Invalid operation.                               */
  5981  /*     COMPMAX    -- returns the larger of the operands, using the    */
  5982  /*                   754 maxnum operation                             */
  5983  /*     COMPMAXMAG -- ditto, comparing absolute values                 */
  5984  /*     COMPMIN    -- the 754 minnum operation                         */
  5985  /*     COMPMINMAG -- ditto, comparing absolute values                 */
  5986  /*     COMTOTAL   -- returns the signum (as a number) giving the      */
  5987  /*                   result of a comparison using 754 total ordering  */
  5988  /*                                                                    */
  5989  /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
  5990  /*   lhs is A                                                         */
  5991  /*   rhs is B                                                         */
  5992  /*   set is the context                                               */
  5993  /*   op  is the operation flag                                        */
  5994  /*   status is the usual accumulator                                  */
  5995  /*                                                                    */
  5996  /* C must have space for one digit for COMPARE or set->digits for     */
  5997  /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
  5998  /* ------------------------------------------------------------------ */
  5999  /* The emphasis here is on speed for common cases, and avoiding       */
  6000  /* coefficient comparison if possible.                                */
  6001  /* ------------------------------------------------------------------ */
  6002  decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
  6003                           const decNumber *rhs, decContext *set,
  6004                           Flag op, uInt *status) {
  6005    #if DECSUBSET
  6006    decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
  6007    decNumber *allocrhs=NULL;        // .., rhs
  6008    #endif
  6009    Int   result=0;                  // default result value
  6010    uByte merged;                    // work
  6011  
  6012    #if DECCHECK
  6013    if (decCheckOperands(res, lhs, rhs, set)) return res;
  6014    #endif
  6015  
  6016    do {                             // protect allocated storage
  6017      #if DECSUBSET
  6018      if (!set->extended) {
  6019        // reduce operands and set lostDigits status, as needed
  6020        if (lhs->digits>set->digits) {
  6021          alloclhs=decRoundOperand(lhs, set, status);
  6022          if (alloclhs==NULL) {result=BADINT; break;}
  6023          lhs=alloclhs;
  6024          }
  6025        if (rhs->digits>set->digits) {
  6026          allocrhs=decRoundOperand(rhs, set, status);
  6027          if (allocrhs==NULL) {result=BADINT; break;}
  6028          rhs=allocrhs;
  6029          }
  6030        }
  6031      #endif
  6032      // [following code does not require input rounding]
  6033  
  6034      // If total ordering then handle differing signs 'up front'
  6035      if (op==COMPTOTAL) {                // total ordering
  6036        if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
  6037          result=-1;
  6038          break;
  6039          }
  6040        if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
  6041          result=+1;
  6042          break;
  6043          }
  6044        }
  6045  
  6046      // handle NaNs specially; let infinities drop through
  6047      // This assumes sNaN (even just one) leads to NaN.
  6048      merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
  6049      if (merged) {                       // a NaN bit set
  6050        if (op==COMPARE);                 // result will be NaN
  6051         else if (op==COMPSIG)            // treat qNaN as sNaN
  6052          *status|=DEC_Invalid_operation | DEC_sNaN;
  6053         else if (op==COMPTOTAL) {        // total ordering, always finite
  6054          // signs are known to be the same; compute the ordering here
  6055          // as if the signs are both positive, then invert for negatives
  6056          if (!decNumberIsNaN(lhs)) result=-1;
  6057           else if (!decNumberIsNaN(rhs)) result=+1;
  6058           // here if both NaNs
  6059           else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
  6060           else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
  6061           else { // both NaN or both sNaN
  6062            // now it just depends on the payload
  6063            result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  6064                                  rhs->lsu, D2U(rhs->digits), 0);
  6065            // [Error not possible, as these are 'aligned']
  6066            } // both same NaNs
  6067          if (decNumberIsNegative(lhs)) result=-result;
  6068          break;
  6069          } // total order
  6070  
  6071         else if (merged & DECSNAN);           // sNaN -> qNaN
  6072         else { // here if MIN or MAX and one or two quiet NaNs
  6073          // min or max -- 754 rules ignore single NaN
  6074          if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
  6075            // just one NaN; force choice to be the non-NaN operand
  6076            op=COMPMAX;
  6077            if (lhs->bits & DECNAN) result=-1; // pick rhs
  6078                               else result=+1; // pick lhs
  6079            break;
  6080            }
  6081          } // max or min
  6082        op=COMPNAN;                            // use special path
  6083        decNaNs(res, lhs, rhs, set, status);   // propagate NaN
  6084        break;
  6085        }
  6086      // have numbers
  6087      if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
  6088       else result=decCompare(lhs, rhs, 0);    // sign matters
  6089      } while(0);                              // end protected
  6090  
  6091    if (result==BADINT) *status|=DEC_Insufficient_storage; // rare
  6092     else {
  6093      if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum
  6094        if (op==COMPTOTAL && result==0) {
  6095          // operands are numerically equal or same NaN (and same sign,
  6096          // tested first); if identical, leave result 0
  6097          if (lhs->exponent!=rhs->exponent) {
  6098            if (lhs->exponent<rhs->exponent) result=-1;
  6099             else result=+1;
  6100            if (decNumberIsNegative(lhs)) result=-result;
  6101            } // lexp!=rexp
  6102          } // total-order by exponent
  6103        decNumberZero(res);               // [always a valid result]
  6104        if (result!=0) {                  // must be -1 or +1
  6105          *res->lsu=1;
  6106          if (result<0) res->bits=DECNEG;
  6107          }
  6108        }
  6109       else if (op==COMPNAN);             // special, drop through
  6110       else {                             // MAX or MIN, non-NaN result
  6111        Int residue=0;                    // rounding accumulator
  6112        // choose the operand for the result
  6113        const decNumber *choice;
  6114        if (result==0) { // operands are numerically equal
  6115          // choose according to sign then exponent (see 754)
  6116          uByte slhs=(lhs->bits & DECNEG);
  6117          uByte srhs=(rhs->bits & DECNEG);
  6118          #if DECSUBSET
  6119          if (!set->extended) {           // subset: force left-hand
  6120            op=COMPMAX;
  6121            result=+1;
  6122            }
  6123          else
  6124          #endif
  6125          if (slhs!=srhs) {          // signs differ
  6126            if (slhs) result=-1;     // rhs is max
  6127                 else result=+1;     // lhs is max
  6128            }
  6129           else if (slhs && srhs) {  // both negative
  6130            if (lhs->exponent<rhs->exponent) result=+1;
  6131                                        else result=-1;
  6132            // [if equal, use lhs, technically identical]
  6133            }
  6134           else {                    // both positive
  6135            if (lhs->exponent>rhs->exponent) result=+1;
  6136                                        else result=-1;
  6137            // [ditto]
  6138            }
  6139          } // numerically equal
  6140        // here result will be non-0; reverse if looking for MIN
  6141        if (op==COMPMIN || op==COMPMINMAG) result=-result;
  6142        choice=(result>0 ? lhs : rhs);    // choose
  6143        // copy chosen to result, rounding if need be
  6144        decCopyFit(res, choice, set, &residue, status);
  6145        decFinish(res, set, &residue, status);
  6146        }
  6147      }
  6148    #if DECSUBSET
  6149    if (allocrhs!=NULL) free(allocrhs);   // free any storage used
  6150    if (alloclhs!=NULL) free(alloclhs);   // ..
  6151    #endif
  6152    return res;
  6153    } // decCompareOp
  6154  
  6155  /* ------------------------------------------------------------------ */
  6156  /* decCompare -- compare two decNumbers by numerical value            */
  6157  /*                                                                    */
  6158  /*  This routine compares A ? B without altering them.                */
  6159  /*                                                                    */
  6160  /*  Arg1 is A, a decNumber which is not a NaN                         */
  6161  /*  Arg2 is B, a decNumber which is not a NaN                         */
  6162  /*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
  6163  /*                                                                    */
  6164  /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
  6165  /*  (the only possible failure is an allocation error)                */
  6166  /* ------------------------------------------------------------------ */
  6167  static Int decCompare(const decNumber *lhs, const decNumber *rhs,
  6168                        Flag abs) {
  6169    Int   result;                    // result value
  6170    Int   sigr;                      // rhs signum
  6171    Int   compare;                   // work
  6172  
  6173    result=1;                                  // assume signum(lhs)
  6174    if (ISZERO(lhs)) result=0;
  6175    if (abs) {
  6176      if (ISZERO(rhs)) return result;          // LHS wins or both 0
  6177      // RHS is non-zero
  6178      if (result==0) return -1;                // LHS is 0; RHS wins
  6179      // [here, both non-zero, result=1]
  6180      }
  6181     else {                                    // signs matter
  6182      if (result && decNumberIsNegative(lhs)) result=-1;
  6183      sigr=1;                                  // compute signum(rhs)
  6184      if (ISZERO(rhs)) sigr=0;
  6185       else if (decNumberIsNegative(rhs)) sigr=-1;
  6186      if (result > sigr) return +1;            // L > R, return 1
  6187      if (result < sigr) return -1;            // L < R, return -1
  6188      if (result==0) return 0;                   // both 0
  6189      }
  6190  
  6191    // signums are the same; both are non-zero
  6192    if ((lhs->bits | rhs->bits) & DECINF) {    // one or more infinities
  6193      if (decNumberIsInfinite(rhs)) {
  6194        if (decNumberIsInfinite(lhs)) result=0;// both infinite
  6195         else result=-result;                  // only rhs infinite
  6196        }
  6197      return result;
  6198      }
  6199    // must compare the coefficients, allowing for exponents
  6200    if (lhs->exponent>rhs->exponent) {         // LHS exponent larger
  6201      // swap sides, and sign
  6202      const decNumber *temp=lhs;
  6203      lhs=rhs;
  6204      rhs=temp;
  6205      result=-result;
  6206      }
  6207    compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
  6208                           rhs->lsu, D2U(rhs->digits),
  6209                           rhs->exponent-lhs->exponent);
  6210    if (compare!=BADINT) compare*=result;      // comparison succeeded
  6211    return compare;
  6212    } // decCompare
  6213  
  6214  /* ------------------------------------------------------------------ */
  6215  /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
  6216  /*                                                                    */
  6217  /*  This routine compares A ? B*10**E where A and B are unit arrays   */
  6218  /*  A is a plain integer                                              */
  6219  /*  B has an exponent of E (which must be non-negative)               */
  6220  /*                                                                    */
  6221  /*  Arg1 is A first Unit (lsu)                                        */
  6222  /*  Arg2 is A length in Units                                         */
  6223  /*  Arg3 is B first Unit (lsu)                                        */
  6224  /*  Arg4 is B length in Units                                         */
  6225  /*  Arg5 is E (0 if the units are aligned)                            */
  6226  /*                                                                    */
  6227  /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
  6228  /*  (the only possible failure is an allocation error, which can      */
  6229  /*  only occur if E!=0)                                               */
  6230  /* ------------------------------------------------------------------ */
  6231  static Int decUnitCompare(const Unit *a, Int alength,
  6232                            const Unit *b, Int blength, Int exp) {
  6233    Unit  *acc;                      // accumulator for result
  6234    Unit  accbuff[SD2U(DECBUFFER*2+1)]; // local buffer
  6235    Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
  6236    Int   accunits, need;            // units in use or needed for acc
  6237    const Unit *l, *r, *u;           // work
  6238    Int   expunits, exprem, result;  // ..
  6239  
  6240    if (exp==0) {                    // aligned; fastpath
  6241      if (alength>blength) return 1;
  6242      if (alength<blength) return -1;
  6243      // same number of units in both -- need unit-by-unit compare
  6244      l=a+alength-1;
  6245      r=b+alength-1;
  6246      for (;l>=a; l--, r--) {
  6247        if (*l>*r) return 1;
  6248        if (*l<*r) return -1;
  6249        }
  6250      return 0;                      // all units match
  6251      } // aligned
  6252  
  6253    // Unaligned.  If one is >1 unit longer than the other, padded
  6254    // approximately, then can return easily
  6255    if (alength>blength+(Int)D2U(exp)) return 1;
  6256    if (alength+1<blength+(Int)D2U(exp)) return -1;
  6257  
  6258    // Need to do a real subtract.  For this, a result buffer is needed
  6259    // even though only the sign is of interest.  Its length needs
  6260    // to be the larger of alength and padded blength, +2
  6261    need=blength+D2U(exp);                // maximum real length of B
  6262    if (need<alength) need=alength;
  6263    need+=2;
  6264    acc=accbuff;                          // assume use local buffer
  6265    if (need*sizeof(Unit)>sizeof(accbuff)) {
  6266      allocacc=(Unit *)malloc(need*sizeof(Unit));
  6267      if (allocacc==NULL) return BADINT;  // hopeless -- abandon
  6268      acc=allocacc;
  6269      }
  6270    // Calculate units and remainder from exponent.
  6271    expunits=exp/DECDPUN;
  6272    exprem=exp%DECDPUN;
  6273    // subtract [A+B*(-m)]
  6274    accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
  6275                           -(Int)powers[exprem]);
  6276    // [UnitAddSub result may have leading zeros, even on zero]
  6277    if (accunits<0) result=-1;            // negative result
  6278     else {                               // non-negative result
  6279      // check units of the result before freeing any storage
  6280      for (u=acc; u<acc+accunits-1 && *u==0;) u++;
  6281      result=(*u==0 ? 0 : +1);
  6282      }
  6283    // clean up and return the result
  6284    if (allocacc!=NULL) free(allocacc);   // drop any storage used
  6285    return result;
  6286    } // decUnitCompare
  6287  
  6288  /* ------------------------------------------------------------------ */
  6289  /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
  6290  /*                                                                    */
  6291  /*  This routine performs the calculation:                            */
  6292  /*                                                                    */
  6293  /*  C=A+(B*M)                                                         */
  6294  /*                                                                    */
  6295  /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
  6296  /*                                                                    */
  6297  /*  A may be shorter or longer than B.                                */
  6298  /*                                                                    */
  6299  /*  Leading zeros are not removed after a calculation.  The result is */
  6300  /*  either the same length as the longer of A and B (adding any       */
  6301  /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
  6302  /*                                                                    */
  6303  /*  A and B content are not altered unless C is also A or B.          */
  6304  /*  C may be the same array as A or B, but only if no zero padding is */
  6305  /*  requested (that is, C may be B only if bshift==0).                */
  6306  /*  C is filled from the lsu; only those units necessary to complete  */
  6307  /*  the calculation are referenced.                                   */
  6308  /*                                                                    */
  6309  /*  Arg1 is A first Unit (lsu)                                        */
  6310  /*  Arg2 is A length in Units                                         */
  6311  /*  Arg3 is B first Unit (lsu)                                        */
  6312  /*  Arg4 is B length in Units                                         */
  6313  /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
  6314  /*  Arg6 is C first Unit (lsu)                                        */
  6315  /*  Arg7 is M, the multiplier                                         */
  6316  /*                                                                    */
  6317  /*  returns the count of Units written to C, which will be non-zero   */
  6318  /*  and negated if the result is negative.  That is, the sign of the  */
  6319  /*  returned Int is the sign of the result (positive for zero) and    */
  6320  /*  the absolute value of the Int is the count of Units.              */
  6321  /*                                                                    */
  6322  /*  It is the caller's responsibility to make sure that C size is     */
  6323  /*  safe, allowing space if necessary for a one-Unit carry.           */
  6324  /*                                                                    */
  6325  /*  This routine is severely performance-critical; *any* change here  */
  6326  /*  must be measured (timed) to assure no performance degradation.    */
  6327  /*  In particular, trickery here tends to be counter-productive, as   */
  6328  /*  increased complexity of code hurts register optimizations on      */
  6329  /*  register-poor architectures.  Avoiding divisions is nearly        */
  6330  /*  always a Good Idea, however.                                      */
  6331  /*                                                                    */
  6332  /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
  6333  /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
  6334  /* ------------------------------------------------------------------ */
  6335  static Int decUnitAddSub(const Unit *a, Int alength,
  6336                           const Unit *b, Int blength, Int bshift,
  6337                           Unit *c, Int m) {
  6338    const Unit *alsu=a;              // A lsu [need to remember it]
  6339    Unit *clsu=c;                    // C ditto
  6340    Unit *minC;                      // low water mark for C
  6341    Unit *maxC;                      // high water mark for C
  6342    eInt carry=0;                    // carry integer (could be Long)
  6343    Int  add;                        // work
  6344    #if DECDPUN<=4                   // myriadal, millenary, etc.
  6345    Int  est;                        // estimated quotient
  6346    #endif
  6347  
  6348    #if DECTRACE
  6349    if (alength<1 || blength<1)
  6350      printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
  6351    #endif
  6352  
  6353    maxC=c+alength;                  // A is usually the longer
  6354    minC=c+blength;                  // .. and B the shorter
  6355    if (bshift!=0) {                 // B is shifted; low As copy across
  6356      minC+=bshift;
  6357      // if in place [common], skip copy unless there's a gap [rare]
  6358      if (a==c && bshift<=alength) {
  6359        c+=bshift;
  6360        a+=bshift;
  6361        }
  6362       else for (; c<clsu+bshift; a++, c++) {  // copy needed
  6363        if (a<alsu+alength) *c=*a;
  6364         else *c=0;
  6365        }
  6366      }
  6367    if (minC>maxC) { // swap
  6368      Unit *hold=minC;
  6369      minC=maxC;
  6370      maxC=hold;
  6371      }
  6372  
  6373    // For speed, do the addition as two loops; the first where both A
  6374    // and B contribute, and the second (if necessary) where only one or
  6375    // other of the numbers contribute.
  6376    // Carry handling is the same (i.e., duplicated) in each case.
  6377    for (; c<minC; c++) {
  6378      carry+=*a;
  6379      a++;
  6380      carry+=((eInt)*b)*m;                // [special-casing m=1/-1
  6381      b++;                                // here is not a win]
  6382      // here carry is new Unit of digits; it could be +ve or -ve
  6383      if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
  6384        *c=(Unit)carry;
  6385        carry=0;
  6386        continue;
  6387        }
  6388      #if DECDPUN==4                           // use divide-by-multiply
  6389        if (carry>=0) {
  6390          est=(((ueInt)carry>>11)*53687)>>18;
  6391          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6392          carry=est;                           // likely quotient [89%]
  6393          if (*c<DECDPUNMAX+1) continue;       // estimate was correct
  6394          carry++;
  6395          *c-=DECDPUNMAX+1;
  6396          continue;
  6397          }
  6398        // negative case
  6399        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6400        est=(((ueInt)carry>>11)*53687)>>18;
  6401        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6402        carry=est-(DECDPUNMAX+1);              // correctly negative
  6403        if (*c<DECDPUNMAX+1) continue;         // was OK
  6404        carry++;
  6405        *c-=DECDPUNMAX+1;
  6406      #elif DECDPUN==3
  6407        if (carry>=0) {
  6408          est=(((ueInt)carry>>3)*16777)>>21;
  6409          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6410          carry=est;                           // likely quotient [99%]
  6411          if (*c<DECDPUNMAX+1) continue;       // estimate was correct
  6412          carry++;
  6413          *c-=DECDPUNMAX+1;
  6414          continue;
  6415          }
  6416        // negative case
  6417        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6418        est=(((ueInt)carry>>3)*16777)>>21;
  6419        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6420        carry=est-(DECDPUNMAX+1);              // correctly negative
  6421        if (*c<DECDPUNMAX+1) continue;         // was OK
  6422        carry++;
  6423        *c-=DECDPUNMAX+1;
  6424      #elif DECDPUN<=2
  6425        // Can use QUOT10 as carry <= 4 digits
  6426        if (carry>=0) {
  6427          est=QUOT10(carry, DECDPUN);
  6428          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6429          carry=est;                           // quotient
  6430          continue;
  6431          }
  6432        // negative case
  6433        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6434        est=QUOT10(carry, DECDPUN);
  6435        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6436        carry=est-(DECDPUNMAX+1);              // correctly negative
  6437      #else
  6438        // remainder operator is undefined if negative, so must test
  6439        if ((ueInt)carry<(DECDPUNMAX+1)*2) {   // fastpath carry +1
  6440          *c=(Unit)(carry-(DECDPUNMAX+1));     // [helps additions]
  6441          carry=1;
  6442          continue;
  6443          }
  6444        if (carry>=0) {
  6445          *c=(Unit)(carry%(DECDPUNMAX+1));
  6446          carry=carry/(DECDPUNMAX+1);
  6447          continue;
  6448          }
  6449        // negative case
  6450        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6451        *c=(Unit)(carry%(DECDPUNMAX+1));
  6452        carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6453      #endif
  6454      } // c
  6455  
  6456    // now may have one or other to complete
  6457    // [pretest to avoid loop setup/shutdown]
  6458    if (c<maxC) for (; c<maxC; c++) {
  6459      if (a<alsu+alength) {               // still in A
  6460        carry+=*a;
  6461        a++;
  6462        }
  6463       else {                             // inside B
  6464        carry+=((eInt)*b)*m;
  6465        b++;
  6466        }
  6467      // here carry is new Unit of digits; it could be +ve or -ve and
  6468      // magnitude up to DECDPUNMAX squared
  6469      if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
  6470        *c=(Unit)carry;
  6471        carry=0;
  6472        continue;
  6473        }
  6474      // result for this unit is negative or >DECDPUNMAX
  6475      #if DECDPUN==4                           // use divide-by-multiply
  6476        if (carry>=0) {
  6477          est=(((ueInt)carry>>11)*53687)>>18;
  6478          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6479          carry=est;                           // likely quotient [79.7%]
  6480          if (*c<DECDPUNMAX+1) continue;       // estimate was correct
  6481          carry++;
  6482          *c-=DECDPUNMAX+1;
  6483          continue;
  6484          }
  6485        // negative case
  6486        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6487        est=(((ueInt)carry>>11)*53687)>>18;
  6488        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6489        carry=est-(DECDPUNMAX+1);              // correctly negative
  6490        if (*c<DECDPUNMAX+1) continue;         // was OK
  6491        carry++;
  6492        *c-=DECDPUNMAX+1;
  6493      #elif DECDPUN==3
  6494        if (carry>=0) {
  6495          est=(((ueInt)carry>>3)*16777)>>21;
  6496          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6497          carry=est;                           // likely quotient [99%]
  6498          if (*c<DECDPUNMAX+1) continue;       // estimate was correct
  6499          carry++;
  6500          *c-=DECDPUNMAX+1;
  6501          continue;
  6502          }
  6503        // negative case
  6504        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6505        est=(((ueInt)carry>>3)*16777)>>21;
  6506        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6507        carry=est-(DECDPUNMAX+1);              // correctly negative
  6508        if (*c<DECDPUNMAX+1) continue;         // was OK
  6509        carry++;
  6510        *c-=DECDPUNMAX+1;
  6511      #elif DECDPUN<=2
  6512        if (carry>=0) {
  6513          est=QUOT10(carry, DECDPUN);
  6514          *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
  6515          carry=est;                           // quotient
  6516          continue;
  6517          }
  6518        // negative case
  6519        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6520        est=QUOT10(carry, DECDPUN);
  6521        *c=(Unit)(carry-est*(DECDPUNMAX+1));
  6522        carry=est-(DECDPUNMAX+1);              // correctly negative
  6523      #else
  6524        if ((ueInt)carry<(DECDPUNMAX+1)*2){    // fastpath carry 1
  6525          *c=(Unit)(carry-(DECDPUNMAX+1));
  6526          carry=1;
  6527          continue;
  6528          }
  6529        // remainder operator is undefined if negative, so must test
  6530        if (carry>=0) {
  6531          *c=(Unit)(carry%(DECDPUNMAX+1));
  6532          carry=carry/(DECDPUNMAX+1);
  6533          continue;
  6534          }
  6535        // negative case
  6536        carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
  6537        *c=(Unit)(carry%(DECDPUNMAX+1));
  6538        carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
  6539      #endif
  6540      } // c
  6541  
  6542    // OK, all A and B processed; might still have carry or borrow
  6543    // return number of Units in the result, negated if a borrow
  6544    if (carry==0) return c-clsu;     // no carry, so no more to do
  6545    if (carry>0) {                   // positive carry
  6546      *c=(Unit)carry;                // place as new unit
  6547      c++;                           // ..
  6548      return c-clsu;
  6549      }
  6550    // -ve carry: it's a borrow; complement needed
  6551    add=1;                           // temporary carry...
  6552    for (c=clsu; c<maxC; c++) {
  6553      add=DECDPUNMAX+add-*c;
  6554      if (add<=DECDPUNMAX) {
  6555        *c=(Unit)add;
  6556        add=0;
  6557        }
  6558       else {
  6559        *c=0;
  6560        add=1;
  6561        }
  6562      }
  6563    // add an extra unit iff it would be non-zero
  6564    #if DECTRACE
  6565      printf("UAS borrow: add %ld, carry %ld\n", add, carry);
  6566    #endif
  6567    if ((add-carry-1)!=0) {
  6568      *c=(Unit)(add-carry-1);
  6569      c++;                      // interesting, include it
  6570      }
  6571    return clsu-c;              // -ve result indicates borrowed
  6572    } // decUnitAddSub
  6573  
  6574  /* ------------------------------------------------------------------ */
  6575  /* decTrim -- trim trailing zeros or normalize                        */
  6576  /*                                                                    */
  6577  /*   dn is the number to trim or normalize                            */
  6578  /*   set is the context to use to check for clamp                     */
  6579  /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
  6580  /*   noclamp is 1 to unconditional (unclamped) trim                   */
  6581  /*   dropped returns the number of discarded trailing zeros           */
  6582  /*   returns dn                                                       */
  6583  /*                                                                    */
  6584  /* If clamp is set in the context then the number of zeros trimmed    */
  6585  /* may be limited if the exponent is high.                            */
  6586  /* All fields are updated as required.  This is a utility operation,  */
  6587  /* so special values are unchanged and no error is possible.          */
  6588  /* ------------------------------------------------------------------ */
  6589  static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
  6590                             Flag noclamp, Int *dropped) {
  6591    Int   d, exp;                    // work
  6592    uInt  cut;                       // ..
  6593    Unit  *up;                       // -> current Unit
  6594  
  6595    #if DECCHECK
  6596    if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
  6597    #endif
  6598  
  6599    *dropped=0;                           // assume no zeros dropped
  6600    if ((dn->bits & DECSPECIAL)           // fast exit if special ..
  6601      || (*dn->lsu & 0x01)) return dn;    // .. or odd
  6602    if (ISZERO(dn)) {                     // .. or 0
  6603      dn->exponent=0;                     // (sign is preserved)
  6604      return dn;
  6605      }
  6606  
  6607    // have a finite number which is even
  6608    exp=dn->exponent;
  6609    cut=1;                           // digit (1-DECDPUN) in Unit
  6610    up=dn->lsu;                      // -> current Unit
  6611    for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]
  6612      // slice by powers
  6613      #if DECDPUN<=4
  6614        uInt quot=QUOT10(*up, cut);
  6615        if ((*up-quot*powers[cut])!=0) break;  // found non-0 digit
  6616      #else
  6617        if (*up%powers[cut]!=0) break;         // found non-0 digit
  6618      #endif
  6619      // have a trailing 0
  6620      if (!all) {                    // trimming
  6621        // [if exp>0 then all trailing 0s are significant for trim]
  6622        if (exp<=0) {                // if digit might be significant
  6623          if (exp==0) break;         // then quit
  6624          exp++;                     // next digit might be significant
  6625          }
  6626        }
  6627      cut++;                         // next power
  6628      if (cut>DECDPUN) {             // need new Unit
  6629        up++;
  6630        cut=1;
  6631        }
  6632      } // d
  6633    if (d==0) return dn;             // none to drop
  6634  
  6635    // may need to limit drop if clamping
  6636    if (set->clamp && !noclamp) {
  6637      Int maxd=set->emax-set->digits+1-dn->exponent;
  6638      if (maxd<=0) return dn;        // nothing possible
  6639      if (d>maxd) d=maxd;
  6640      }
  6641  
  6642    // effect the drop
  6643    decShiftToLeast(dn->lsu, D2U(dn->digits), d);
  6644    dn->exponent+=d;                 // maintain numerical value
  6645    dn->digits-=d;                   // new length
  6646    *dropped=d;                      // report the count
  6647    return dn;
  6648    } // decTrim
  6649  
  6650  /* ------------------------------------------------------------------ */
  6651  /* decReverse -- reverse a Unit array in place                        */
  6652  /*                                                                    */
  6653  /*   ulo    is the start of the array                                 */
  6654  /*   uhi    is the end of the array (highest Unit to include)         */
  6655  /*                                                                    */
  6656  /* The units ulo through uhi are reversed in place (if the number     */
  6657  /* of units is odd, the middle one is untouched).  Note that the      */
  6658  /* digit(s) in each unit are unaffected.                              */
  6659  /* ------------------------------------------------------------------ */
  6660  static void decReverse(Unit *ulo, Unit *uhi) {
  6661    Unit temp;
  6662    for (; ulo<uhi; ulo++, uhi--) {
  6663      temp=*ulo;
  6664      *ulo=*uhi;
  6665      *uhi=temp;
  6666      }
  6667    return;
  6668    } // decReverse
  6669  
  6670  /* ------------------------------------------------------------------ */
  6671  /* decShiftToMost -- shift digits in array towards most significant   */
  6672  /*                                                                    */
  6673  /*   uar    is the array                                              */
  6674  /*   digits is the count of digits in use in the array                */
  6675  /*   shift  is the number of zeros to pad with (least significant);   */
  6676  /*     it must be zero or positive                                    */
  6677  /*                                                                    */
  6678  /*   returns the new length of the integer in the array, in digits    */
  6679  /*                                                                    */
  6680  /* No overflow is permitted (that is, the uar array must be known to  */
  6681  /* be large enough to hold the result, after shifting).               */
  6682  /* ------------------------------------------------------------------ */
  6683  static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
  6684    Unit  *target, *source, *first;  // work
  6685    Int   cut;                       // odd 0's to add
  6686    uInt  next;                      // work
  6687  
  6688    if (shift==0) return digits;     // [fastpath] nothing to do
  6689    if ((digits+shift)<=DECDPUN) {   // [fastpath] single-unit case
  6690      *uar=(Unit)(*uar*powers[shift]);
  6691      return digits+shift;
  6692      }
  6693  
  6694    next=0;                          // all paths
  6695    source=uar+D2U(digits)-1;        // where msu comes from
  6696    target=source+D2U(shift);        // where upper part of first cut goes
  6697    cut=DECDPUN-MSUDIGITS(shift);    // where to slice
  6698    if (cut==0) {                    // unit-boundary case
  6699      for (; source>=uar; source--, target--) *target=*source;
  6700      }
  6701     else {
  6702      first=uar+D2U(digits+shift)-1; // where msu of source will end up
  6703      for (; source>=uar; source--, target--) {
  6704        // split the source Unit and accumulate remainder for next
  6705        #if DECDPUN<=4
  6706          uInt quot=QUOT10(*source, cut);
  6707          uInt rem=*source-quot*powers[cut];
  6708          next+=quot;
  6709        #else
  6710          uInt rem=*source%powers[cut];
  6711          next+=*source/powers[cut];
  6712        #endif
  6713        if (target<=first) *target=(Unit)next;   // write to target iff valid
  6714        next=rem*powers[DECDPUN-cut];            // save remainder for next Unit
  6715        }
  6716      } // shift-move
  6717  
  6718    // propagate any partial unit to one below and clear the rest
  6719    for (; target>=uar; target--) {
  6720      *target=(Unit)next;
  6721      next=0;
  6722      }
  6723    return digits+shift;
  6724    } // decShiftToMost
  6725  
  6726  /* ------------------------------------------------------------------ */
  6727  /* decShiftToLeast -- shift digits in array towards least significant */
  6728  /*                                                                    */
  6729  /*   uar   is the array                                               */
  6730  /*   units is length of the array, in units                           */
  6731  /*   shift is the number of digits to remove from the lsu end; it     */
  6732  /*     must be zero or positive and <= than units*DECDPUN.            */
  6733  /*                                                                    */
  6734  /*   returns the new length of the integer in the array, in units     */
  6735  /*                                                                    */
  6736  /* Removed digits are discarded (lost).  Units not required to hold   */
  6737  /* the final result are unchanged.                                    */
  6738  /* ------------------------------------------------------------------ */
  6739  static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
  6740    Unit  *target, *up;              // work
  6741    Int   cut, count;                // work
  6742    Int   quot, rem;                 // for division
  6743  
  6744    if (shift==0) return units;      // [fastpath] nothing to do
  6745    if (shift==units*DECDPUN) {      // [fastpath] little to do
  6746      *uar=0;                        // all digits cleared gives zero
  6747      return 1;                      // leaves just the one
  6748      }
  6749  
  6750    target=uar;                      // both paths
  6751    cut=MSUDIGITS(shift);
  6752    if (cut==DECDPUN) {              // unit-boundary case; easy
  6753      up=uar+D2U(shift);
  6754      for (; up<uar+units; target++, up++) *target=*up;
  6755      return target-uar;
  6756      }
  6757  
  6758    // messier
  6759    up=uar+D2U(shift-cut);           // source; correct to whole Units
  6760    count=units*DECDPUN-shift;       // the maximum new length
  6761    #if DECDPUN<=4
  6762      quot=QUOT10(*up, cut);
  6763    #else
  6764      quot=*up/powers[cut];
  6765    #endif
  6766    for (; ; target++) {
  6767      *target=(Unit)quot;
  6768      count-=(DECDPUN-cut);
  6769      if (count<=0) break;
  6770      up++;
  6771      quot=*up;
  6772      #if DECDPUN<=4
  6773        quot=QUOT10(quot, cut);
  6774        rem=*up-quot*powers[cut];
  6775      #else
  6776        rem=quot%powers[cut];
  6777        quot=quot/powers[cut];
  6778      #endif
  6779      *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  6780      count-=cut;
  6781      if (count<=0) break;
  6782      }
  6783    return target-uar+1;
  6784    } // decShiftToLeast
  6785  
  6786  #if DECSUBSET
  6787  /* ------------------------------------------------------------------ */
  6788  /* decRoundOperand -- round an operand  [used for subset only]        */
  6789  /*                                                                    */
  6790  /*   dn is the number to round (dn->digits is > set->digits)          */
  6791  /*   set is the relevant context                                      */
  6792  /*   status is the status accumulator                                 */
  6793  /*                                                                    */
  6794  /*   returns an allocated decNumber with the rounded result.          */
  6795  /*                                                                    */
  6796  /* lostDigits and other status may be set by this.                    */
  6797  /*                                                                    */
  6798  /* Since the input is an operand, it must not be modified.            */
  6799  /* Instead, return an allocated decNumber, rounded as required.       */
  6800  /* It is the caller's responsibility to free the allocated storage.   */
  6801  /*                                                                    */
  6802  /* If no storage is available then the result cannot be used, so NULL */
  6803  /* is returned.                                                       */
  6804  /* ------------------------------------------------------------------ */
  6805  static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
  6806                                    uInt *status) {
  6807    decNumber *res;                       // result structure
  6808    uInt newstatus=0;                     // status from round
  6809    Int  residue=0;                       // rounding accumulator
  6810  
  6811    // Allocate storage for the returned decNumber, big enough for the
  6812    // length specified by the context
  6813    res=(decNumber *)malloc(sizeof(decNumber)
  6814                            +(D2U(set->digits)-1)*sizeof(Unit));
  6815    if (res==NULL) {
  6816      *status|=DEC_Insufficient_storage;
  6817      return NULL;
  6818      }
  6819    decCopyFit(res, dn, set, &residue, &newstatus);
  6820    decApplyRound(res, set, residue, &newstatus);
  6821  
  6822    // If that set Inexact then "lost digits" is raised...
  6823    if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
  6824    *status|=newstatus;
  6825    return res;
  6826    } // decRoundOperand
  6827  #endif
  6828  
  6829  /* ------------------------------------------------------------------ */
  6830  /* decCopyFit -- copy a number, truncating the coefficient if needed  */
  6831  /*                                                                    */
  6832  /*   dest is the target decNumber                                     */
  6833  /*   src  is the source decNumber                                     */
  6834  /*   set is the context [used for length (digits) and rounding mode]  */
  6835  /*   residue is the residue accumulator                               */
  6836  /*   status contains the current status to be updated                 */
  6837  /*                                                                    */
  6838  /* (dest==src is allowed and will be a no-op if fits)                 */
  6839  /* All fields are updated as required.                                */
  6840  /* ------------------------------------------------------------------ */
  6841  static void decCopyFit(decNumber *dest, const decNumber *src,
  6842                         decContext *set, Int *residue, uInt *status) {
  6843    dest->bits=src->bits;
  6844    dest->exponent=src->exponent;
  6845    decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
  6846    } // decCopyFit
  6847  
  6848  /* ------------------------------------------------------------------ */
  6849  /* decSetCoeff -- set the coefficient of a number                     */
  6850  /*                                                                    */
  6851  /*   dn    is the number whose coefficient array is to be set.        */
  6852  /*         It must have space for set->digits digits                  */
  6853  /*   set   is the context [for size]                                  */
  6854  /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
  6855  /*   len   is digits in the source coefficient [may be dn->digits]    */
  6856  /*   residue is the residue accumulator.  This has values as in       */
  6857  /*         decApplyRound, and will be unchanged unless the            */
  6858  /*         target size is less than len.  In this case, the           */
  6859  /*         coefficient is truncated and the residue is updated to     */
  6860  /*         reflect the previous residue and the dropped digits.       */
  6861  /*   status is the status accumulator, as usual                       */
  6862  /*                                                                    */
  6863  /* The coefficient may already be in the number, or it can be an      */
  6864  /* external intermediate array.  If it is in the number, lsu must ==  */
  6865  /* dn->lsu and len must == dn->digits.                                */
  6866  /*                                                                    */
  6867  /* Note that the coefficient length (len) may be < set->digits, and   */
  6868  /* in this case this merely copies the coefficient (or is a no-op     */
  6869  /* if dn->lsu==lsu).                                                  */
  6870  /*                                                                    */
  6871  /* Note also that (only internally, from decQuantizeOp and            */
  6872  /* decSetSubnormal) the value of set->digits may be less than one,    */
  6873  /* indicating a round to left.  This routine handles that case        */
  6874  /* correctly; caller ensures space.                                   */
  6875  /*                                                                    */
  6876  /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
  6877  /* updated as necessary.   dn->bits (sign) is unchanged.              */
  6878  /*                                                                    */
  6879  /* DEC_Rounded status is set if any digits are discarded.             */
  6880  /* DEC_Inexact status is set if any non-zero digits are discarded, or */
  6881  /*                       incoming residue was non-0 (implies rounded) */
  6882  /* ------------------------------------------------------------------ */
  6883  // mapping array: maps 0-9 to canonical residues, so that a residue
  6884  // can be adjusted in the range [-1, +1] and achieve correct rounding
  6885  //                             0  1  2  3  4  5  6  7  8  9
  6886  static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
  6887  static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
  6888                          Int len, Int *residue, uInt *status) {
  6889    Int   discard;              // number of digits to discard
  6890    uInt  cut;                  // cut point in Unit
  6891    const Unit *up;             // work
  6892    Unit  *target;              // ..
  6893    Int   count;                // ..
  6894    #if DECDPUN<=4
  6895    uInt  temp;                 // ..
  6896    #endif
  6897  
  6898    discard=len-set->digits;    // digits to discard
  6899    if (discard<=0) {           // no digits are being discarded
  6900      if (dn->lsu!=lsu) {       // copy needed
  6901        // copy the coefficient array to the result number; no shift needed
  6902        count=len;              // avoids D2U
  6903        up=lsu;
  6904        for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6905          *target=*up;
  6906        dn->digits=len;         // set the new length
  6907        }
  6908      // dn->exponent and residue are unchanged, record any inexactitude
  6909      if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
  6910      return;
  6911      }
  6912  
  6913    // some digits must be discarded ...
  6914    dn->exponent+=discard;      // maintain numerical value
  6915    *status|=DEC_Rounded;       // accumulate Rounded status
  6916    if (*residue>1) *residue=1; // previous residue now to right, so reduce
  6917  
  6918    if (discard>len) {          // everything, +1, is being discarded
  6919      // guard digit is 0
  6920      // residue is all the number [NB could be all 0s]
  6921      if (*residue<=0) {        // not already positive
  6922        count=len;              // avoids D2U
  6923        for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0
  6924          *residue=1;
  6925          break;                // no need to check any others
  6926          }
  6927        }
  6928      if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
  6929      *dn->lsu=0;               // coefficient will now be 0
  6930      dn->digits=1;             // ..
  6931      return;
  6932      } // total discard
  6933  
  6934    // partial discard [most common case]
  6935    // here, at least the first (most significant) discarded digit exists
  6936  
  6937    // spin up the number, noting residue during the spin, until get to
  6938    // the Unit with the first discarded digit.  When reach it, extract
  6939    // it and remember its position
  6940    count=0;
  6941    for (up=lsu;; up++) {
  6942      count+=DECDPUN;
  6943      if (count>=discard) break; // full ones all checked
  6944      if (*up!=0) *residue=1;
  6945      } // up
  6946  
  6947    // here up -> Unit with first discarded digit
  6948    cut=discard-(count-DECDPUN)-1;
  6949    if (cut==DECDPUN-1) {       // unit-boundary case (fast)
  6950      Unit half=(Unit)powers[DECDPUN]>>1;
  6951      // set residue directly
  6952      if (*up>=half) {
  6953        if (*up>half) *residue=7;
  6954        else *residue+=5;       // add sticky bit
  6955        }
  6956       else { // <half
  6957        if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]
  6958        }
  6959      if (set->digits<=0) {     // special for Quantize/Subnormal :-(
  6960        *dn->lsu=0;             // .. result is 0
  6961        dn->digits=1;           // ..
  6962        }
  6963       else {                   // shift to least
  6964        count=set->digits;      // now digits to end up with
  6965        dn->digits=count;       // set the new length
  6966        up++;                   // move to next
  6967        // on unit boundary, so shift-down copy loop is simple
  6968        for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
  6969          *target=*up;
  6970        }
  6971      } // unit-boundary case
  6972  
  6973     else { // discard digit is in low digit(s), and not top digit
  6974      uInt  discard1;                // first discarded digit
  6975      uInt  quot, rem;               // for divisions
  6976      if (cut==0) quot=*up;          // is at bottom of unit
  6977       else /* cut>0 */ {            // it's not at bottom of unit
  6978        #if DECDPUN<=4
  6979          quot=QUOT10(*up, cut);
  6980          rem=*up-quot*powers[cut];
  6981        #else
  6982          rem=*up%powers[cut];
  6983          quot=*up/powers[cut];
  6984        #endif
  6985        if (rem!=0) *residue=1;
  6986        }
  6987      // discard digit is now at bottom of quot
  6988      #if DECDPUN<=4
  6989        temp=(quot*6554)>>16;        // fast /10
  6990        // Vowels algorithm here not a win (9 instructions)
  6991        discard1=quot-X10(temp);
  6992        quot=temp;
  6993      #else
  6994        discard1=quot%10;
  6995        quot=quot/10;
  6996      #endif
  6997      // here, discard1 is the guard digit, and residue is everything
  6998      // else [use mapping array to accumulate residue safely]
  6999      *residue+=resmap[discard1];
  7000      cut++;                         // update cut
  7001      // here: up -> Unit of the array with bottom digit
  7002      //       cut is the division point for each Unit
  7003      //       quot holds the uncut high-order digits for the current unit
  7004      if (set->digits<=0) {          // special for Quantize/Subnormal :-(
  7005        *dn->lsu=0;                  // .. result is 0
  7006        dn->digits=1;                // ..
  7007        }
  7008       else {                        // shift to least needed
  7009        count=set->digits;           // now digits to end up with
  7010        dn->digits=count;            // set the new length
  7011        // shift-copy the coefficient array to the result number
  7012        for (target=dn->lsu; ; target++) {
  7013          *target=(Unit)quot;
  7014          count-=(DECDPUN-cut);
  7015          if (count<=0) break;
  7016          up++;
  7017          quot=*up;
  7018          #if DECDPUN<=4
  7019            quot=QUOT10(quot, cut);
  7020            rem=*up-quot*powers[cut];
  7021          #else
  7022            rem=quot%powers[cut];
  7023            quot=quot/powers[cut];
  7024          #endif
  7025          *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
  7026          count-=cut;
  7027          if (count<=0) break;
  7028          } // shift-copy loop
  7029        } // shift to least
  7030      } // not unit boundary
  7031  
  7032    if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
  7033    return;
  7034    } // decSetCoeff
  7035  
  7036  /* ------------------------------------------------------------------ */
  7037  /* decApplyRound -- apply pending rounding to a number                */
  7038  /*                                                                    */
  7039  /*   dn    is the number, with space for set->digits digits           */
  7040  /*   set   is the context [for size and rounding mode]                */
  7041  /*   residue indicates pending rounding, being any accumulated        */
  7042  /*         guard and sticky information.  It may be:                  */
  7043  /*         6-9: rounding digit is >5                                  */
  7044  /*         5:   rounding digit is exactly half-way                    */
  7045  /*         1-4: rounding digit is <5 and >0                           */
  7046  /*         0:   the coefficient is exact                              */
  7047  /*        -1:   as 1, but the hidden digits are subtractive, that     */
  7048  /*              is, of the opposite sign to dn.  In this case the     */
  7049  /*              coefficient must be non-0.  This case occurs when     */
  7050  /*              subtracting a small number (which can be reduced to   */
  7051  /*              a sticky bit); see decAddOp.                          */
  7052  /*   status is the status accumulator, as usual                       */
  7053  /*                                                                    */
  7054  /* This routine applies rounding while keeping the length of the      */
  7055  /* coefficient constant.  The exponent and status are unchanged       */
  7056  /* except if:                                                         */
  7057  /*                                                                    */
  7058  /*   -- the coefficient was increased and is all nines (in which      */
  7059  /*      case Overflow could occur, and is handled directly here so    */
  7060  /*      the caller does not need to re-test for overflow)             */
  7061  /*                                                                    */
  7062  /*   -- the coefficient was decreased and becomes all nines (in which */
  7063  /*      case Underflow could occur, and is also handled directly).    */
  7064  /*                                                                    */
  7065  /* All fields in dn are updated as required.                          */
  7066  /*                                                                    */
  7067  /* ------------------------------------------------------------------ */
  7068  static void decApplyRound(decNumber *dn, decContext *set, Int residue,
  7069                            uInt *status) {
  7070    Int  bump;                  // 1 if coefficient needs to be incremented
  7071                                // -1 if coefficient needs to be decremented
  7072  
  7073    if (residue==0) return;     // nothing to apply
  7074  
  7075    bump=0;                     // assume a smooth ride
  7076  
  7077    // now decide whether, and how, to round, depending on mode
  7078    switch (set->round) {
  7079      case DEC_ROUND_05UP: {    // round zero or five up (for reround)
  7080        // This is the same as DEC_ROUND_DOWN unless there is a
  7081        // positive residue and the lsd of dn is 0 or 5, in which case
  7082        // it is bumped; when residue is <0, the number is therefore
  7083        // bumped down unless the final digit was 1 or 6 (in which
  7084        // case it is bumped down and then up -- a no-op)
  7085        Int lsd5=*dn->lsu%5;     // get lsd and quintate
  7086        if (residue<0 && lsd5!=1) bump=-1;
  7087         else if (residue>0 && lsd5==0) bump=1;
  7088        // [bump==1 could be applied directly; use common path for clarity]
  7089        break;} // r-05
  7090  
  7091      case DEC_ROUND_DOWN: {
  7092        // no change, except if negative residue
  7093        if (residue<0) bump=-1;
  7094        break;} // r-d
  7095  
  7096      case DEC_ROUND_HALF_DOWN: {
  7097        if (residue>5) bump=1;
  7098        break;} // r-h-d
  7099  
  7100      case DEC_ROUND_HALF_EVEN: {
  7101        if (residue>5) bump=1;            // >0.5 goes up
  7102         else if (residue==5) {           // exactly 0.5000...
  7103          // 0.5 goes up iff [new] lsd is odd
  7104          if (*dn->lsu & 0x01) bump=1;
  7105          }
  7106        break;} // r-h-e
  7107  
  7108      case DEC_ROUND_HALF_UP: {
  7109        if (residue>=5) bump=1;
  7110        break;} // r-h-u
  7111  
  7112      case DEC_ROUND_UP: {
  7113        if (residue>0) bump=1;
  7114        break;} // r-u
  7115  
  7116      case DEC_ROUND_CEILING: {
  7117        // same as _UP for positive numbers, and as _DOWN for negatives
  7118        // [negative residue cannot occur on 0]
  7119        if (decNumberIsNegative(dn)) {
  7120          if (residue<0) bump=-1;
  7121          }
  7122         else {
  7123          if (residue>0) bump=1;
  7124          }
  7125        break;} // r-c
  7126  
  7127      case DEC_ROUND_FLOOR: {
  7128        // same as _UP for negative numbers, and as _DOWN for positive
  7129        // [negative residue cannot occur on 0]
  7130        if (!decNumberIsNegative(dn)) {
  7131          if (residue<0) bump=-1;
  7132          }
  7133         else {
  7134          if (residue>0) bump=1;
  7135          }
  7136        break;} // r-f
  7137  
  7138      default: {      // e.g., DEC_ROUND_MAX
  7139        *status|=DEC_Invalid_context;
  7140        #if DECTRACE || (DECCHECK && DECVERB)
  7141        printf("Unknown rounding mode: %d\n", set->round);
  7142        #endif
  7143        break;}
  7144      } // switch
  7145  
  7146    // now bump the number, up or down, if need be
  7147    if (bump==0) return;                       // no action required
  7148  
  7149    // Simply use decUnitAddSub unless bumping up and the number is
  7150    // all nines.  In this special case set to 100... explicitly
  7151    // and adjust the exponent by one (as otherwise could overflow
  7152    // the array)
  7153    // Similarly handle all-nines result if bumping down.
  7154    if (bump>0) {
  7155      Unit *up;                                // work
  7156      uInt count=dn->digits;                   // digits to be checked
  7157      for (up=dn->lsu; ; up++) {
  7158        if (count<=DECDPUN) {
  7159          // this is the last Unit (the msu)
  7160          if (*up!=powers[count]-1) break;     // not still 9s
  7161          // here if it, too, is all nines
  7162          *up=(Unit)powers[count-1];           // here 999 -> 100 etc.
  7163          for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0
  7164          dn->exponent++;                      // and bump exponent
  7165          // [which, very rarely, could cause Overflow...]
  7166          if ((dn->exponent+dn->digits)>set->emax+1) {
  7167            decSetOverflow(dn, set, status);
  7168            }
  7169          return;                              // done
  7170          }
  7171        // a full unit to check, with more to come
  7172        if (*up!=DECDPUNMAX) break;            // not still 9s
  7173        count-=DECDPUN;
  7174        } // up
  7175      } // bump>0
  7176     else {                                    // -1
  7177      // here checking for a pre-bump of 1000... (leading 1, all
  7178      // other digits zero)
  7179      Unit *up, *sup;                          // work
  7180      uInt count=dn->digits;                   // digits to be checked
  7181      for (up=dn->lsu; ; up++) {
  7182        if (count<=DECDPUN) {
  7183          // this is the last Unit (the msu)
  7184          if (*up!=powers[count-1]) break;     // not 100..
  7185          // here if have the 1000... case
  7186          sup=up;                              // save msu pointer
  7187          *up=(Unit)powers[count]-1;           // here 100 in msu -> 999
  7188          // others all to all-nines, too
  7189          for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
  7190          dn->exponent--;                      // and bump exponent
  7191  
  7192          // iff the number was at the subnormal boundary (exponent=etiny)
  7193          // then the exponent is now out of range, so it will in fact get
  7194          // clamped to etiny and the final 9 dropped.
  7195          // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,
  7196          //        dn->exponent, set->digits);
  7197          if (dn->exponent+1==set->emin-set->digits+1) {
  7198            if (count==1 && dn->digits==1) *sup=0;  // here 9 -> 0[.9]
  7199             else {
  7200              *sup=(Unit)powers[count-1]-1;    // here 999.. in msu -> 99..
  7201              dn->digits--;
  7202              }
  7203            dn->exponent++;
  7204            *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  7205            }
  7206          return;                              // done
  7207          }
  7208  
  7209        // a full unit to check, with more to come
  7210        if (*up!=0) break;                     // not still 0s
  7211        count-=DECDPUN;
  7212        } // up
  7213  
  7214      } // bump<0
  7215  
  7216    // Actual bump needed.  Do it.
  7217    decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
  7218    } // decApplyRound
  7219  
  7220  #if DECSUBSET
  7221  /* ------------------------------------------------------------------ */
  7222  /* decFinish -- finish processing a number                            */
  7223  /*                                                                    */
  7224  /*   dn is the number                                                 */
  7225  /*   set is the context                                               */
  7226  /*   residue is the rounding accumulator (as in decApplyRound)        */
  7227  /*   status is the accumulator                                        */
  7228  /*                                                                    */
  7229  /* This finishes off the current number by:                           */
  7230  /*    1. If not extended:                                             */
  7231  /*       a. Converting a zero result to clean '0'                     */
  7232  /*       b. Reducing positive exponents to 0, if would fit in digits  */
  7233  /*    2. Checking for overflow and subnormals (always)                */
  7234  /* Note this is just Finalize when no subset arithmetic.              */
  7235  /* All fields are updated as required.                                */
  7236  /* ------------------------------------------------------------------ */
  7237  static void decFinish(decNumber *dn, decContext *set, Int *residue,
  7238                        uInt *status) {
  7239    if (!set->extended) {
  7240      if ISZERO(dn) {                // value is zero
  7241        dn->exponent=0;              // clean exponent ..
  7242        dn->bits=0;                  // .. and sign
  7243        return;                      // no error possible
  7244        }
  7245      if (dn->exponent>=0) {         // non-negative exponent
  7246        // >0; reduce to integer if possible
  7247        if (set->digits >= (dn->exponent+dn->digits)) {
  7248          dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
  7249          dn->exponent=0;
  7250          }
  7251        }
  7252      } // !extended
  7253  
  7254    decFinalize(dn, set, residue, status);
  7255    } // decFinish
  7256  #endif
  7257  
  7258  /* ------------------------------------------------------------------ */
  7259  /* decFinalize -- final check, clamp, and round of a number           */
  7260  /*                                                                    */
  7261  /*   dn is the number                                                 */
  7262  /*   set is the context                                               */
  7263  /*   residue is the rounding accumulator (as in decApplyRound)        */
  7264  /*   status is the status accumulator                                 */
  7265  /*                                                                    */
  7266  /* This finishes off the current number by checking for subnormal     */
  7267  /* results, applying any pending rounding, checking for overflow,     */
  7268  /* and applying any clamping.                                         */
  7269  /* Underflow and overflow conditions are raised as appropriate.       */
  7270  /* All fields are updated as required.                                */
  7271  /* ------------------------------------------------------------------ */
  7272  static void decFinalize(decNumber *dn, decContext *set, Int *residue,
  7273                          uInt *status) {
  7274    Int shift;                            // shift needed if clamping
  7275    Int tinyexp=set->emin-dn->digits+1;   // precalculate subnormal boundary
  7276  
  7277    // Must be careful, here, when checking the exponent as the
  7278    // adjusted exponent could overflow 31 bits [because it may already
  7279    // be up to twice the expected].
  7280  
  7281    // First test for subnormal.  This must be done before any final
  7282    // round as the result could be rounded to Nmin or 0.
  7283    if (dn->exponent<=tinyexp) {          // prefilter
  7284      Int comp;
  7285      decNumber nmin;
  7286      // A very nasty case here is dn == Nmin and residue<0
  7287      if (dn->exponent<tinyexp) {
  7288        // Go handle subnormals; this will apply round if needed.
  7289        decSetSubnormal(dn, set, residue, status);
  7290        return;
  7291        }
  7292      // Equals case: only subnormal if dn=Nmin and negative residue
  7293      decNumberZero(&nmin);
  7294      nmin.lsu[0]=1;
  7295      nmin.exponent=set->emin;
  7296      comp=decCompare(dn, &nmin, 1);                // (signless compare)
  7297      if (comp==BADINT) {                           // oops
  7298        *status|=DEC_Insufficient_storage;          // abandon...
  7299        return;
  7300        }
  7301      if (*residue<0 && comp==0) {                  // neg residue and dn==Nmin
  7302        decApplyRound(dn, set, *residue, status);   // might force down
  7303        decSetSubnormal(dn, set, residue, status);
  7304        return;
  7305        }
  7306      }
  7307  
  7308    // now apply any pending round (this could raise overflow).
  7309    if (*residue!=0) decApplyRound(dn, set, *residue, status);
  7310  
  7311    // Check for overflow [redundant in the 'rare' case] or clamp
  7312    if (dn->exponent<=set->emax-set->digits+1) return;   // neither needed
  7313  
  7314  
  7315    // here when might have an overflow or clamp to do
  7316    if (dn->exponent>set->emax-dn->digits+1) {           // too big
  7317      decSetOverflow(dn, set, status);
  7318      return;
  7319      }
  7320    // here when the result is normal but in clamp range
  7321    if (!set->clamp) return;
  7322  
  7323    // here when need to apply the IEEE exponent clamp (fold-down)
  7324    shift=dn->exponent-(set->emax-set->digits+1);
  7325  
  7326    // shift coefficient (if non-zero)
  7327    if (!ISZERO(dn)) {
  7328      dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
  7329      }
  7330    dn->exponent-=shift;   // adjust the exponent to match
  7331    *status|=DEC_Clamped;  // and record the dirty deed
  7332    return;
  7333    } // decFinalize
  7334  
  7335  /* ------------------------------------------------------------------ */
  7336  /* decSetOverflow -- set number to proper overflow value              */
  7337  /*                                                                    */
  7338  /*   dn is the number (used for sign [only] and result)               */
  7339  /*   set is the context [used for the rounding mode, etc.]            */
  7340  /*   status contains the current status to be updated                 */
  7341  /*                                                                    */
  7342  /* This sets the sign of a number and sets its value to either        */
  7343  /* Infinity or the maximum finite value, depending on the sign of     */
  7344  /* dn and the rounding mode, following IEEE 754 rules.                */
  7345  /* ------------------------------------------------------------------ */
  7346  static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
  7347    Flag needmax=0;                  // result is maximum finite value
  7348    uByte sign=dn->bits&DECNEG;      // clean and save sign bit
  7349  
  7350    if (ISZERO(dn)) {                // zero does not overflow magnitude
  7351      Int emax=set->emax;                      // limit value
  7352      if (set->clamp) emax-=set->digits-1;     // lower if clamping
  7353      if (dn->exponent>emax) {                 // clamp required
  7354        dn->exponent=emax;
  7355        *status|=DEC_Clamped;
  7356        }
  7357      return;
  7358      }
  7359  
  7360    decNumberZero(dn);
  7361    switch (set->round) {
  7362      case DEC_ROUND_DOWN: {
  7363        needmax=1;                   // never Infinity
  7364        break;} // r-d
  7365      case DEC_ROUND_05UP: {
  7366        needmax=1;                   // never Infinity
  7367        break;} // r-05
  7368      case DEC_ROUND_CEILING: {
  7369        if (sign) needmax=1;         // Infinity if non-negative
  7370        break;} // r-c
  7371      case DEC_ROUND_FLOOR: {
  7372        if (!sign) needmax=1;        // Infinity if negative
  7373        break;} // r-f
  7374      default: break;                // Infinity in all other cases
  7375      }
  7376    if (needmax) {
  7377      decSetMaxValue(dn, set);
  7378      dn->bits=sign;                 // set sign
  7379      }
  7380     else dn->bits=sign|DECINF;      // Value is +/-Infinity
  7381    *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
  7382    } // decSetOverflow
  7383  
  7384  /* ------------------------------------------------------------------ */
  7385  /* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
  7386  /*                                                                    */
  7387  /*   dn is the number to set                                          */
  7388  /*   set is the context [used for digits and emax]                    */
  7389  /*                                                                    */
  7390  /* This sets the number to the maximum positive value.                */
  7391  /* ------------------------------------------------------------------ */
  7392  static void decSetMaxValue(decNumber *dn, decContext *set) {
  7393    Unit *up;                        // work
  7394    Int count=set->digits;           // nines to add
  7395    dn->digits=count;
  7396    // fill in all nines to set maximum value
  7397    for (up=dn->lsu; ; up++) {
  7398      if (count>DECDPUN) *up=DECDPUNMAX;  // unit full o'nines
  7399       else {                             // this is the msu
  7400        *up=(Unit)(powers[count]-1);
  7401        break;
  7402        }
  7403      count-=DECDPUN;                // filled those digits
  7404      } // up
  7405    dn->bits=0;                      // + sign
  7406    dn->exponent=set->emax-set->digits+1;
  7407    } // decSetMaxValue
  7408  
  7409  /* ------------------------------------------------------------------ */
  7410  /* decSetSubnormal -- process value whose exponent is <Emin           */
  7411  /*                                                                    */
  7412  /*   dn is the number (used as input as well as output; it may have   */
  7413  /*         an allowed subnormal value, which may need to be rounded)  */
  7414  /*   set is the context [used for the rounding mode]                  */
  7415  /*   residue is any pending residue                                   */
  7416  /*   status contains the current status to be updated                 */
  7417  /*                                                                    */
  7418  /* If subset mode, set result to zero and set Underflow flags.        */
  7419  /*                                                                    */
  7420  /* Value may be zero with a low exponent; this does not set Subnormal */
  7421  /* but the exponent will be clamped to Etiny.                         */
  7422  /*                                                                    */
  7423  /* Otherwise ensure exponent is not out of range, and round as        */
  7424  /* necessary.  Underflow is set if the result is Inexact.             */
  7425  /* ------------------------------------------------------------------ */
  7426  static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
  7427                              uInt *status) {
  7428    decContext workset;         // work
  7429    Int        etiny, adjust;   // ..
  7430  
  7431    #if DECSUBSET
  7432    // simple set to zero and 'hard underflow' for subset
  7433    if (!set->extended) {
  7434      decNumberZero(dn);
  7435      // always full overflow
  7436      *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
  7437      return;
  7438      }
  7439    #endif
  7440  
  7441    // Full arithmetic -- allow subnormals, rounded to minimum exponent
  7442    // (Etiny) if needed
  7443    etiny=set->emin-(set->digits-1);      // smallest allowed exponent
  7444  
  7445    if ISZERO(dn) {                       // value is zero
  7446      // residue can never be non-zero here
  7447      #if DECCHECK
  7448        if (*residue!=0) {
  7449          printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
  7450          *status|=DEC_Invalid_operation;
  7451          }
  7452      #endif
  7453      if (dn->exponent<etiny) {           // clamp required
  7454        dn->exponent=etiny;
  7455        *status|=DEC_Clamped;
  7456        }
  7457      return;
  7458      }
  7459  
  7460    *status|=DEC_Subnormal;               // have a non-zero subnormal
  7461    adjust=etiny-dn->exponent;            // calculate digits to remove
  7462    if (adjust<=0) {                      // not out of range; unrounded
  7463      // residue can never be non-zero here, except in the Nmin-residue
  7464      // case (which is a subnormal result), so can take fast-path here
  7465      // it may already be inexact (from setting the coefficient)
  7466      if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7467      return;
  7468      }
  7469  
  7470    // adjust>0, so need to rescale the result so exponent becomes Etiny
  7471    // [this code is similar to that in rescale]
  7472    workset=*set;                         // clone rounding, etc.
  7473    workset.digits=dn->digits-adjust;     // set requested length
  7474    workset.emin-=adjust;                 // and adjust emin to match
  7475    // [note that the latter can be <1, here, similar to Rescale case]
  7476    decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
  7477    decApplyRound(dn, &workset, *residue, status);
  7478  
  7479    // Use 754 default rule: Underflow is set iff Inexact
  7480    // [independent of whether trapped]
  7481    if (*status&DEC_Inexact) *status|=DEC_Underflow;
  7482  
  7483    // if rounded up a 999s case, exponent will be off by one; adjust
  7484    // back if so [it will fit, because it was shortened earlier]
  7485    if (dn->exponent>etiny) {
  7486      dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
  7487      dn->exponent--;                     // (re)adjust the exponent.
  7488      }
  7489  
  7490    // if rounded to zero, it is by definition clamped...
  7491    if (ISZERO(dn)) *status|=DEC_Clamped;
  7492    } // decSetSubnormal
  7493  
  7494  /* ------------------------------------------------------------------ */
  7495  /* decCheckMath - check entry conditions for a math function          */
  7496  /*                                                                    */
  7497  /*   This checks the context and the operand                          */
  7498  /*                                                                    */
  7499  /*   rhs is the operand to check                                      */
  7500  /*   set is the context to check                                      */
  7501  /*   status is unchanged if both are good                             */
  7502  /*                                                                    */
  7503  /* returns non-zero if status is changed, 0 otherwise                 */
  7504  /*                                                                    */
  7505  /* Restrictions enforced:                                             */
  7506  /*                                                                    */
  7507  /*   digits, emax, and -emin in the context must be less than         */
  7508  /*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
  7509  /*   non-zero.  Invalid_operation is set in the status if a           */
  7510  /*   restriction is violated.                                         */
  7511  /* ------------------------------------------------------------------ */
  7512  static uInt decCheckMath(const decNumber *rhs, decContext *set,
  7513                           uInt *status) {
  7514    uInt save=*status;                         // record
  7515    if (set->digits>DEC_MAX_MATH
  7516     || set->emax>DEC_MAX_MATH
  7517     || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
  7518     else if ((rhs->digits>DEC_MAX_MATH
  7519       || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
  7520       || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
  7521       && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
  7522    return (*status!=save);
  7523    } // decCheckMath
  7524  
  7525  /* ------------------------------------------------------------------ */
  7526  /* decGetInt -- get integer from a number                             */
  7527  /*                                                                    */
  7528  /*   dn is the number [which will not be altered]                     */
  7529  /*                                                                    */
  7530  /*   returns one of:                                                  */
  7531  /*     BADINT if there is a non-zero fraction                         */
  7532  /*     the converted integer                                          */
  7533  /*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
  7534  /*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
  7535  /*                                                                    */
  7536  /* This checks and gets a whole number from the input decNumber.      */
  7537  /* The sign can be determined from dn by the caller when BIGEVEN or   */
  7538  /* BIGODD is returned.                                                */
  7539  /* ------------------------------------------------------------------ */
  7540  static Int decGetInt(const decNumber *dn) {
  7541    Int  theInt;                          // result accumulator
  7542    const Unit *up;                       // work
  7543    Int  got;                             // digits (real or not) processed
  7544    Int  ilength=dn->digits+dn->exponent; // integral length
  7545    Flag neg=decNumberIsNegative(dn);     // 1 if -ve
  7546  
  7547    // The number must be an integer that fits in 10 digits
  7548    // Assert, here, that 10 is enough for any rescale Etiny
  7549    #if DEC_MAX_EMAX > 999999999
  7550      #error GetInt may need updating [for Emax]
  7551    #endif
  7552    #if DEC_MIN_EMIN < -999999999
  7553      #error GetInt may need updating [for Emin]
  7554    #endif
  7555    if (ISZERO(dn)) return 0;             // zeros are OK, with any exponent
  7556  
  7557    up=dn->lsu;                           // ready for lsu
  7558    theInt=0;                             // ready to accumulate
  7559    if (dn->exponent>=0) {                // relatively easy
  7560      // no fractional part [usual]; allow for positive exponent
  7561      got=dn->exponent;
  7562      }
  7563     else { // -ve exponent; some fractional part to check and discard
  7564      Int count=-dn->exponent;            // digits to discard
  7565      // spin up whole units until reach the Unit with the unit digit
  7566      for (; count>=DECDPUN; up++) {
  7567        if (*up!=0) return BADINT;        // non-zero Unit to discard
  7568        count-=DECDPUN;
  7569        }
  7570      if (count==0) got=0;                // [a multiple of DECDPUN]
  7571       else {                             // [not multiple of DECDPUN]
  7572        Int rem;                          // work
  7573        // slice off fraction digits and check for non-zero
  7574        #if DECDPUN<=4
  7575          theInt=QUOT10(*up, count);
  7576          rem=*up-theInt*powers[count];
  7577        #else
  7578          rem=*up%powers[count];          // slice off discards
  7579          theInt=*up/powers[count];
  7580        #endif
  7581        if (rem!=0) return BADINT;        // non-zero fraction
  7582        // it looks good
  7583        got=DECDPUN-count;                // number of digits so far
  7584        up++;                             // ready for next
  7585        }
  7586      }
  7587    // now it's known there's no fractional part
  7588  
  7589    // tricky code now, to accumulate up to 9.3 digits
  7590    if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there
  7591  
  7592    if (ilength<11) {
  7593      Int save=theInt;
  7594      // collect any remaining unit(s)
  7595      for (; got<ilength; up++) {
  7596        theInt+=*up*powers[got];
  7597        got+=DECDPUN;
  7598        }
  7599      if (ilength==10) {                  // need to check for wrap
  7600        if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
  7601           // [that test also disallows the BADINT result case]
  7602         else if (neg && theInt>1999999997) ilength=11;
  7603         else if (!neg && theInt>999999999) ilength=11;
  7604        if (ilength==11) theInt=save;     // restore correct low bit
  7605        }
  7606      }
  7607  
  7608    if (ilength>10) {                     // too big
  7609      if (theInt&1) return BIGODD;        // bottom bit 1
  7610      return BIGEVEN;                     // bottom bit 0
  7611      }
  7612  
  7613    if (neg) theInt=-theInt;              // apply sign
  7614    return theInt;
  7615    } // decGetInt
  7616  
  7617  /* ------------------------------------------------------------------ */
  7618  /* decDecap -- decapitate the coefficient of a number                 */
  7619  /*                                                                    */
  7620  /*   dn   is the number to be decapitated                             */
  7621  /*   drop is the number of digits to be removed from the left of dn;  */
  7622  /*     this must be <= dn->digits (if equal, the coefficient is       */
  7623  /*     set to 0)                                                      */
  7624  /*                                                                    */
  7625  /* Returns dn; dn->digits will be <= the initial digits less drop     */
  7626  /* (after removing drop digits there may be leading zero digits       */
  7627  /* which will also be removed).  Only dn->lsu and dn->digits change.  */
  7628  /* ------------------------------------------------------------------ */
  7629  static decNumber *decDecap(decNumber *dn, Int drop) {
  7630    Unit *msu;                            // -> target cut point
  7631    Int cut;                              // work
  7632    if (drop>=dn->digits) {               // losing the whole thing
  7633      #if DECCHECK
  7634      if (drop>dn->digits)
  7635        printf("decDecap called with drop>digits [%ld>%ld]\n",
  7636               (LI)drop, (LI)dn->digits);
  7637      #endif
  7638      dn->lsu[0]=0;
  7639      dn->digits=1;
  7640      return dn;
  7641      }
  7642    msu=dn->lsu+D2U(dn->digits-drop)-1;   // -> likely msu
  7643    cut=MSUDIGITS(dn->digits-drop);       // digits to be in use in msu
  7644    if (cut!=DECDPUN) *msu%=powers[cut];  // clear left digits
  7645    // that may have left leading zero digits, so do a proper count...
  7646    dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
  7647    return dn;
  7648    } // decDecap
  7649  
  7650  /* ------------------------------------------------------------------ */
  7651  /* decBiStr -- compare string with pairwise options                   */
  7652  /*                                                                    */
  7653  /*   targ is the string to compare                                    */
  7654  /*   str1 is one of the strings to compare against (length may be 0)  */
  7655  /*   str2 is the other; it must be the same length as str1            */
  7656  /*                                                                    */
  7657  /*   returns 1 if strings compare equal, (that is, it is the same     */
  7658  /*   length as str1 and str2, and each character of targ is in either */
  7659  /*   str1 or str2 in the corresponding position), or 0 otherwise      */
  7660  /*                                                                    */
  7661  /* This is used for generic caseless compare, including the awkward   */
  7662  /* case of the Turkish dotted and dotless Is.  Use as (for example):  */
  7663  /*   if (decBiStr(test, "mike", "MIKE")) ...                          */
  7664  /* ------------------------------------------------------------------ */
  7665  static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
  7666    for (;;targ++, str1++, str2++) {
  7667      if (*targ!=*str1 && *targ!=*str2) return 0;
  7668      // *targ has a match in one (or both, if terminator)
  7669      if (*targ=='\0') break;
  7670      } // forever
  7671    return 1;
  7672    } // decBiStr
  7673  
  7674  /* ------------------------------------------------------------------ */
  7675  /* decNaNs -- handle NaN operand or operands                          */
  7676  /*                                                                    */
  7677  /*   res     is the result number                                     */
  7678  /*   lhs     is the first operand                                     */
  7679  /*   rhs     is the second operand, or NULL if none                   */
  7680  /*   context is used to limit payload length                          */
  7681  /*   status  contains the current status                              */
  7682  /*   returns res in case convenient                                   */
  7683  /*                                                                    */
  7684  /* Called when one or both operands is a NaN, and propagates the      */
  7685  /* appropriate result to res.  When an sNaN is found, it is changed   */
  7686  /* to a qNaN and Invalid operation is set.                            */
  7687  /* ------------------------------------------------------------------ */
  7688  static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
  7689                             const decNumber *rhs, decContext *set,
  7690                             uInt *status) {
  7691    // This decision tree ends up with LHS being the source pointer,
  7692    // and status updated if need be
  7693    if (lhs->bits & DECSNAN)
  7694      *status|=DEC_Invalid_operation | DEC_sNaN;
  7695     else if (rhs==NULL);
  7696     else if (rhs->bits & DECSNAN) {
  7697      lhs=rhs;
  7698      *status|=DEC_Invalid_operation | DEC_sNaN;
  7699      }
  7700     else if (lhs->bits & DECNAN);
  7701     else lhs=rhs;
  7702  
  7703    // propagate the payload
  7704    if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy
  7705     else { // too long
  7706      const Unit *ul;
  7707      Unit *ur, *uresp1;
  7708      // copy safe number of units, then decapitate
  7709      res->bits=lhs->bits;                // need sign etc.
  7710      uresp1=res->lsu+D2U(set->digits);
  7711      for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
  7712      res->digits=D2U(set->digits)*DECDPUN;
  7713      // maybe still too long
  7714      if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
  7715      }
  7716  
  7717    res->bits&=~DECSNAN;        // convert any sNaN to NaN, while
  7718    res->bits|=DECNAN;          // .. preserving sign
  7719    res->exponent=0;            // clean exponent
  7720                                // [coefficient was copied/decapitated]
  7721    return res;
  7722    } // decNaNs
  7723  
  7724  /* ------------------------------------------------------------------ */
  7725  /* decStatus -- apply non-zero status                                 */
  7726  /*                                                                    */
  7727  /*   dn     is the number to set if error                             */
  7728  /*   status contains the current status (not yet in context)          */
  7729  /*   set    is the context                                            */
  7730  /*                                                                    */
  7731  /* If the status is an error status, the number is set to a NaN,      */
  7732  /* unless the error was an overflow, divide-by-zero, or underflow,    */
  7733  /* in which case the number will have already been set.               */
  7734  /*                                                                    */
  7735  /* The context status is then updated with the new status.  Note that */
  7736  /* this may raise a signal, so control may never return from this     */
  7737  /* routine (hence resources must be recovered before it is called).   */
  7738  /* ------------------------------------------------------------------ */
  7739  static void decStatus(decNumber *dn, uInt status, decContext *set) {
  7740    if (status & DEC_NaNs) {              // error status -> NaN
  7741      // if cause was an sNaN, clear and propagate [NaN is already set up]
  7742      if (status & DEC_sNaN) status&=~DEC_sNaN;
  7743       else {
  7744        decNumberZero(dn);                // other error: clean throughout
  7745        dn->bits=DECNAN;                  // and make a quiet NaN
  7746        }
  7747      }
  7748    decContextSetStatus(set, status);     // [may not return]
  7749    return;
  7750    } // decStatus
  7751  
  7752  /* ------------------------------------------------------------------ */
  7753  /* decGetDigits -- count digits in a Units array                      */
  7754  /*                                                                    */
  7755  /*   uar is the Unit array holding the number (this is often an       */
  7756  /*          accumulator of some sort)                                 */
  7757  /*   len is the length of the array in units [>=1]                    */
  7758  /*                                                                    */
  7759  /*   returns the number of (significant) digits in the array          */
  7760  /*                                                                    */
  7761  /* All leading zeros are excluded, except the last if the array has   */
  7762  /* only zero Units.                                                   */
  7763  /* ------------------------------------------------------------------ */
  7764  // This may be called twice during some operations.
  7765  static Int decGetDigits(Unit *uar, Int len) {
  7766    Unit *up=uar+(len-1);            // -> msu
  7767    Int  digits=(len-1)*DECDPUN+1;   // possible digits excluding msu
  7768    #if DECDPUN>4
  7769    uInt const *pow;                 // work
  7770    #endif
  7771                                     // (at least 1 in final msu)
  7772    #if DECCHECK
  7773    if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
  7774    #endif
  7775  
  7776    for (; up>=uar; up--) {
  7777      if (*up==0) {                  // unit is all 0s
  7778        if (digits==1) break;        // a zero has one digit
  7779        digits-=DECDPUN;             // adjust for 0 unit
  7780        continue;}
  7781      // found the first (most significant) non-zero Unit
  7782      #if DECDPUN>1                  // not done yet
  7783      if (*up<10) break;             // is 1-9
  7784      digits++;
  7785      #if DECDPUN>2                  // not done yet
  7786      if (*up<100) break;            // is 10-99
  7787      digits++;
  7788      #if DECDPUN>3                  // not done yet
  7789      if (*up<1000) break;           // is 100-999
  7790      digits++;
  7791      #if DECDPUN>4                  // count the rest ...
  7792      for (pow=&powers[4]; *up>=*pow; pow++) digits++;
  7793      #endif
  7794      #endif
  7795      #endif
  7796      #endif
  7797      break;
  7798      } // up
  7799    return digits;
  7800    } // decGetDigits
  7801  
  7802  #if DECTRACE | DECCHECK
  7803  /* ------------------------------------------------------------------ */
  7804  /* decNumberShow -- display a number [debug aid]                      */
  7805  /*   dn is the number to show                                         */
  7806  /*                                                                    */
  7807  /* Shows: sign, exponent, coefficient (msu first), digits             */
  7808  /*    or: sign, special-value                                         */
  7809  /* ------------------------------------------------------------------ */
  7810  // this is public so other modules can use it
  7811  void decNumberShow(const decNumber *dn) {
  7812    const Unit *up;                  // work
  7813    uInt u, d;                       // ..
  7814    Int cut;                         // ..
  7815    char isign='+';                  // main sign
  7816    if (dn==NULL) {
  7817      printf("NULL\n");
  7818      return;}
  7819    if (decNumberIsNegative(dn)) isign='-';
  7820    printf(" >> %c ", isign);
  7821    if (dn->bits&DECSPECIAL) {       // Is a special value
  7822      if (decNumberIsInfinite(dn)) printf("Infinity");
  7823       else {                                  // a NaN
  7824        if (dn->bits&DECSNAN) printf("sNaN");  // signalling NaN
  7825         else printf("NaN");
  7826        }
  7827      // if coefficient and exponent are 0, no more to do
  7828      if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
  7829        printf("\n");
  7830        return;}
  7831      // drop through to report other information
  7832      printf(" ");
  7833      }
  7834  
  7835    // now carefully display the coefficient
  7836    up=dn->lsu+D2U(dn->digits)-1;         // msu
  7837    printf("%ld", (LI)*up);
  7838    for (up=up-1; up>=dn->lsu; up--) {
  7839      u=*up;
  7840      printf(":");
  7841      for (cut=DECDPUN-1; cut>=0; cut--) {
  7842        d=u/powers[cut];
  7843        u-=d*powers[cut];
  7844        printf("%ld", (LI)d);
  7845        } // cut
  7846      } // up
  7847    if (dn->exponent!=0) {
  7848      char esign='+';
  7849      if (dn->exponent<0) esign='-';
  7850      printf(" E%c%ld", esign, (LI)abs(dn->exponent));
  7851      }
  7852    printf(" [%ld]\n", (LI)dn->digits);
  7853    } // decNumberShow
  7854  #endif
  7855  
  7856  #if DECTRACE || DECCHECK
  7857  /* ------------------------------------------------------------------ */
  7858  /* decDumpAr -- display a unit array [debug/check aid]                */
  7859  /*   name is a single-character tag name                              */
  7860  /*   ar   is the array to display                                     */
  7861  /*   len  is the length of the array in Units                         */
  7862  /* ------------------------------------------------------------------ */
  7863  static void decDumpAr(char name, const Unit *ar, Int len) {
  7864    Int i;
  7865    const char *spec;
  7866    #if DECDPUN==9
  7867      spec="%09d ";
  7868    #elif DECDPUN==8
  7869      spec="%08d ";
  7870    #elif DECDPUN==7
  7871      spec="%07d ";
  7872    #elif DECDPUN==6
  7873      spec="%06d ";
  7874    #elif DECDPUN==5
  7875      spec="%05d ";
  7876    #elif DECDPUN==4
  7877      spec="%04d ";
  7878    #elif DECDPUN==3
  7879      spec="%03d ";
  7880    #elif DECDPUN==2
  7881      spec="%02d ";
  7882    #else
  7883      spec="%d ";
  7884    #endif
  7885    printf("  :%c: ", name);
  7886    for (i=len-1; i>=0; i--) {
  7887      if (i==len-1) printf("%ld ", (LI)ar[i]);
  7888       else printf(spec, ar[i]);
  7889      }
  7890    printf("\n");
  7891    return;}
  7892  #endif
  7893  
  7894  #if DECCHECK
  7895  /* ------------------------------------------------------------------ */
  7896  /* decCheckOperands -- check operand(s) to a routine                  */
  7897  /*   res is the result structure (not checked; it will be set to      */
  7898  /*          quiet NaN if error found (and it is not NULL))            */
  7899  /*   lhs is the first operand (may be DECUNRESU)                      */
  7900  /*   rhs is the second (may be DECUNUSED)                             */
  7901  /*   set is the context (may be DECUNCONT)                            */
  7902  /*   returns 0 if both operands, and the context are clean, or 1      */
  7903  /*     otherwise (in which case the context will show an error,       */
  7904  /*     unless NULL).  Note that res is not cleaned; caller should     */
  7905  /*     handle this so res=NULL case is safe.                          */
  7906  /* The caller is expected to abandon immediately if 1 is returned.    */
  7907  /* ------------------------------------------------------------------ */
  7908  static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
  7909                               const decNumber *rhs, decContext *set) {
  7910    Flag bad=0;
  7911    if (set==NULL) {                 // oops; hopeless
  7912      #if DECTRACE || DECVERB
  7913      printf("Reference to context is NULL.\n");
  7914      #endif
  7915      bad=1;
  7916      return 1;}
  7917     else if (set!=DECUNCONT
  7918       && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
  7919      bad=1;
  7920      #if DECTRACE || DECVERB
  7921      printf("Bad context [digits=%ld round=%ld].\n",
  7922             (LI)set->digits, (LI)set->round);
  7923      #endif
  7924      }
  7925     else {
  7926      if (res==NULL) {
  7927        bad=1;
  7928        #if DECTRACE
  7929        // this one not DECVERB as standard tests include NULL
  7930        printf("Reference to result is NULL.\n");
  7931        #endif
  7932        }
  7933      if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
  7934      if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
  7935      }
  7936    if (bad) {
  7937      if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
  7938      if (res!=DECUNRESU && res!=NULL) {
  7939        decNumberZero(res);
  7940        res->bits=DECNAN;       // qNaN
  7941        }
  7942      }
  7943    return bad;
  7944    } // decCheckOperands
  7945  
  7946  /* ------------------------------------------------------------------ */
  7947  /* decCheckNumber -- check a number                                   */
  7948  /*   dn is the number to check                                        */
  7949  /*   returns 0 if the number is clean, or 1 otherwise                 */
  7950  /*                                                                    */
  7951  /* The number is considered valid if it could be a result from some   */
  7952  /* operation in some valid context.                                   */
  7953  /* ------------------------------------------------------------------ */
  7954  static Flag decCheckNumber(const decNumber *dn) {
  7955    const Unit *up;             // work
  7956    uInt maxuint;               // ..
  7957    Int ae, d, digits;          // ..
  7958    Int emin, emax;             // ..
  7959  
  7960    if (dn==NULL) {             // hopeless
  7961      #if DECTRACE
  7962      // this one not DECVERB as standard tests include NULL
  7963      printf("Reference to decNumber is NULL.\n");
  7964      #endif
  7965      return 1;}
  7966  
  7967    // check special values
  7968    if (dn->bits & DECSPECIAL) {
  7969      if (dn->exponent!=0) {
  7970        #if DECTRACE || DECVERB
  7971        printf("Exponent %ld (not 0) for a special value [%02x].\n",
  7972               (LI)dn->exponent, dn->bits);
  7973        #endif
  7974        return 1;}
  7975  
  7976      // 2003.09.08: NaNs may now have coefficients, so next tests Inf only
  7977      if (decNumberIsInfinite(dn)) {
  7978        if (dn->digits!=1) {
  7979          #if DECTRACE || DECVERB
  7980          printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
  7981          #endif
  7982          return 1;}
  7983        if (*dn->lsu!=0) {
  7984          #if DECTRACE || DECVERB
  7985          printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
  7986          #endif
  7987          decDumpAr('I', dn->lsu, D2U(dn->digits));
  7988          return 1;}
  7989        } // Inf
  7990      // 2002.12.26: negative NaNs can now appear through proposed IEEE
  7991      //             concrete formats (decimal64, etc.).
  7992      return 0;
  7993      }
  7994  
  7995    // check the coefficient
  7996    if (dn->digits<1 || dn->digits>DECNUMMAXP) {
  7997      #if DECTRACE || DECVERB
  7998      printf("Digits %ld in number.\n", (LI)dn->digits);
  7999      #endif
  8000      return 1;}
  8001  
  8002    d=dn->digits;
  8003  
  8004    for (up=dn->lsu; d>0; up++) {
  8005      if (d>DECDPUN) maxuint=DECDPUNMAX;
  8006       else {                   // reached the msu
  8007        maxuint=powers[d]-1;
  8008        if (dn->digits>1 && *up<powers[d-1]) {
  8009          #if DECTRACE || DECVERB
  8010          printf("Leading 0 in number.\n");
  8011          decNumberShow(dn);
  8012          #endif
  8013          return 1;}
  8014        }
  8015      if (*up>maxuint) {
  8016        #if DECTRACE || DECVERB
  8017        printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
  8018                (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
  8019        #endif
  8020        return 1;}
  8021      d-=DECDPUN;
  8022      }
  8023  
  8024    // check the exponent.  Note that input operands can have exponents
  8025    // which are out of the set->emin/set->emax and set->digits range
  8026    // (just as they can have more digits than set->digits).
  8027    ae=dn->exponent+dn->digits-1;    // adjusted exponent
  8028    emax=DECNUMMAXE;
  8029    emin=DECNUMMINE;
  8030    digits=DECNUMMAXP;
  8031    if (ae<emin-(digits-1)) {
  8032      #if DECTRACE || DECVERB
  8033      printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
  8034      decNumberShow(dn);
  8035      #endif
  8036      return 1;}
  8037    if (ae>+emax) {
  8038      #if DECTRACE || DECVERB
  8039      printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
  8040      decNumberShow(dn);
  8041      #endif
  8042      return 1;}
  8043  
  8044    return 0;              // it's OK
  8045    } // decCheckNumber
  8046  
  8047  /* ------------------------------------------------------------------ */
  8048  /* decCheckInexact -- check a normal finite inexact result has digits */
  8049  /*   dn is the number to check                                        */
  8050  /*   set is the context (for status and precision)                    */
  8051  /*   sets Invalid operation, etc., if some digits are missing         */
  8052  /* [this check is not made for DECSUBSET compilation or when          */
  8053  /* subnormal is not set]                                              */
  8054  /* ------------------------------------------------------------------ */
  8055  static void decCheckInexact(const decNumber *dn, decContext *set) {
  8056    #if !DECSUBSET && DECEXTFLAG
  8057      if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
  8058       && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
  8059        #if DECTRACE || DECVERB
  8060        printf("Insufficient digits [%ld] on normal Inexact result.\n",
  8061               (LI)dn->digits);
  8062        decNumberShow(dn);
  8063        #endif
  8064        decContextSetStatus(set, DEC_Invalid_operation);
  8065        }
  8066    #else
  8067      // next is a noop for quiet compiler
  8068      if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
  8069    #endif
  8070    return;
  8071    } // decCheckInexact
  8072  #endif
  8073  
  8074  #if DECALLOC
  8075  #undef malloc
  8076  #undef free
  8077  /* ------------------------------------------------------------------ */
  8078  /* decMalloc -- accountable allocation routine                        */
  8079  /*   n is the number of bytes to allocate                             */
  8080  /*                                                                    */
  8081  /* Semantics is the same as the stdlib malloc routine, but bytes      */
  8082  /* allocated are accounted for globally, and corruption fences are    */
  8083  /* added before and after the 'actual' storage.                       */
  8084  /* ------------------------------------------------------------------ */
  8085  /* This routine allocates storage with an extra twelve bytes; 8 are   */
  8086  /* at the start and hold:                                             */
  8087  /*   0-3 the original length requested                                */
  8088  /*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
  8089  /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
  8090  /* ------------------------------------------------------------------ */
  8091  static void *decMalloc(size_t n) {
  8092    uInt  size=n+12;                 // true size
  8093    void  *alloc;                    // -> allocated storage
  8094    uByte *b, *b0;                   // work
  8095    uInt  uiwork;                    // for macros
  8096  
  8097    alloc=malloc(size);              // -> allocated storage
  8098    if (alloc==NULL) return NULL;    // out of strorage
  8099    b0=(uByte *)alloc;               // as bytes
  8100    decAllocBytes+=n;                // account for storage
  8101    UBFROMUI(alloc, n);              // save n
  8102    // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);
  8103    for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
  8104    for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
  8105    return b0+8;                     // -> play area
  8106    } // decMalloc
  8107  
  8108  /* ------------------------------------------------------------------ */
  8109  /* decFree -- accountable free routine                                */
  8110  /*   alloc is the storage to free                                     */
  8111  /*                                                                    */
  8112  /* Semantics is the same as the stdlib malloc routine, except that    */
  8113  /* the global storage accounting is updated and the fences are        */
  8114  /* checked to ensure that no routine has written 'out of bounds'.     */
  8115  /* ------------------------------------------------------------------ */
  8116  /* This routine first checks that the fences have not been corrupted. */
  8117  /* It then frees the storage using the 'truw' storage address (that   */
  8118  /* is, offset by 8).                                                  */
  8119  /* ------------------------------------------------------------------ */
  8120  static void decFree(void *alloc) {
  8121    uInt  n;                         // original length
  8122    uByte *b, *b0;                   // work
  8123    uInt  uiwork;                    // for macros
  8124  
  8125    if (alloc==NULL) return;         // allowed; it's a nop
  8126    b0=(uByte *)alloc;               // as bytes
  8127    b0-=8;                           // -> true start of storage
  8128    n=UBTOUI(b0);                    // lift length
  8129    for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
  8130      printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
  8131             b-b0-8, (LI)b0);
  8132    for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
  8133      printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
  8134             b-b0-8, (LI)b0, (LI)n);
  8135    free(b0);                        // drop the storage
  8136    decAllocBytes-=n;                // account for storage
  8137    // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);
  8138    } // decFree
  8139  #define malloc(a) decMalloc(a)
  8140  #define free(a) decFree(a)
  8141  #endif