decNumber.c /size: 380 Kb    last modification: 2025-02-21 11:03
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
174const 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
199static 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 */
221static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
222                              decContext *, uByte, uInt *);
223static Flag        decBiStr(const char *, const char *, const char *);
224static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
225static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
226static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
227static decNumber * decCompareOp(decNumber *, const decNumber *,
228                              const decNumber *, decContext *,
229                              Flag, uInt *);
230static void        decCopyFit(decNumber *, const decNumber *, decContext *,
231                              Int *, uInt *);
232static decNumber * decDecap(decNumber *, Int);
233static decNumber * decDivideOp(decNumber *, const decNumber *,
234                              const decNumber *, decContext *, Flag, uInt *);
235static decNumber * decExpOp(decNumber *, const decNumber *,
236                              decContext *, uInt *);
237static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
238static Int         decGetDigits(Unit *, Int);
239static Int         decGetInt(const decNumber *);
240static decNumber * decLnOp(decNumber *, const decNumber *,
241                              decContext *, uInt *);
242static decNumber * decMultiplyOp(decNumber *, const decNumber *,
243                              const decNumber *, decContext *,
244                              uInt *);
245static decNumber * decNaNs(decNumber *, const decNumber *,
246                              const decNumber *, decContext *, uInt *);
247static decNumber * decQuantizeOp(decNumber *, const decNumber *,
248                              const decNumber *, decContext *, Flag,
249                              uInt *);
250static void        decReverse(Unit *, Unit *);
251static void        decSetCoeff(decNumber *, decContext *, const Unit *,
252                              Int, Int *, uInt *);
253static void        decSetMaxValue(decNumber *, decContext *);
254static void        decSetOverflow(decNumber *, decContext *, uInt *);
255static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
256static Int         decShiftToLeast(Unit *, Int, Int);
257static Int         decShiftToMost(Unit *, Int, Int);
258static void        decStatus(decNumber *, uInt, decContext *);
259static void        decToString(const decNumber *, char[], Flag);
260static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
261static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
262                              Unit *, Int);
263static 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
269static void        decFinish(decNumber *, decContext *, Int *, uInt *);
270static 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:
287static void *decMalloc(size_t);
288static void  decFree(void *);
289uInt 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# include "../../utilities/auxmemory.h"
298# define malloc lmt_memory_malloc
299# define free   lmt_memory_free
300
301#if DECCHECK
302// Optional checking routines.  Enabling these means that decNumber
303// and decContext operands to operator routines are checked for
304// correctness.  This roughly doubles the execution time of the
305// fastest routines (and adds 600+ bytes), so should not normally be
306// used in 'production'.
307// decCheckInexact is used to check that inexact results have a full
308// complement of digits (where appropriate -- this is not the case
309// for Quantize, for example)
310#define DECUNRESU ((decNumber *)(void *)0xffffffff)
311#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
312#define DECUNCONT ((decContext *)(void *)(0xffffffff))
313static Flag decCheckOperands(decNumber *, const decNumber *,
314                             const decNumber *, decContext *);
315static Flag decCheckNumber(const decNumber *);
316static void decCheckInexact(const decNumber *, decContext *);
317#endif
318
319#if DECTRACE || DECCHECK
320// Optional trace/debugging routines (may or may not be used)
321void decNumberShow(const decNumber *);  // displays the components of a number
322static void decDumpAr(char, const Unit *, Int);
323#endif
324
325/* ================================================================== */
326/* Conversions                                                        */
327/* ================================================================== */
328
329/* ------------------------------------------------------------------ */
330/* from-int32 -- conversion from Int or uInt                          */
331/*                                                                    */
332/*  dn is the decNumber to receive the integer                        */
333/*  in or uin is the integer to be converted                          */
334/*  returns dn                                                        */
335/*                                                                    */
336/* No error is possible.                                              */
337/* ------------------------------------------------------------------ */
338decNumber * decNumberFromInt32(decNumber *dn, Int in) {
339  uInt unsig;
340  if (in>=0) unsig=in;
341   else {                               // negative (possibly BADINT)
342    if (in==BADINT) unsig=(uInt)1073741824*2; // special case
343     else unsig=-in;                    // invert
344    }
345  // in is now positive
346  decNumberFromUInt32(dn, unsig);
347  if (in<0) dn->bits=DECNEG;            // sign needed
348  return dn;
349  } // decNumberFromInt32
350
351decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
352  Unit *up;                             // work pointer
353  decNumberZero(dn);                    // clean
354  if (uin==0) return dn;                // [or decGetDigits bad call]
355  for (up=dn->lsu; uin>0; up++) {
356    *up=(Unit)(uin%(DECDPUNMAX+1));
357    uin=uin/(DECDPUNMAX+1);
358    }
359  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
360  return dn;
361  } // decNumberFromUInt32
362
363/* ------------------------------------------------------------------ */
364/* to-int32 -- conversion to Int or uInt                              */
365/*                                                                    */
366/*  dn is the decNumber to convert                                    */
367/*  set is the context for reporting errors                           */
368/*  returns the converted decNumber, or 0 if Invalid is set           */
369/*                                                                    */
370/* Invalid is set if the decNumber does not have exponent==0 or if    */
371/* it is a NaN, Infinite, or out-of-range.                            */
372/* ------------------------------------------------------------------ */
373Int decNumberToInt32(const decNumber *dn, decContext *set) {
374  #if DECCHECK
375  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
376  #endif
377
378  // special or too many digits, or bad exponent
379  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; // bad
380   else { // is a finite integer with 10 or fewer digits
381    Int d;                         // work
382    const Unit *up;                // ..
383    uInt hi=0, lo;                 // ..
384    up=dn->lsu;                    // -> lsu
385    lo=*up;                        // get 1 to 9 digits
386    #if DECDPUN>1                  // split to higher
387      hi=lo/10;
388      lo=lo%10;
389    #endif
390    up++;
391    // collect remaining Units, if any, into hi
392    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
393    // now low has the lsd, hi the remainder
394    if (hi>214748364 || (hi==214748364 && lo>7)) { // out of range?
395      // most-negative is a reprieve
396      if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
397      // bad -- drop through
398      }
399     else { // in-range always
400      Int i=X10(hi)+lo;
401      if (dn->bits&DECNEG) return -i;
402      return i;
403      }
404    } // integer
405  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
406  return 0;
407  } // decNumberToInt32
408
409uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
410  #if DECCHECK
411  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
412  #endif
413  // special or too many digits, or bad exponent, or negative (<0)
414  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
415    || (dn->bits&DECNEG && !ISZERO(dn)));                   // bad
416   else { // is a finite integer with 10 or fewer digits
417    Int d;                         // work
418    const Unit *up;                // ..
419    uInt hi=0, lo;                 // ..
420    up=dn->lsu;                    // -> lsu
421    lo=*up;                        // get 1 to 9 digits
422    #if DECDPUN>1                  // split to higher
423      hi=lo/10;
424      lo=lo%10;
425    #endif
426    up++;
427    // collect remaining Units, if any, into hi
428    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
429
430    // now low has the lsd, hi the remainder
431    if (hi>429496729 || (hi==429496729 && lo>5)) ; // no reprieve possible
432     else return X10(hi)+lo;
433    } // integer
434  decContextSetStatus(set, DEC_Invalid_operation); // [may not return]
435  return 0;
436  } // decNumberToUInt32
437
438/* ------------------------------------------------------------------ */
439/* to-scientific-string -- conversion to numeric string               */
440/* to-engineering-string -- conversion to numeric string              */
441/*                                                                    */
442/*   decNumberToString(dn, string);                                   */
443/*   decNumberToEngString(dn, string);                                */
444/*                                                                    */
445/*  dn is the decNumber to convert                                    */
446/*  string is the string where the result will be laid out            */
447/*                                                                    */
448/*  string must be at least dn->digits+14 characters long             */
449/*                                                                    */
450/*  No error is possible, and no status can be set.                   */
451/* ------------------------------------------------------------------ */
452char * decNumberToString(const decNumber *dn, char *string){
453  decToString(dn, string, 0);
454  return string;
455  } // DecNumberToString
456
457char * decNumberToEngString(const decNumber *dn, char *string){
458  decToString(dn, string, 1);
459  return string;
460  } // DecNumberToEngString
461
462/* ------------------------------------------------------------------ */
463/* to-number -- conversion from numeric string                        */
464/*                                                                    */
465/* decNumberFromString -- convert string to decNumber                 */
466/*   dn        -- the number structure to fill                        */
467/*   chars[]   -- the string to convert ('\0' terminated)             */
468/*   set       -- the context used for processing any error,          */
469/*                determining the maximum precision available         */
470/*                (set.digits), determining the maximum and minimum   */
471/*                exponent (set.emax and set.emin), determining if    */
472/*                extended values are allowed, and checking the       */
473/*                rounding mode if overflow occurs or rounding is     */
474/*                needed.                                             */
475/*                                                                    */
476/* The length of the coefficient and the size of the exponent are     */
477/* checked by this routine, so the correct error (Underflow or        */
478/* Overflow) can be reported or rounding applied, as necessary.       */
479/*                                                                    */
480/* If bad syntax is detected, the result will be a quiet NaN.         */
481/* ------------------------------------------------------------------ */
482decNumber * decNumberFromString(decNumber *dn, const char chars[],
483                                decContext *set) {
484  Int   exponent=0;                // working exponent [assume 0]
485  uByte bits=0;                    // working flags [assume +ve]
486  Unit  *res;                      // where result will be built
487  Unit  resbuff[SD2U(DECBUFFER+9)];// local buffer in case need temporary
488                                   // [+9 allows for ln() constants]
489  Unit  *allocres=NULL;            // -> allocated result, iff allocated
490  Int   d=0;                       // count of digits found in decimal part
491  const char *dotchar=NULL;        // where dot was found
492  const char *cfirst=chars;        // -> first character of decimal part
493  const char *last=NULL;           // -> last digit of decimal part
494  const char *c;                   // work
495  Unit  *up;                       // ..
496  #if DECDPUN>1
497  Int   cut, out;                  // ..
498  #endif
499  Int   residue;                   // rounding residue
500  uInt  status=0;                  // error code
501
502  #if DECCHECK
503  if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
504    return decNumberZero(dn);
505  #endif
506
507  do {                             // status & malloc protection
508    for (c=chars;; c++) {          // -> input character
509      if (*c>='0' && *c<='9') {    // test for Arabic digit
510        last=c;
511        d++;                       // count of real digits
512        continue;                  // still in decimal part
513        }
514      if (*c=='.' && dotchar==NULL) { // first '.'
515        dotchar=c;                 // record offset into decimal part
516        if (c==cfirst) cfirst++;   // first digit must follow
517        continue;}
518      if (c==chars) {              // first in string...
519        if (*c=='-') {             // valid - sign
520          cfirst++;
521          bits=DECNEG;
522          continue;}
523        if (*c=='+') {             // valid + sign
524          cfirst++;
525          continue;}
526        }
527      // *c is not a digit, or a valid +, -, or '.'
528      break;
529      } // c
530
531    if (last==NULL) {              // no digits yet
532      status=DEC_Conversion_syntax;// assume the worst
533      if (*c=='\0') break;         // and no more to come...
534      #if DECSUBSET
535      // if subset then infinities and NaNs are not allowed
536      if (!set->extended) break;   // hopeless
537      #endif
538      // Infinities and NaNs are possible, here
539      if (dotchar!=NULL) break;    // .. unless had a dot
540      decNumberZero(dn);           // be optimistic
541      if (decBiStr(c, "infinity", "INFINITY")
542       || decBiStr(c, "inf", "INF")) {
543        dn->bits=bits | DECINF;
544        status=0;                  // is OK
545        break; // all done
546        }
547      // a NaN expected
548      // 2003.09.10 NaNs are now permitted to have a sign
549      dn->bits=bits | DECNAN;      // assume simple NaN
550      if (*c=='s' || *c=='S') {    // looks like an sNaN
551        c++;
552        dn->bits=bits | DECSNAN;
553        }
554      if (*c!='n' && *c!='N') break;    // check caseless "NaN"
555      c++;
556      if (*c!='a' && *c!='A') break;    // ..
557      c++;
558      if (*c!='n' && *c!='N') break;    // ..
559      c++;
560      // now either nothing, or nnnn payload, expected
561      // -> start of integer and skip leading 0s [including plain 0]
562      for (cfirst=c; *cfirst=='0';) cfirst++;
563      if (*cfirst=='\0') {         // "NaN" or "sNaN", maybe with all 0s
564        status=0;                  // it's good
565        break;                     // ..
566        }
567      // something other than 0s; setup last and d as usual [no dots]
568      for (c=cfirst;; c++, d++) {
569        if (*c<'0' || *c>'9') break; // test for Arabic digit
570        last=c;
571        }
572      if (*c!='\0') break;         // not all digits
573      if (d>set->digits-1) {
574        // [NB: payload in a decNumber can be full length unless
575        // clamped, in which case can only be digits-1]
576        if (set->clamp) break;
577        if (d>set->digits) break;
578        } // too many digits?
579      // good; drop through to convert the integer to coefficient
580      status=0;                    // syntax is OK
581      bits=dn->bits;               // for copy-back
582      } // last==NULL
583
584     else if (*c!='\0') {          // more to process...
585      // had some digits; exponent is only valid sequence now
586      Flag nege;                   // 1=negative exponent
587      const char *firstexp;        // -> first significant exponent digit
588      status=DEC_Conversion_syntax;// assume the worst
589      if (*c!='e' && *c!='E') break;
590      /* Found 'e' or 'E' -- now process explicit exponent */
591      // 1998.07.11: sign no longer required
592      nege=0;
593      c++;                         // to (possible) sign
594      if (*c=='-') {nege=1; c++;}
595       else if (*c=='+') c++;
596      if (*c=='\0') break;
597
598      for (; *c=='0' && *(c+1)!='\0';) c++;  // strip insignificant zeros
599      firstexp=c;                            // save exponent digit place
600      for (; ;c++) {
601        if (*c<'0' || *c>'9') break;         // not a digit
602        exponent=X10(exponent)+(Int)*c-(Int)'0';
603        } // c
604      // if not now on a '\0', *c must not be a digit
605      if (*c!='\0') break;
606
607      // (this next test must be after the syntax checks)
608      // if it was too long the exponent may have wrapped, so check
609      // carefully and set it to a certain overflow if wrap possible
610      if (c>=firstexp+9+1) {
611        if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
612        // [up to 1999999999 is OK, for example 1E-1000000998]
613        }
614      if (nege) exponent=-exponent;     // was negative
615      status=0;                         // is OK
616      } // stuff after digits
617
618    // Here when whole string has been inspected; syntax is good
619    // cfirst->first digit (never dot), last->last digit (ditto)
620
621    // strip leading zeros/dot [leave final 0 if all 0's]
622    if (*cfirst=='0') {                 // [cfirst has stepped over .]
623      for (c=cfirst; c<last; c++, cfirst++) {
624        if (*c=='.') continue;          // ignore dots
625        if (*c!='0') break;             // non-zero found
626        d--;                            // 0 stripped
627        } // c
628      #if DECSUBSET
629      // make a rapid exit for easy zeros if !extended
630      if (*cfirst=='0' && !set->extended) {
631        decNumberZero(dn);              // clean result
632        break;                          // [could be return]
633        }
634      #endif
635      } // at least one leading 0
636
637    // Handle decimal point...
638    if (dotchar!=NULL && dotchar<last)  // non-trailing '.' found?
639      exponent-=(last-dotchar);         // adjust exponent
640    // [we can now ignore the .]
641
642    // OK, the digits string is good.  Assemble in the decNumber, or in
643    // a temporary units array if rounding is needed
644    if (d<=set->digits) res=dn->lsu;    // fits into supplied decNumber
645     else {                             // rounding needed
646      Int needbytes=D2U(d)*sizeof(Unit);// bytes needed
647      res=resbuff;                      // assume use local buffer
648      if (needbytes>(Int)sizeof(resbuff)) { // too big for local
649        allocres=(Unit *)malloc(needbytes);
650        if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
651        res=allocres;
652        }
653      }
654    // res now -> number lsu, buffer, or allocated storage for Unit array
655
656    // Place the coefficient into the selected Unit array
657    // [this is often 70% of the cost of this function when DECDPUN>1]
658    #if DECDPUN>1
659    out=0;                         // accumulator
660    up=res+D2U(d)-1;               // -> msu
661    cut=d-(up-res)*DECDPUN;        // digits in top unit
662    for (c=cfirst;; c++) {         // along the digits
663      if (*c=='.') continue;       // ignore '.' [don't decrement cut]
664      out=X10(out)+(Int)*c-(Int)'0';
665      if (c==last) break;          // done [never get to trailing '.']
666      cut--;
667      if (cut>0) continue;         // more for this unit
668      *up=(Unit)out;               // write unit
669      up--;                        // prepare for unit below..
670      cut=DECDPUN;                 // ..
671      out=0;                       // ..
672      } // c
673    *up=(Unit)out;                 // write lsu
674
675    #else
676    // DECDPUN==1
677    up=res;                        // -> lsu
678    for (c=last; c>=cfirst; c--) { // over each character, from least
679      if (*c=='.') continue;       // ignore . [don't step up]
680      *up=(Unit)((Int)*c-(Int)'0');
681      up++;
682      } // c
683    #endif
684
685    dn->bits=bits;
686    dn->exponent=exponent;
687    dn->digits=d;
688
689    // if not in number (too long) shorten into the number
690    if (d>set->digits) {
691      residue=0;
692      decSetCoeff(dn, set, res, d, &residue, &status);
693      // always check for overflow or subnormal and round as needed
694      decFinalize(dn, set, &residue, &status);
695      }
696     else { // no rounding, but may still have overflow or subnormal
697      // [these tests are just for performance; finalize repeats them]
698      if ((dn->exponent-1<set->emin-dn->digits)
699       || (dn->exponent-1>set->emax-set->digits)) {
700        residue=0;
701        decFinalize(dn, set, &residue, &status);
702        }
703      }
704    // decNumberShow(dn);
705    } while(0);                         // [for break]
706
707  if (allocres!=NULL) free(allocres);   // drop any storage used
708  if (status!=0) decStatus(dn, status, set);
709  return dn;
710  } /* decNumberFromString */
711
712/* ================================================================== */
713/* Operators                                                          */
714/* ================================================================== */
715
716/* ------------------------------------------------------------------ */
717/* decNumberAbs -- absolute value operator                            */
718/*                                                                    */
719/*   This computes C = abs(A)                                         */
720/*                                                                    */
721/*   res is C, the result.  C may be A                                */
722/*   rhs is A                                                         */
723/*   set is the context                                               */
724/*                                                                    */
725/* See also decNumberCopyAbs for a quiet bitwise version of this.     */
726/* C must have space for set->digits digits.                          */
727/* ------------------------------------------------------------------ */
728/* This has the same effect as decNumberPlus unless A is negative,    */
729/* in which case it has the same effect as decNumberMinus.            */
730/* ------------------------------------------------------------------ */
731decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
732                         decContext *set) {
733  decNumber dzero;                      // for 0
734  uInt status=0;                        // accumulator
735
736  #if DECCHECK
737  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
738  #endif
739
740  decNumberZero(&dzero);                // set 0
741  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
742  decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
743  if (status!=0) decStatus(res, status, set);
744  #if DECCHECK
745  decCheckInexact(res, set);
746  #endif
747  return res;
748  } // decNumberAbs
749
750/* ------------------------------------------------------------------ */
751/* decNumberAdd -- add two Numbers                                    */
752/*                                                                    */
753/*   This computes C = A + B                                          */
754/*                                                                    */
755/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
756/*   lhs is A                                                         */
757/*   rhs is B                                                         */
758/*   set is the context                                               */
759/*                                                                    */
760/* C must have space for set->digits digits.                          */
761/* ------------------------------------------------------------------ */
762/* This just calls the routine shared with Subtract                   */
763decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
764                         const decNumber *rhs, decContext *set) {
765  uInt status=0;                        // accumulator
766  decAddOp(res, lhs, rhs, set, 0, &status);
767  if (status!=0) decStatus(res, status, set);
768  #if DECCHECK
769  decCheckInexact(res, set);
770  #endif
771  return res;
772  } // decNumberAdd
773
774/* ------------------------------------------------------------------ */
775/* decNumberAnd -- AND two Numbers, digitwise                         */
776/*                                                                    */
777/*   This computes C = A & B                                          */
778/*                                                                    */
779/*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
780/*   lhs is A                                                         */
781/*   rhs is B                                                         */
782/*   set is the context (used for result length and error report)     */
783/*                                                                    */
784/* C must have space for set->digits digits.                          */
785/*                                                                    */
786/* Logical function restrictions apply (see above); a NaN is          */
787/* returned with Invalid_operation if a restriction is violated.      */
788/* ------------------------------------------------------------------ */
789decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
790                         const decNumber *rhs, decContext *set) {
791  const Unit *ua, *ub;                  // -> operands
792  const Unit *msua, *msub;              // -> operand msus
793  Unit *uc,  *msuc;                     // -> result and its msu
794  Int   msudigs;                        // digits in res msu
795  #if DECCHECK
796  if (decCheckOperands(res, lhs, rhs, set)) return res;
797  #endif
798
799  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
800   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
801    decStatus(res, DEC_Invalid_operation, set);
802    return res;
803    }
804
805  // operands are valid
806  ua=lhs->lsu;                          // bottom-up
807  ub=rhs->lsu;                          // ..
808  uc=res->lsu;                          // ..
809  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
810  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
811  msuc=uc+D2U(set->digits)-1;           // -> msu of result
812  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
813  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
814    Unit a, b;                          // extract units
815    if (ua>msua) a=0;
816     else a=*ua;
817    if (ub>msub) b=0;
818     else b=*ub;
819    *uc=0;                              // can now write back
820    if (a|b) {                          // maybe 1 bits to examine
821      Int i, j;
822      *uc=0;                            // can now write back
823      // This loop could be unrolled and/or use BIN2BCD tables
824      for (i=0; i<DECDPUN; i++) {
825        if (a&b&1) *uc=*uc+(Unit)powers[i];  // effect AND
826        j=a%10;
827        a=a/10;
828        j|=b%10;
829        b=b/10;
830        if (j>1) {
831          decStatus(res, DEC_Invalid_operation, set);
832          return res;
833          }
834        if (uc==msuc && i==msudigs-1) break; // just did final digit
835        } // each digit
836      } // both OK
837    } // each unit
838  // [here uc-1 is the msu of the result]
839  res->digits=decGetDigits(res->lsu, uc-res->lsu);
840  res->exponent=0;                      // integer
841  res->bits=0;                          // sign=0
842  return res;  // [no status to set]
843  } // decNumberAnd
844
845/* ------------------------------------------------------------------ */
846/* decNumberCompare -- compare two Numbers                            */
847/*                                                                    */
848/*   This computes C = A ? B                                          */
849/*                                                                    */
850/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
851/*   lhs is A                                                         */
852/*   rhs is B                                                         */
853/*   set is the context                                               */
854/*                                                                    */
855/* C must have space for one digit (or NaN).                          */
856/* ------------------------------------------------------------------ */
857decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
858                             const decNumber *rhs, decContext *set) {
859  uInt status=0;                        // accumulator
860  decCompareOp(res, lhs, rhs, set, COMPARE, &status);
861  if (status!=0) decStatus(res, status, set);
862  return res;
863  } // decNumberCompare
864
865/* ------------------------------------------------------------------ */
866/* decNumberCompareSignal -- compare, signalling on all NaNs          */
867/*                                                                    */
868/*   This computes C = A ? B                                          */
869/*                                                                    */
870/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
871/*   lhs is A                                                         */
872/*   rhs is B                                                         */
873/*   set is the context                                               */
874/*                                                                    */
875/* C must have space for one digit (or NaN).                          */
876/* ------------------------------------------------------------------ */
877decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
878                                   const decNumber *rhs, decContext *set) {
879  uInt status=0;                        // accumulator
880  decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
881  if (status!=0) decStatus(res, status, set);
882  return res;
883  } // decNumberCompareSignal
884
885/* ------------------------------------------------------------------ */
886/* decNumberCompareTotal -- compare two Numbers, using total ordering */
887/*                                                                    */
888/*   This computes C = A ? B, under total ordering                    */
889/*                                                                    */
890/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
891/*   lhs is A                                                         */
892/*   rhs is B                                                         */
893/*   set is the context                                               */
894/*                                                                    */
895/* C must have space for one digit; the result will always be one of  */
896/* -1, 0, or 1.                                                       */
897/* ------------------------------------------------------------------ */
898decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
899                                  const decNumber *rhs, decContext *set) {
900  uInt status=0;                        // accumulator
901  decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
902  if (status!=0) decStatus(res, status, set);
903  return res;
904  } // decNumberCompareTotal
905
906/* ------------------------------------------------------------------ */
907/* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
908/*                                                                    */
909/*   This computes C = |A| ? |B|, under total ordering                */
910/*                                                                    */
911/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
912/*   lhs is A                                                         */
913/*   rhs is B                                                         */
914/*   set is the context                                               */
915/*                                                                    */
916/* C must have space for one digit; the result will always be one of  */
917/* -1, 0, or 1.                                                       */
918/* ------------------------------------------------------------------ */
919decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
920                                     const decNumber *rhs, decContext *set) {
921  uInt status=0;                   // accumulator
922  uInt needbytes;                  // for space calculations
923  decNumber bufa[D2N(DECBUFFER+1)];// +1 in case DECBUFFER=0
924  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
925  decNumber bufb[D2N(DECBUFFER+1)];
926  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
927  decNumber *a, *b;                // temporary pointers
928
929  #if DECCHECK
930  if (decCheckOperands(res, lhs, rhs, set)) return res;
931  #endif
932
933  do {                                  // protect allocated storage
934    // if either is negative, take a copy and absolute
935    if (decNumberIsNegative(lhs)) {     // lhs<0
936      a=bufa;
937      needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
938      if (needbytes>sizeof(bufa)) {     // need malloc space
939        allocbufa=(decNumber *)malloc(needbytes);
940        if (allocbufa==NULL) {          // hopeless -- abandon
941          status|=DEC_Insufficient_storage;
942          break;}
943        a=allocbufa;                    // use the allocated space
944        }
945      decNumberCopy(a, lhs);            // copy content
946      a->bits&=~DECNEG;                 // .. and clear the sign
947      lhs=a;                            // use copy from here on
948      }
949    if (decNumberIsNegative(rhs)) {     // rhs<0
950      b=bufb;
951      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
952      if (needbytes>sizeof(bufb)) {     // need malloc space
953        allocbufb=(decNumber *)malloc(needbytes);
954        if (allocbufb==NULL) {          // hopeless -- abandon
955          status|=DEC_Insufficient_storage;
956          break;}
957        b=allocbufb;                    // use the allocated space
958        }
959      decNumberCopy(b, rhs);            // copy content
960      b->bits&=~DECNEG;                 // .. and clear the sign
961      rhs=b;                            // use copy from here on
962      }
963    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
964    } while(0);                         // end protected
965
966  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
967  if (allocbufb!=NULL) free(allocbufb); // ..
968  if (status!=0) decStatus(res, status, set);
969  return res;
970  } // decNumberCompareTotalMag
971
972/* ------------------------------------------------------------------ */
973/* decNumberDivide -- divide one number by another                    */
974/*                                                                    */
975/*   This computes C = A / B                                          */
976/*                                                                    */
977/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
978/*   lhs is A                                                         */
979/*   rhs is B                                                         */
980/*   set is the context                                               */
981/*                                                                    */
982/* C must have space for set->digits digits.                          */
983/* ------------------------------------------------------------------ */
984decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
985                            const decNumber *rhs, decContext *set) {
986  uInt status=0;                        // accumulator
987  decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
988  if (status!=0) decStatus(res, status, set);
989  #if DECCHECK
990  decCheckInexact(res, set);
991  #endif
992  return res;
993  } // decNumberDivide
994
995/* ------------------------------------------------------------------ */
996/* decNumberDivideInteger -- divide and return integer quotient       */
997/*                                                                    */
998/*   This computes C = A # B, where # is the integer divide operator  */
999/*                                                                    */
1000/*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1001/*   lhs is A                                                         */
1002/*   rhs is B                                                         */
1003/*   set is the context                                               */
1004/*                                                                    */
1005/* C must have space for set->digits digits.                          */
1006/* ------------------------------------------------------------------ */
1007decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1008                                   const decNumber *rhs, decContext *set) {
1009  uInt status=0;                        // accumulator
1010  decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1011  if (status!=0) decStatus(res, status, set);
1012  return res;
1013  } // decNumberDivideInteger
1014
1015/* ------------------------------------------------------------------ */
1016/* decNumberExp -- exponentiation                                     */
1017/*                                                                    */
1018/*   This computes C = exp(A)                                         */
1019/*                                                                    */
1020/*   res is C, the result.  C may be A                                */
1021/*   rhs is A                                                         */
1022/*   set is the context; note that rounding mode has no effect        */
1023/*                                                                    */
1024/* C must have space for set->digits digits.                          */
1025/*                                                                    */
1026/* Mathematical function restrictions apply (see above); a NaN is     */
1027/* returned with Invalid_operation if a restriction is violated.      */
1028/*                                                                    */
1029/* Finite results will always be full precision and Inexact, except   */
1030/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1031/*                                                                    */
1032/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1033/* almost always be correctly rounded, but may be up to 1 ulp in      */
1034/* error in rare cases.                                               */
1035/* ------------------------------------------------------------------ */
1036/* This is a wrapper for decExpOp which can handle the slightly wider */
1037/* (double) range needed by Ln (which has to be able to calculate     */
1038/* exp(-a) where a can be the tiniest number (Ntiny).                 */
1039/* ------------------------------------------------------------------ */
1040decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1041                         decContext *set) {
1042  uInt status=0;                        // accumulator
1043  #if DECSUBSET
1044  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1045  #endif
1046
1047  #if DECCHECK
1048  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1049  #endif
1050
1051  // Check restrictions; these restrictions ensure that if h=8 (see
1052  // decExpOp) then the result will either overflow or underflow to 0.
1053  // Other math functions restrict the input range, too, for inverses.
1054  // If not violated then carry out the operation.
1055  if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1056    #if DECSUBSET
1057    if (!set->extended) {
1058      // reduce operand and set lostDigits status, as needed
1059      if (rhs->digits>set->digits) {
1060        allocrhs=decRoundOperand(rhs, set, &status);
1061        if (allocrhs==NULL) break;
1062        rhs=allocrhs;
1063        }
1064      }
1065    #endif
1066    decExpOp(res, rhs, set, &status);
1067    } while(0);                         // end protected
1068
1069  #if DECSUBSET
1070  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
1071  #endif
1072  // apply significant status
1073  if (status!=0) decStatus(res, status, set);
1074  #if DECCHECK
1075  decCheckInexact(res, set);
1076  #endif
1077  return res;
1078  } // decNumberExp
1079
1080/* ------------------------------------------------------------------ */
1081/* decNumberFMA -- fused multiply add                                 */
1082/*                                                                    */
1083/*   This computes D = (A * B) + C with only one rounding             */
1084/*                                                                    */
1085/*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1086/*   lhs is A                                                         */
1087/*   rhs is B                                                         */
1088/*   fhs is C [far hand side]                                         */
1089/*   set is the context                                               */
1090/*                                                                    */
1091/* Mathematical function restrictions apply (see above); a NaN is     */
1092/* returned with Invalid_operation if a restriction is violated.      */
1093/*                                                                    */
1094/* C must have space for set->digits digits.                          */
1095/* ------------------------------------------------------------------ */
1096decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1097                         const decNumber *rhs, const decNumber *fhs,
1098                         decContext *set) {
1099  uInt status=0;                   // accumulator
1100  decContext dcmul;                // context for the multiplication
1101  uInt needbytes;                  // for space calculations
1102  decNumber bufa[D2N(DECBUFFER*2+1)];
1103  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1104  decNumber *acc;                  // accumulator pointer
1105  decNumber dzero;                 // work
1106
1107  #if DECCHECK
1108  if (decCheckOperands(res, lhs, rhs, set)) return res;
1109  if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1110  #endif
1111
1112  do {                                  // protect allocated storage
1113    #if DECSUBSET
1114    if (!set->extended) {               // [undefined if subset]
1115      status|=DEC_Invalid_operation;
1116      break;}
1117    #endif
1118    // Check math restrictions [these ensure no overflow or underflow]
1119    if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1120     || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1121     || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1122    // set up context for multiply
1123    dcmul=*set;
1124    dcmul.digits=lhs->digits+rhs->digits; // just enough
1125    // [The above may be an over-estimate for subset arithmetic, but that's OK]
1126    dcmul.emax=DEC_MAX_EMAX;            // effectively unbounded ..
1127    dcmul.emin=DEC_MIN_EMIN;            // [thanks to Math restrictions]
1128    // set up decNumber space to receive the result of the multiply
1129    acc=bufa;                           // may fit
1130    needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1131    if (needbytes>sizeof(bufa)) {       // need malloc space
1132      allocbufa=(decNumber *)malloc(needbytes);
1133      if (allocbufa==NULL) {            // hopeless -- abandon
1134        status|=DEC_Insufficient_storage;
1135        break;}
1136      acc=allocbufa;                    // use the allocated space
1137      }
1138    // multiply with extended range and necessary precision
1139    //printf("emin=%ld\n", dcmul.emin);
1140    decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1141    // Only Invalid operation (from sNaN or Inf * 0) is possible in
1142    // status; if either is seen than ignore fhs (in case it is
1143    // another sNaN) and set acc to NaN unless we had an sNaN
1144    // [decMultiplyOp leaves that to caller]
1145    // Note sNaN has to go through addOp to shorten payload if
1146    // necessary
1147    if ((status&DEC_Invalid_operation)!=0) {
1148      if (!(status&DEC_sNaN)) {         // but be true invalid
1149        decNumberZero(res);             // acc not yet set
1150        res->bits=DECNAN;
1151        break;
1152        }
1153      decNumberZero(&dzero);            // make 0 (any non-NaN would do)
1154      fhs=&dzero;                       // use that
1155      }
1156    #if DECCHECK
1157     else { // multiply was OK
1158      if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1159      }
1160    #endif
1161    // add the third operand and result -> res, and all is done
1162    decAddOp(res, acc, fhs, set, 0, &status);
1163    } while(0);                         // end protected
1164
1165  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1166  if (status!=0) decStatus(res, status, set);
1167  #if DECCHECK
1168  decCheckInexact(res, set);
1169  #endif
1170  return res;
1171  } // decNumberFMA
1172
1173/* ------------------------------------------------------------------ */
1174/* decNumberInvert -- invert a Number, digitwise                      */
1175/*                                                                    */
1176/*   This computes C = ~A                                             */
1177/*                                                                    */
1178/*   res is C, the result.  C may be A (e.g., X=~X)                   */
1179/*   rhs is A                                                         */
1180/*   set is the context (used for result length and error report)     */
1181/*                                                                    */
1182/* C must have space for set->digits digits.                          */
1183/*                                                                    */
1184/* Logical function restrictions apply (see above); a NaN is          */
1185/* returned with Invalid_operation if a restriction is violated.      */
1186/* ------------------------------------------------------------------ */
1187decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1188                            decContext *set) {
1189  const Unit *ua, *msua;                // -> operand and its msu
1190  Unit  *uc, *msuc;                     // -> result and its msu
1191  Int   msudigs;                        // digits in res msu
1192  #if DECCHECK
1193  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1194  #endif
1195
1196  if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1197    decStatus(res, DEC_Invalid_operation, set);
1198    return res;
1199    }
1200  // operand is valid
1201  ua=rhs->lsu;                          // bottom-up
1202  uc=res->lsu;                          // ..
1203  msua=ua+D2U(rhs->digits)-1;           // -> msu of rhs
1204  msuc=uc+D2U(set->digits)-1;           // -> msu of result
1205  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1206  for (; uc<=msuc; ua++, uc++) {        // Unit loop
1207    Unit a;                             // extract unit
1208    Int  i, j;                          // work
1209    if (ua>msua) a=0;
1210     else a=*ua;
1211    *uc=0;                              // can now write back
1212    // always need to examine all bits in rhs
1213    // This loop could be unrolled and/or use BIN2BCD tables
1214    for (i=0; i<DECDPUN; i++) {
1215      if ((~a)&1) *uc=*uc+(Unit)powers[i];   // effect INVERT
1216      j=a%10;
1217      a=a/10;
1218      if (j>1) {
1219        decStatus(res, DEC_Invalid_operation, set);
1220        return res;
1221        }
1222      if (uc==msuc && i==msudigs-1) break;   // just did final digit
1223      } // each digit
1224    } // each unit
1225  // [here uc-1 is the msu of the result]
1226  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1227  res->exponent=0;                      // integer
1228  res->bits=0;                          // sign=0
1229  return res;  // [no status to set]
1230  } // decNumberInvert
1231
1232/* ------------------------------------------------------------------ */
1233/* decNumberLn -- natural logarithm                                   */
1234/*                                                                    */
1235/*   This computes C = ln(A)                                          */
1236/*                                                                    */
1237/*   res is C, the result.  C may be A                                */
1238/*   rhs is A                                                         */
1239/*   set is the context; note that rounding mode has no effect        */
1240/*                                                                    */
1241/* C must have space for set->digits digits.                          */
1242/*                                                                    */
1243/* Notable cases:                                                     */
1244/*   A<0 -> Invalid                                                   */
1245/*   A=0 -> -Infinity (Exact)                                         */
1246/*   A=+Infinity -> +Infinity (Exact)                                 */
1247/*   A=1 exactly -> 0 (Exact)                                         */
1248/*                                                                    */
1249/* Mathematical function restrictions apply (see above); a NaN is     */
1250/* returned with Invalid_operation if a restriction is violated.      */
1251/*                                                                    */
1252/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1253/* almost always be correctly rounded, but may be up to 1 ulp in      */
1254/* error in rare cases.                                               */
1255/* ------------------------------------------------------------------ */
1256/* This is a wrapper for decLnOp which can handle the slightly wider  */
1257/* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1258/* to calculate at p+e+2).                                            */
1259/* ------------------------------------------------------------------ */
1260decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1261                        decContext *set) {
1262  uInt status=0;                   // accumulator
1263  #if DECSUBSET
1264  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1265  #endif
1266
1267  #if DECCHECK
1268  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1269  #endif
1270
1271  // Check restrictions; this is a math function; if not violated
1272  // then carry out the operation.
1273  if (!decCheckMath(rhs, set, &status)) do { // protect allocation
1274    #if DECSUBSET
1275    if (!set->extended) {
1276      // reduce operand and set lostDigits status, as needed
1277      if (rhs->digits>set->digits) {
1278        allocrhs=decRoundOperand(rhs, set, &status);
1279        if (allocrhs==NULL) break;
1280        rhs=allocrhs;
1281        }
1282      // special check in subset for rhs=0
1283      if (ISZERO(rhs)) {                // +/- zeros -> error
1284        status|=DEC_Invalid_operation;
1285        break;}
1286      } // extended=0
1287    #endif
1288    decLnOp(res, rhs, set, &status);
1289    } while(0);                         // end protected
1290
1291  #if DECSUBSET
1292  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
1293  #endif
1294  // apply significant status
1295  if (status!=0) decStatus(res, status, set);
1296  #if DECCHECK
1297  decCheckInexact(res, set);
1298  #endif
1299  return res;
1300  } // decNumberLn
1301
1302/* ------------------------------------------------------------------ */
1303/* decNumberLogB - get adjusted exponent, by 754 rules                */
1304/*                                                                    */
1305/*   This computes C = adjustedexponent(A)                            */
1306/*                                                                    */
1307/*   res is C, the result.  C may be A                                */
1308/*   rhs is A                                                         */
1309/*   set is the context, used only for digits and status              */
1310/*                                                                    */
1311/* For an unrounded result, digits may need to be 10 (A might have    */
1312/* 10**9 digits and an exponent of +999999999, or one digit and an    */
1313/* exponent of -1999999999).                                          */
1314/*                                                                    */
1315/* This returns the adjusted exponent of A after (in theory) padding  */
1316/* with zeros on the right to set->digits digits while keeping the    */
1317/* same value.  The exponent is not limited by emin/emax.             */
1318/*                                                                    */
1319/* Notable cases:                                                     */
1320/*   A<0 -> Use |A|                                                   */
1321/*   A=0 -> -Infinity (Division by zero)                              */
1322/*   A=Infinite -> +Infinity (Exact)                                  */
1323/*   A=1 exactly -> 0 (Exact)                                         */
1324/*   NaNs are propagated as usual                                     */
1325/* ------------------------------------------------------------------ */
1326decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1327                          decContext *set) {
1328  uInt status=0;                   // accumulator
1329
1330  #if DECCHECK
1331  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1332  #endif
1333
1334  // NaNs as usual; Infinities return +Infinity; 0->oops
1335  if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1336   else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1337   else if (decNumberIsZero(rhs)) {
1338    decNumberZero(res);                 // prepare for Infinity
1339    res->bits=DECNEG|DECINF;            // -Infinity
1340    status|=DEC_Division_by_zero;       // as per 754
1341    }
1342   else { // finite non-zero
1343    Int ae=rhs->exponent+rhs->digits-1; // adjusted exponent
1344    if (set->digits>=10) decNumberFromInt32(res, ae);  // lay it out
1345     else {
1346      decNumber buft[D2N(10)];          // temporary number
1347      decNumber *t=buft;                // ..
1348      decNumberFromInt32(t, ae);        // lay it out
1349      decNumberPlus(res, t, set);       // round as necessary
1350      }
1351    }
1352
1353  if (status!=0) decStatus(res, status, set);
1354  return res;
1355  } // decNumberLogB
1356
1357/* ------------------------------------------------------------------ */
1358/* decNumberLog10 -- logarithm in base 10                             */
1359/*                                                                    */
1360/*   This computes C = log10(A)                                       */
1361/*                                                                    */
1362/*   res is C, the result.  C may be A                                */
1363/*   rhs is A                                                         */
1364/*   set is the context; note that rounding mode has no effect        */
1365/*                                                                    */
1366/* C must have space for set->digits digits.                          */
1367/*                                                                    */
1368/* Notable cases:                                                     */
1369/*   A<0 -> Invalid                                                   */
1370/*   A=0 -> -Infinity (Exact)                                         */
1371/*   A=+Infinity -> +Infinity (Exact)                                 */
1372/*   A=10**n (if n is an integer) -> n (Exact)                        */
1373/*                                                                    */
1374/* Mathematical function restrictions apply (see above); a NaN is     */
1375/* returned with Invalid_operation if a restriction is violated.      */
1376/*                                                                    */
1377/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1378/* almost always be correctly rounded, but may be up to 1 ulp in      */
1379/* error in rare cases.                                               */
1380/* ------------------------------------------------------------------ */
1381/* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1382/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1383/* requested digits and t is the number of digits in the exponent     */
1384/* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1385/* fastpath in decLnOp.  The final division is done to the requested  */
1386/* precision.                                                         */
1387/* ------------------------------------------------------------------ */
1388decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1389                          decContext *set) {
1390  uInt status=0, ignore=0;         // status accumulators
1391  uInt needbytes;                  // for space calculations
1392  Int p;                           // working precision
1393  Int t;                           // digits in exponent of A
1394
1395  // buffers for a and b working decimals
1396  // (adjustment calculator, same size)
1397  decNumber bufa[D2N(DECBUFFER+2)];
1398  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
1399  decNumber *a=bufa;               // temporary a
1400  decNumber bufb[D2N(DECBUFFER+2)];
1401  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
1402  decNumber *b=bufb;               // temporary b
1403  decNumber bufw[D2N(10)];         // working 2-10 digit number
1404  decNumber *w=bufw;               // ..
1405  #if DECSUBSET
1406  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
1407  #endif
1408
1409  decContext aset;                 // working context
1410
1411  #if DECCHECK
1412  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1413  #endif
1414
1415  // Check restrictions; this is a math function; if not violated
1416  // then carry out the operation.
1417  if (!decCheckMath(rhs, set, &status)) do { // protect malloc
1418    #if DECSUBSET
1419    if (!set->extended) {
1420      // reduce operand and set lostDigits status, as needed
1421      if (rhs->digits>set->digits) {
1422        allocrhs=decRoundOperand(rhs, set, &status);
1423        if (allocrhs==NULL) break;
1424        rhs=allocrhs;
1425        }
1426      // special check in subset for rhs=0
1427      if (ISZERO(rhs)) {                // +/- zeros -> error
1428        status|=DEC_Invalid_operation;
1429        break;}
1430      } // extended=0
1431    #endif
1432
1433    decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
1434
1435    // handle exact powers of 10; only check if +ve finite
1436    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1437      Int residue=0;               // (no residue)
1438      uInt copystat=0;             // clean status
1439
1440      // round to a single digit...
1441      aset.digits=1;
1442      decCopyFit(w, rhs, &aset, &residue, &copystat); // copy & shorten
1443      // if exact and the digit is 1, rhs is a power of 10
1444      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1445        // the exponent, conveniently, is the power of 10; making
1446        // this the result needs a little care as it might not fit,
1447        // so first convert it into the working number, and then move
1448        // to res
1449        decNumberFromInt32(w, w->exponent);
1450        residue=0;
1451        decCopyFit(res, w, set, &residue, &status); // copy & round
1452        decFinish(res, set, &residue, &status);     // cleanup/set flags
1453        break;
1454        } // not a power of 10
1455      } // not a candidate for exact
1456
1457    // simplify the information-content calculation to use 'total
1458    // number of digits in a, including exponent' as compared to the
1459    // requested digits, as increasing this will only rarely cost an
1460    // iteration in ln(a) anyway
1461    t=6;                                // it can never be >6
1462
1463    // allocate space when needed...
1464    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1465    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1466    if (needbytes>sizeof(bufa)) {       // need malloc space
1467      allocbufa=(decNumber *)malloc(needbytes);
1468      if (allocbufa==NULL) {            // hopeless -- abandon
1469        status|=DEC_Insufficient_storage;
1470        break;}
1471      a=allocbufa;                      // use the allocated space
1472      }
1473    aset.digits=p;                      // as calculated
1474    aset.emax=DEC_MAX_MATH;             // usual bounds
1475    aset.emin=-DEC_MAX_MATH;            // ..
1476    aset.clamp=0;                       // and no concrete format
1477    decLnOp(a, rhs, &aset, &status);    // a=ln(rhs)
1478
1479    // skip the division if the result so far is infinite, NaN, or
1480    // zero, or there was an error; note NaN from sNaN needs copy
1481    if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1482    if (a->bits&DECSPECIAL || ISZERO(a)) {
1483      decNumberCopy(res, a);            // [will fit]
1484      break;}
1485
1486    // for ln(10) an extra 3 digits of precision are needed
1487    p=set->digits+3;
1488    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1489    if (needbytes>sizeof(bufb)) {       // need malloc space
1490      allocbufb=(decNumber *)malloc(needbytes);
1491      if (allocbufb==NULL) {            // hopeless -- abandon
1492        status|=DEC_Insufficient_storage;
1493        break;}
1494      b=allocbufb;                      // use the allocated space
1495      }
1496    decNumberZero(w);                   // set up 10...
1497    #if DECDPUN==1
1498    w->lsu[1]=1; w->lsu[0]=0;           // ..
1499    #else
1500    w->lsu[0]=10;                       // ..
1501    #endif
1502    w->digits=2;                        // ..
1503
1504    aset.digits=p;
1505    decLnOp(b, w, &aset, &ignore);      // b=ln(10)
1506
1507    aset.digits=set->digits;            // for final divide
1508    decDivideOp(res, a, b, &aset, DIVIDE, &status); // into result
1509    } while(0);                         // [for break]
1510
1511  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
1512  if (allocbufb!=NULL) free(allocbufb); // ..
1513  #if DECSUBSET
1514  if (allocrhs !=NULL) free(allocrhs);  // ..
1515  #endif
1516  // apply significant status
1517  if (status!=0) decStatus(res, status, set);
1518  #if DECCHECK
1519  decCheckInexact(res, set);
1520  #endif
1521  return res;
1522  } // decNumberLog10
1523
1524/* ------------------------------------------------------------------ */
1525/* decNumberMax -- compare two Numbers and return the maximum         */
1526/*                                                                    */
1527/*   This computes C = A ? B, returning the maximum by 754 rules      */
1528/*                                                                    */
1529/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1530/*   lhs is A                                                         */
1531/*   rhs is B                                                         */
1532/*   set is the context                                               */
1533/*                                                                    */
1534/* C must have space for set->digits digits.                          */
1535/* ------------------------------------------------------------------ */
1536decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1537                         const decNumber *rhs, decContext *set) {
1538  uInt status=0;                        // accumulator
1539  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1540  if (status!=0) decStatus(res, status, set);
1541  #if DECCHECK
1542  decCheckInexact(res, set);
1543  #endif
1544  return res;
1545  } // decNumberMax
1546
1547/* ------------------------------------------------------------------ */
1548/* decNumberMaxMag -- compare and return the maximum by magnitude     */
1549/*                                                                    */
1550/*   This computes C = A ? B, returning the maximum by 754 rules      */
1551/*                                                                    */
1552/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1553/*   lhs is A                                                         */
1554/*   rhs is B                                                         */
1555/*   set is the context                                               */
1556/*                                                                    */
1557/* C must have space for set->digits digits.                          */
1558/* ------------------------------------------------------------------ */
1559decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1560                         const decNumber *rhs, decContext *set) {
1561  uInt status=0;                        // accumulator
1562  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1563  if (status!=0) decStatus(res, status, set);
1564  #if DECCHECK
1565  decCheckInexact(res, set);
1566  #endif
1567  return res;
1568  } // decNumberMaxMag
1569
1570/* ------------------------------------------------------------------ */
1571/* decNumberMin -- compare two Numbers and return the minimum         */
1572/*                                                                    */
1573/*   This computes C = A ? B, returning the minimum by 754 rules      */
1574/*                                                                    */
1575/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1576/*   lhs is A                                                         */
1577/*   rhs is B                                                         */
1578/*   set is the context                                               */
1579/*                                                                    */
1580/* C must have space for set->digits digits.                          */
1581/* ------------------------------------------------------------------ */
1582decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1583                         const decNumber *rhs, decContext *set) {
1584  uInt status=0;                        // accumulator
1585  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1586  if (status!=0) decStatus(res, status, set);
1587  #if DECCHECK
1588  decCheckInexact(res, set);
1589  #endif
1590  return res;
1591  } // decNumberMin
1592
1593/* ------------------------------------------------------------------ */
1594/* decNumberMinMag -- compare and return the minimum by magnitude     */
1595/*                                                                    */
1596/*   This computes C = A ? B, returning the minimum by 754 rules      */
1597/*                                                                    */
1598/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1599/*   lhs is A                                                         */
1600/*   rhs is B                                                         */
1601/*   set is the context                                               */
1602/*                                                                    */
1603/* C must have space for set->digits digits.                          */
1604/* ------------------------------------------------------------------ */
1605decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1606                         const decNumber *rhs, decContext *set) {
1607  uInt status=0;                        // accumulator
1608  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1609  if (status!=0) decStatus(res, status, set);
1610  #if DECCHECK
1611  decCheckInexact(res, set);
1612  #endif
1613  return res;
1614  } // decNumberMinMag
1615
1616/* ------------------------------------------------------------------ */
1617/* decNumberMinus -- prefix minus operator                            */
1618/*                                                                    */
1619/*   This computes C = 0 - A                                          */
1620/*                                                                    */
1621/*   res is C, the result.  C may be A                                */
1622/*   rhs is A                                                         */
1623/*   set is the context                                               */
1624/*                                                                    */
1625/* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1626/* C must have space for set->digits digits.                          */
1627/* ------------------------------------------------------------------ */
1628/* Simply use AddOp for the subtract, which will do the necessary.    */
1629/* ------------------------------------------------------------------ */
1630decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1631                           decContext *set) {
1632  decNumber dzero;
1633  uInt status=0;                        // accumulator
1634
1635  #if DECCHECK
1636  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1637  #endif
1638
1639  decNumberZero(&dzero);                // make 0
1640  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1641  decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1642  if (status!=0) decStatus(res, status, set);
1643  #if DECCHECK
1644  decCheckInexact(res, set);
1645  #endif
1646  return res;
1647  } // decNumberMinus
1648
1649/* ------------------------------------------------------------------ */
1650/* decNumberNextMinus -- next towards -Infinity                       */
1651/*                                                                    */
1652/*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1653/*                                                                    */
1654/*   res is C, the result.  C may be A                                */
1655/*   rhs is A                                                         */
1656/*   set is the context                                               */
1657/*                                                                    */
1658/* This is a generalization of 754 NextDown.                          */
1659/* ------------------------------------------------------------------ */
1660decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1661                               decContext *set) {
1662  decNumber dtiny;                           // constant
1663  decContext workset=*set;                   // work
1664  uInt status=0;                             // accumulator
1665  #if DECCHECK
1666  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1667  #endif
1668
1669  // +Infinity is the special case
1670  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1671    decSetMaxValue(res, set);                // is +ve
1672    // there is no status to set
1673    return res;
1674    }
1675  decNumberZero(&dtiny);                     // start with 0
1676  dtiny.lsu[0]=1;                            // make number that is ..
1677  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
1678  workset.round=DEC_ROUND_FLOOR;
1679  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1680  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1681  if (status!=0) decStatus(res, status, set);
1682  return res;
1683  } // decNumberNextMinus
1684
1685/* ------------------------------------------------------------------ */
1686/* decNumberNextPlus -- next towards +Infinity                        */
1687/*                                                                    */
1688/*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1689/*                                                                    */
1690/*   res is C, the result.  C may be A                                */
1691/*   rhs is A                                                         */
1692/*   set is the context                                               */
1693/*                                                                    */
1694/* This is a generalization of 754 NextUp.                            */
1695/* ------------------------------------------------------------------ */
1696decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1697                              decContext *set) {
1698  decNumber dtiny;                           // constant
1699  decContext workset=*set;                   // work
1700  uInt status=0;                             // accumulator
1701  #if DECCHECK
1702  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1703  #endif
1704
1705  // -Infinity is the special case
1706  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1707    decSetMaxValue(res, set);
1708    res->bits=DECNEG;                        // negative
1709    // there is no status to set
1710    return res;
1711    }
1712  decNumberZero(&dtiny);                     // start with 0
1713  dtiny.lsu[0]=1;                            // make number that is ..
1714  dtiny.exponent=DEC_MIN_EMIN-1;             // .. smaller than tiniest
1715  workset.round=DEC_ROUND_CEILING;
1716  decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1717  status&=DEC_Invalid_operation|DEC_sNaN;    // only sNaN Invalid please
1718  if (status!=0) decStatus(res, status, set);
1719  return res;
1720  } // decNumberNextPlus
1721
1722/* ------------------------------------------------------------------ */
1723/* decNumberNextToward -- next towards rhs                            */
1724/*                                                                    */
1725/*   This computes C = A +/- infinitesimal, rounded towards           */
1726/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1727/*   modified during revision but dropped from 754-2008.              */
1728/*                                                                    */
1729/*   res is C, the result.  C may be A or B.                          */
1730/*   lhs is A                                                         */
1731/*   rhs is B                                                         */
1732/*   set is the context                                               */
1733/*                                                                    */
1734/* This is a generalization of 754-1985 NextAfter.                    */
1735/* ------------------------------------------------------------------ */
1736decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1737                                const decNumber *rhs, decContext *set) {
1738  decNumber dtiny;                           // constant
1739  decContext workset=*set;                   // work
1740  Int result;                                // ..
1741  uInt status=0;                             // accumulator
1742  #if DECCHECK
1743  if (decCheckOperands(res, lhs, rhs, set)) return res;
1744  #endif
1745
1746  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1747    decNaNs(res, lhs, rhs, set, &status);
1748    }
1749   else { // Is numeric, so no chance of sNaN Invalid, etc.
1750    result=decCompare(lhs, rhs, 0);     // sign matters
1751    if (result==BADINT) status|=DEC_Insufficient_storage; // rare
1752     else { // valid compare
1753      if (result==0) decNumberCopySign(res, lhs, rhs); // easy
1754       else { // differ: need NextPlus or NextMinus
1755        uByte sub;                      // add or subtract
1756        if (result<0) {                 // lhs<rhs, do nextplus
1757          // -Infinity is the special case
1758          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1759            decSetMaxValue(res, set);
1760            res->bits=DECNEG;           // negative
1761            return res;                 // there is no status to set
1762            }
1763          workset.round=DEC_ROUND_CEILING;
1764          sub=0;                        // add, please
1765          } // plus
1766         else {                         // lhs>rhs, do nextminus
1767          // +Infinity is the special case
1768          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1769            decSetMaxValue(res, set);
1770            return res;                 // there is no status to set
1771            }
1772          workset.round=DEC_ROUND_FLOOR;
1773          sub=DECNEG;                   // subtract, please
1774          } // minus
1775        decNumberZero(&dtiny);          // start with 0
1776        dtiny.lsu[0]=1;                 // make number that is ..
1777        dtiny.exponent=DEC_MIN_EMIN-1;  // .. smaller than tiniest
1778        decAddOp(res, lhs, &dtiny, &workset, sub, &status); // + or -
1779        // turn off exceptions if the result is a normal number
1780        // (including Nmin), otherwise let all status through
1781        if (decNumberIsNormal(res, set)) status=0;
1782        } // unequal
1783      } // compare OK
1784    } // numeric
1785  if (status!=0) decStatus(res, status, set);
1786  return res;
1787  } // decNumberNextToward
1788
1789/* ------------------------------------------------------------------ */
1790/* decNumberOr -- OR two Numbers, digitwise                           */
1791/*                                                                    */
1792/*   This computes C = A | B                                          */
1793/*                                                                    */
1794/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1795/*   lhs is A                                                         */
1796/*   rhs is B                                                         */
1797/*   set is the context (used for result length and error report)     */
1798/*                                                                    */
1799/* C must have space for set->digits digits.                          */
1800/*                                                                    */
1801/* Logical function restrictions apply (see above); a NaN is          */
1802/* returned with Invalid_operation if a restriction is violated.      */
1803/* ------------------------------------------------------------------ */
1804decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1805                        const decNumber *rhs, decContext *set) {
1806  const Unit *ua, *ub;                  // -> operands
1807  const Unit *msua, *msub;              // -> operand msus
1808  Unit  *uc, *msuc;                     // -> result and its msu
1809  Int   msudigs;                        // digits in res msu
1810  #if DECCHECK
1811  if (decCheckOperands(res, lhs, rhs, set)) return res;
1812  #endif
1813
1814  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1815   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1816    decStatus(res, DEC_Invalid_operation, set);
1817    return res;
1818    }
1819  // operands are valid
1820  ua=lhs->lsu;                          // bottom-up
1821  ub=rhs->lsu;                          // ..
1822  uc=res->lsu;                          // ..
1823  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
1824  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
1825  msuc=uc+D2U(set->digits)-1;           // -> msu of result
1826  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
1827  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
1828    Unit a, b;                          // extract units
1829    if (ua>msua) a=0;
1830     else a=*ua;
1831    if (ub>msub) b=0;
1832     else b=*ub;
1833    *uc=0;                              // can now write back
1834    if (a|b) {                          // maybe 1 bits to examine
1835      Int i, j;
1836      // This loop could be unrolled and/or use BIN2BCD tables
1837      for (i=0; i<DECDPUN; i++) {
1838        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     // effect OR
1839        j=a%10;
1840        a=a/10;
1841        j|=b%10;
1842        b=b/10;
1843        if (j>1) {
1844          decStatus(res, DEC_Invalid_operation, set);
1845          return res;
1846          }
1847        if (uc==msuc && i==msudigs-1) break;      // just did final digit
1848        } // each digit
1849      } // non-zero
1850    } // each unit
1851  // [here uc-1 is the msu of the result]
1852  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1853  res->exponent=0;                      // integer
1854  res->bits=0;                          // sign=0
1855  return res;  // [no status to set]
1856  } // decNumberOr
1857
1858/* ------------------------------------------------------------------ */
1859/* decNumberPlus -- prefix plus operator                              */
1860/*                                                                    */
1861/*   This computes C = 0 + A                                          */
1862/*                                                                    */
1863/*   res is C, the result.  C may be A                                */
1864/*   rhs is A                                                         */
1865/*   set is the context                                               */
1866/*                                                                    */
1867/* See also decNumberCopy for a quiet bitwise version of this.        */
1868/* C must have space for set->digits digits.                          */
1869/* ------------------------------------------------------------------ */
1870/* This simply uses AddOp; Add will take fast path after preparing A. */
1871/* Performance is a concern here, as this routine is often used to    */
1872/* check operands and apply rounding and overflow/underflow testing.  */
1873/* ------------------------------------------------------------------ */
1874decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1875                          decContext *set) {
1876  decNumber dzero;
1877  uInt status=0;                        // accumulator
1878  #if DECCHECK
1879  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1880  #endif
1881
1882  decNumberZero(&dzero);                // make 0
1883  dzero.exponent=rhs->exponent;         // [no coefficient expansion]
1884  decAddOp(res, &dzero, rhs, set, 0, &status);
1885  if (status!=0) decStatus(res, status, set);
1886  #if DECCHECK
1887  decCheckInexact(res, set);
1888  #endif
1889  return res;
1890  } // decNumberPlus
1891
1892/* ------------------------------------------------------------------ */
1893/* decNumberMultiply -- multiply two Numbers                          */
1894/*                                                                    */
1895/*   This computes C = A x B                                          */
1896/*                                                                    */
1897/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1898/*   lhs is A                                                         */
1899/*   rhs is B                                                         */
1900/*   set is the context                                               */
1901/*                                                                    */
1902/* C must have space for set->digits digits.                          */
1903/* ------------------------------------------------------------------ */
1904decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1905                              const decNumber *rhs, decContext *set) {
1906  uInt status=0;                   // accumulator
1907  decMultiplyOp(res, lhs, rhs, set, &status);
1908  if (status!=0) decStatus(res, status, set);
1909  #if DECCHECK
1910  decCheckInexact(res, set);
1911  #endif
1912  return res;
1913  } // decNumberMultiply
1914
1915/* ------------------------------------------------------------------ */
1916/* decNumberPower -- raise a number to a power                        */
1917/*                                                                    */
1918/*   This computes C = A ** B                                         */
1919/*                                                                    */
1920/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1921/*   lhs is A                                                         */
1922/*   rhs is B                                                         */
1923/*   set is the context                                               */
1924/*                                                                    */
1925/* C must have space for set->digits digits.                          */
1926/*                                                                    */
1927/* Mathematical function restrictions apply (see above); a NaN is     */
1928/* returned with Invalid_operation if a restriction is violated.      */
1929/*                                                                    */
1930/* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1931/* restrictions on A and the context are relaxed to the usual bounds, */
1932/* for compatibility with the earlier (integer power only) version    */
1933/* of this function.                                                  */
1934/*                                                                    */
1935/* When B is an integer, the result may be exact, even if rounded.    */
1936/*                                                                    */
1937/* The final result is rounded according to the context; it will      */
1938/* almost always be correctly rounded, but may be up to 1 ulp in      */
1939/* error in rare cases.                                               */
1940/* ------------------------------------------------------------------ */
1941decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1942                           const decNumber *rhs, decContext *set) {
1943  #if DECSUBSET
1944  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
1945  decNumber *allocrhs=NULL;        // .., rhs
1946  #endif
1947  decNumber *allocdac=NULL;        // -> allocated acc buffer, iff used
1948  decNumber *allocinv=NULL;        // -> allocated 1/x buffer, iff used
1949  Int   reqdigits=set->digits;     // requested DIGITS
1950  Int   n;                         // rhs in binary
1951  Flag  rhsint=0;                  // 1 if rhs is an integer
1952  Flag  useint=0;                  // 1 if can use integer calculation
1953  Flag  isoddint=0;                // 1 if rhs is an integer and odd
1954  Int   i;                         // work
1955  #if DECSUBSET
1956  Int   dropped;                   // ..
1957  #endif
1958  uInt  needbytes;                 // buffer size needed
1959  Flag  seenbit;                   // seen a bit while powering
1960  Int   residue=0;                 // rounding residue
1961  uInt  status=0;                  // accumulators
1962  uByte bits=0;                    // result sign if errors
1963  decContext aset;                 // working context
1964  decNumber dnOne;                 // work value 1...
1965  // local accumulator buffer [a decNumber, with digits+elength+1 digits]
1966  decNumber dacbuff[D2N(DECBUFFER+9)];
1967  decNumber *dac=dacbuff;          // -> result accumulator
1968  // same again for possible 1/lhs calculation
1969  decNumber invbuff[D2N(DECBUFFER+9)];
1970
1971  #if DECCHECK
1972  if (decCheckOperands(res, lhs, rhs, set)) return res;
1973  #endif
1974
1975  do {                             // protect allocated storage
1976    #if DECSUBSET
1977    if (!set->extended) { // reduce operands and set status, as needed
1978      if (lhs->digits>reqdigits) {
1979        alloclhs=decRoundOperand(lhs, set, &status);
1980        if (alloclhs==NULL) break;
1981        lhs=alloclhs;
1982        }
1983      if (rhs->digits>reqdigits) {
1984        allocrhs=decRoundOperand(rhs, set, &status);
1985        if (allocrhs==NULL) break;
1986        rhs=allocrhs;
1987        }
1988      }
1989    #endif
1990    // [following code does not require input rounding]
1991
1992    // handle NaNs and rhs Infinity (lhs infinity is harder)
1993    if (SPECIALARGS) {
1994      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { // NaNs
1995        decNaNs(res, lhs, rhs, set, &status);
1996        break;}
1997      if (decNumberIsInfinite(rhs)) {   // rhs Infinity
1998        Flag rhsneg=rhs->bits&DECNEG;   // save rhs sign
1999        if (decNumberIsNegative(lhs)    // lhs<0
2000         && !decNumberIsZero(lhs))      // ..
2001          status|=DEC_Invalid_operation;
2002         else {                         // lhs >=0
2003          decNumberZero(&dnOne);        // set up 1
2004          dnOne.lsu[0]=1;
2005          decNumberCompare(dac, lhs, &dnOne, set); // lhs ? 1
2006          decNumberZero(res);           // prepare for 0/1/Infinity
2007          if (decNumberIsNegative(dac)) {    // lhs<1
2008            if (rhsneg) res->bits|=DECINF;   // +Infinity [else is +0]
2009            }
2010           else if (dac->lsu[0]==0) {        // lhs=1
2011            // 1**Infinity is inexact, so return fully-padded 1.0000
2012            Int shift=set->digits-1;
2013            *res->lsu=1;                     // was 0, make int 1
2014            res->digits=decShiftToMost(res->lsu, 1, shift);
2015            res->exponent=-shift;            // make 1.0000...
2016            status|=DEC_Inexact|DEC_Rounded; // deemed inexact
2017            }
2018           else {                            // lhs>1
2019            if (!rhsneg) res->bits|=DECINF;  // +Infinity [else is +0]
2020            }
2021          } // lhs>=0
2022        break;}
2023      // [lhs infinity drops through]
2024      } // specials
2025
2026    // Original rhs may be an integer that fits and is in range
2027    n=decGetInt(rhs);
2028    if (n!=BADINT) {                    // it is an integer
2029      rhsint=1;                         // record the fact for 1**n
2030      isoddint=(Flag)n&1;               // [works even if big]
2031      if (n!=BIGEVEN && n!=BIGODD)      // can use integer path?
2032        useint=1;                       // looks good
2033      }
2034
2035    if (decNumberIsNegative(lhs)        // -x ..
2036      && isoddint) bits=DECNEG;         // .. to an odd power
2037
2038    // handle LHS infinity
2039    if (decNumberIsInfinite(lhs)) {     // [NaNs already handled]
2040      uByte rbits=rhs->bits;            // save
2041      decNumberZero(res);               // prepare
2042      if (n==0) *res->lsu=1;            // [-]Inf**0 => 1
2043       else {
2044        // -Inf**nonint -> error
2045        if (!rhsint && decNumberIsNegative(lhs)) {
2046          status|=DEC_Invalid_operation;     // -Inf**nonint is error
2047          break;}
2048        if (!(rbits & DECNEG)) bits|=DECINF; // was not a **-n
2049        // [otherwise will be 0 or -0]
2050        res->bits=bits;
2051        }
2052      break;}
2053
2054    // similarly handle LHS zero
2055    if (decNumberIsZero(lhs)) {
2056      if (n==0) {                            // 0**0 => Error
2057        #if DECSUBSET
2058        if (!set->extended) {                // [unless subset]
2059          decNumberZero(res);
2060          *res->lsu=1;                       // return 1
2061          break;}
2062        #endif
2063        status|=DEC_Invalid_operation;
2064        }
2065       else {                                // 0**x
2066        uByte rbits=rhs->bits;               // save
2067        if (rbits & DECNEG) {                // was a 0**(-n)
2068          #if DECSUBSET
2069          if (!set->extended) {              // [bad if subset]
2070            status|=DEC_Invalid_operation;
2071            break;}
2072          #endif
2073          bits|=DECINF;
2074          }
2075        decNumberZero(res);                  // prepare
2076        // [otherwise will be 0 or -0]
2077        res->bits=bits;
2078        }
2079      break;}
2080
2081    // here both lhs and rhs are finite; rhs==0 is handled in the
2082    // integer path.  Next handle the non-integer cases
2083    if (!useint) {                      // non-integral rhs
2084      // any -ve lhs is bad, as is either operand or context out of
2085      // bounds
2086      if (decNumberIsNegative(lhs)) {
2087        status|=DEC_Invalid_operation;
2088        break;}
2089      if (decCheckMath(lhs, set, &status)
2090       || decCheckMath(rhs, set, &status)) break; // variable status
2091
2092      decContextDefault(&aset, DEC_INIT_DECIMAL64); // clean context
2093      aset.emax=DEC_MAX_MATH;           // usual bounds
2094      aset.emin=-DEC_MAX_MATH;          // ..
2095      aset.clamp=0;                     // and no concrete format
2096
2097      // calculate the result using exp(ln(lhs)*rhs), which can
2098      // all be done into the accumulator, dac.  The precision needed
2099      // is enough to contain the full information in the lhs (which
2100      // is the total digits, including exponent), or the requested
2101      // precision, if larger, + 4; 6 is used for the exponent
2102      // maximum length, and this is also used when it is shorter
2103      // than the requested digits as it greatly reduces the >0.5 ulp
2104      // cases at little cost (because Ln doubles digits each
2105      // iteration so a few extra digits rarely causes an extra
2106      // iteration)
2107      aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2108      } // non-integer rhs
2109
2110     else { // rhs is in-range integer
2111      if (n==0) {                       // x**0 = 1
2112        // (0**0 was handled above)
2113        decNumberZero(res);             // result=1
2114        *res->lsu=1;                    // ..
2115        break;}
2116      // rhs is a non-zero integer
2117      if (n<0) n=-n;                    // use abs(n)
2118
2119      aset=*set;                        // clone the context
2120      aset.round=DEC_ROUND_HALF_EVEN;   // internally use balanced
2121      // calculate the working DIGITS
2122      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2123      #if DECSUBSET
2124      if (!set->extended) aset.digits--;     // use classic precision
2125      #endif
2126      // it's an error if this is more than can be handled
2127      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2128      } // integer path
2129
2130    // aset.digits is the count of digits for the accumulator needed
2131    // if accumulator is too long for local storage, then allocate
2132    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2133    // [needbytes also used below if 1/lhs needed]
2134    if (needbytes>sizeof(dacbuff)) {
2135      allocdac=(decNumber *)malloc(needbytes);
2136      if (allocdac==NULL) {   // hopeless -- abandon
2137        status|=DEC_Insufficient_storage;
2138        break;}
2139      dac=allocdac;           // use the allocated space
2140      }
2141    // here, aset is set up and accumulator is ready for use
2142
2143    if (!useint) {                           // non-integral rhs
2144      // x ** y; special-case x=1 here as it will otherwise always
2145      // reduce to integer 1; decLnOp has a fastpath which detects
2146      // the case of x=1
2147      decLnOp(dac, lhs, &aset, &status);     // dac=ln(lhs)
2148      // [no error possible, as lhs 0 already handled]
2149      if (ISZERO(dac)) {                     // x==1, 1.0, etc.
2150        // need to return fully-padded 1.0000 etc., but rhsint->1
2151        *dac->lsu=1;                         // was 0, make int 1
2152        if (!rhsint) {                       // add padding
2153          Int shift=set->digits-1;
2154          dac->digits=decShiftToMost(dac->lsu, 1, shift);
2155          dac->exponent=-shift;              // make 1.0000...
2156          status|=DEC_Inexact|DEC_Rounded;   // deemed inexact
2157          }
2158        }
2159       else {
2160        decMultiplyOp(dac, dac, rhs, &aset, &status);  // dac=dac*rhs
2161        decExpOp(dac, dac, &aset, &status);            // dac=exp(dac)
2162        }
2163      // and drop through for final rounding
2164      } // non-integer rhs
2165
2166     else {                             // carry on with integer
2167      decNumberZero(dac);               // acc=1
2168      *dac->lsu=1;                      // ..
2169
2170      // if a negative power the constant 1 is needed, and if not subset
2171      // invert the lhs now rather than inverting the result later
2172      if (decNumberIsNegative(rhs)) {   // was a **-n [hence digits>0]
2173        decNumber *inv=invbuff;         // asssume use fixed buffer
2174        decNumberCopy(&dnOne, dac);     // dnOne=1;  [needed now or later]
2175        #if DECSUBSET
2176        if (set->extended) {            // need to calculate 1/lhs
2177        #endif
2178          // divide lhs into 1, putting result in dac [dac=1/dac]
2179          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2180          // now locate or allocate space for the inverted lhs
2181          if (needbytes>sizeof(invbuff)) {
2182            allocinv=(decNumber *)malloc(needbytes);
2183            if (allocinv==NULL) {       // hopeless -- abandon
2184              status|=DEC_Insufficient_storage;
2185              break;}
2186            inv=allocinv;               // use the allocated space
2187            }
2188          // [inv now points to big-enough buffer or allocated storage]
2189          decNumberCopy(inv, dac);      // copy the 1/lhs
2190          decNumberCopy(dac, &dnOne);   // restore acc=1
2191          lhs=inv;                      // .. and go forward with new lhs
2192        #if DECSUBSET
2193          }
2194        #endif
2195        }
2196
2197      // Raise-to-the-power loop...
2198      seenbit=0;                   // set once a 1-bit is encountered
2199      for (i=1;;i++){              // for each bit [top bit ignored]
2200        // abandon if had overflow or terminal underflow
2201        if (status & (DEC_Overflow|DEC_Underflow)) { // interesting?
2202          if (status&DEC_Overflow || ISZERO(dac)) break;
2203          }
2204        // [the following two lines revealed an optimizer bug in a C++
2205        // compiler, with symptom: 5**3 -> 25, when n=n+n was used]
2206        n=n<<1;                    // move next bit to testable position
2207        if (n<0) {                 // top bit is set
2208          seenbit=1;               // OK, significant bit seen
2209          decMultiplyOp(dac, dac, lhs, &aset, &status); // dac=dac*x
2210          }
2211        if (i==31) break;          // that was the last bit
2212        if (!seenbit) continue;    // no need to square 1
2213        decMultiplyOp(dac, dac, dac, &aset, &status); // dac=dac*dac [square]
2214        } /*i*/ // 32 bits
2215
2216      // complete internal overflow or underflow processing
2217      if (status & (DEC_Overflow|DEC_Underflow)) {
2218        #if DECSUBSET
2219        // If subset, and power was negative, reverse the kind of -erflow
2220        // [1/x not yet done]
2221        if (!set->extended && decNumberIsNegative(rhs)) {
2222          if (status & DEC_Overflow)
2223            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2224           else { // trickier -- Underflow may or may not be set
2225            status&=~(DEC_Underflow | DEC_Subnormal); // [one or both]
2226            status|=DEC_Overflow;
2227            }
2228          }
2229        #endif
2230        dac->bits=(dac->bits & ~DECNEG) | bits; // force correct sign
2231        // round subnormals [to set.digits rather than aset.digits]
2232        // or set overflow result similarly as required
2233        decFinalize(dac, set, &residue, &status);
2234        decNumberCopy(res, dac);   // copy to result (is now OK length)
2235        break;
2236        }
2237
2238      #if DECSUBSET
2239      if (!set->extended &&                  // subset math
2240          decNumberIsNegative(rhs)) {        // was a **-n [hence digits>0]
2241        // so divide result into 1 [dac=1/dac]
2242        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2243        }
2244      #endif
2245      } // rhs integer path
2246
2247    // reduce result to the requested length and copy to result
2248    decCopyFit(res, dac, set, &residue, &status);
2249    decFinish(res, set, &residue, &status);  // final cleanup
2250    #if DECSUBSET
2251    if (!set->extended) decTrim(res, set, 0, 1, &dropped); // trailing zeros
2252    #endif
2253    } while(0);                         // end protected
2254
2255  if (allocdac!=NULL) free(allocdac);   // drop any storage used
2256  if (allocinv!=NULL) free(allocinv);   // ..
2257  #if DECSUBSET
2258  if (alloclhs!=NULL) free(alloclhs);   // ..
2259  if (allocrhs!=NULL) free(allocrhs);   // ..
2260  #endif
2261  if (status!=0) decStatus(res, status, set);
2262  #if DECCHECK
2263  decCheckInexact(res, set);
2264  #endif
2265  return res;
2266  } // decNumberPower
2267
2268/* ------------------------------------------------------------------ */
2269/* decNumberQuantize -- force exponent to requested value             */
2270/*                                                                    */
2271/*   This computes C = op(A, B), where op adjusts the coefficient     */
2272/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2273/*   of C has exponent of B.  The numerical value of C will equal A,  */
2274/*   except for the effects of any rounding that occurred.            */
2275/*                                                                    */
2276/*   res is C, the result.  C may be A or B                           */
2277/*   lhs is A, the number to adjust                                   */
2278/*   rhs is B, the number with exponent to match                      */
2279/*   set is the context                                               */
2280/*                                                                    */
2281/* C must have space for set->digits digits.                          */
2282/*                                                                    */
2283/* Unless there is an error or the result is infinite, the exponent   */
2284/* after the operation is guaranteed to be equal to that of B.        */
2285/* ------------------------------------------------------------------ */
2286decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2287                              const decNumber *rhs, decContext *set) {
2288  uInt status=0;                        // accumulator
2289  decQuantizeOp(res, lhs, rhs, set, 1, &status);
2290  if (status!=0) decStatus(res, status, set);
2291  return res;
2292  } // decNumberQuantize
2293
2294/* ------------------------------------------------------------------ */
2295/* decNumberReduce -- remove trailing zeros                           */
2296/*                                                                    */
2297/*   This computes C = 0 + A, and normalizes the result               */
2298/*                                                                    */
2299/*   res is C, the result.  C may be A                                */
2300/*   rhs is A                                                         */
2301/*   set is the context                                               */
2302/*                                                                    */
2303/* C must have space for set->digits digits.                          */
2304/* ------------------------------------------------------------------ */
2305// Previously known as Normalize
2306decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2307                               decContext *set) {
2308  return decNumberReduce(res, rhs, set);
2309  } // decNumberNormalize
2310
2311decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2312                            decContext *set) {
2313  #if DECSUBSET
2314  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2315  #endif
2316  uInt status=0;                   // as usual
2317  Int  residue=0;                  // as usual
2318  Int  dropped;                    // work
2319
2320  #if DECCHECK
2321  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2322  #endif
2323
2324  do {                             // protect allocated storage
2325    #if DECSUBSET
2326    if (!set->extended) {
2327      // reduce operand and set lostDigits status, as needed
2328      if (rhs->digits>set->digits) {
2329        allocrhs=decRoundOperand(rhs, set, &status);
2330        if (allocrhs==NULL) break;
2331        rhs=allocrhs;
2332        }
2333      }
2334    #endif
2335    // [following code does not require input rounding]
2336
2337    // Infinities copy through; NaNs need usual treatment
2338    if (decNumberIsNaN(rhs)) {
2339      decNaNs(res, rhs, NULL, set, &status);
2340      break;
2341      }
2342
2343    // reduce result to the requested length and copy to result
2344    decCopyFit(res, rhs, set, &residue, &status); // copy & round
2345    decFinish(res, set, &residue, &status);       // cleanup/set flags
2346    decTrim(res, set, 1, 0, &dropped);            // normalize in place
2347                                                  // [may clamp]
2348    } while(0);                              // end protected
2349
2350  #if DECSUBSET
2351  if (allocrhs !=NULL) free(allocrhs);       // ..
2352  #endif
2353  if (status!=0) decStatus(res, status, set);// then report status
2354  return res;
2355  } // decNumberReduce
2356
2357/* ------------------------------------------------------------------ */
2358/* decNumberRescale -- force exponent to requested value              */
2359/*                                                                    */
2360/*   This computes C = op(A, B), where op adjusts the coefficient     */
2361/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2362/*   of C has the value B.  The numerical value of C will equal A,    */
2363/*   except for the effects of any rounding that occurred.            */
2364/*                                                                    */
2365/*   res is C, the result.  C may be A or B                           */
2366/*   lhs is A, the number to adjust                                   */
2367/*   rhs is B, the requested exponent                                 */
2368/*   set is the context                                               */
2369/*                                                                    */
2370/* C must have space for set->digits digits.                          */
2371/*                                                                    */
2372/* Unless there is an error or the result is infinite, the exponent   */
2373/* after the operation is guaranteed to be equal to B.                */
2374/* ------------------------------------------------------------------ */
2375decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2376                             const decNumber *rhs, decContext *set) {
2377  uInt status=0;                        // accumulator
2378  decQuantizeOp(res, lhs, rhs, set, 0, &status);
2379  if (status!=0) decStatus(res, status, set);
2380  return res;
2381  } // decNumberRescale
2382
2383/* ------------------------------------------------------------------ */
2384/* decNumberRemainder -- divide and return remainder                  */
2385/*                                                                    */
2386/*   This computes C = A % B                                          */
2387/*                                                                    */
2388/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2389/*   lhs is A                                                         */
2390/*   rhs is B                                                         */
2391/*   set is the context                                               */
2392/*                                                                    */
2393/* C must have space for set->digits digits.                          */
2394/* ------------------------------------------------------------------ */
2395decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2396                               const decNumber *rhs, decContext *set) {
2397  uInt status=0;                        // accumulator
2398  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2399  if (status!=0) decStatus(res, status, set);
2400  #if DECCHECK
2401  decCheckInexact(res, set);
2402  #endif
2403  return res;
2404  } // decNumberRemainder
2405
2406/* ------------------------------------------------------------------ */
2407/* decNumberRemainderNear -- divide and return remainder from nearest */
2408/*                                                                    */
2409/*   This computes C = A % B, where % is the IEEE remainder operator  */
2410/*                                                                    */
2411/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2412/*   lhs is A                                                         */
2413/*   rhs is B                                                         */
2414/*   set is the context                                               */
2415/*                                                                    */
2416/* C must have space for set->digits digits.                          */
2417/* ------------------------------------------------------------------ */
2418decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2419                                   const decNumber *rhs, decContext *set) {
2420  uInt status=0;                        // accumulator
2421  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2422  if (status!=0) decStatus(res, status, set);
2423  #if DECCHECK
2424  decCheckInexact(res, set);
2425  #endif
2426  return res;
2427  } // decNumberRemainderNear
2428
2429/* ------------------------------------------------------------------ */
2430/* decNumberRotate -- rotate the coefficient of a Number left/right   */
2431/*                                                                    */
2432/*   This computes C = A rot B  (in base ten and rotating set->digits */
2433/*   digits).                                                         */
2434/*                                                                    */
2435/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2436/*   lhs is A                                                         */
2437/*   rhs is B, the number of digits to rotate (-ve to right)          */
2438/*   set is the context                                               */
2439/*                                                                    */
2440/* The digits of the coefficient of A are rotated to the left (if B   */
2441/* is positive) or to the right (if B is negative) without adjusting  */
2442/* the exponent or the sign of A.  If lhs->digits is less than        */
2443/* set->digits the coefficient is padded with zeros on the left       */
2444/* before the rotate.  Any leading zeros in the result are removed    */
2445/* as usual.                                                          */
2446/*                                                                    */
2447/* B must be an integer (q=0) and in the range -set->digits through   */
2448/* +set->digits.                                                      */
2449/* C must have space for set->digits digits.                          */
2450/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2451/* B must be valid).  No status is set unless B is invalid or an      */
2452/* operand is an sNaN.                                                */
2453/* ------------------------------------------------------------------ */
2454decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2455                           const decNumber *rhs, decContext *set) {
2456  uInt status=0;              // accumulator
2457  Int  rotate;                // rhs as an Int
2458
2459  #if DECCHECK
2460  if (decCheckOperands(res, lhs, rhs, set)) return res;
2461  #endif
2462
2463  // NaNs propagate as normal
2464  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2465    decNaNs(res, lhs, rhs, set, &status);
2466   // rhs must be an integer
2467   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2468    status=DEC_Invalid_operation;
2469   else { // both numeric, rhs is an integer
2470    rotate=decGetInt(rhs);                   // [cannot fail]
2471    if (rotate==BADINT                       // something bad ..
2472     || rotate==BIGODD || rotate==BIGEVEN    // .. very big ..
2473     || abs(rotate)>set->digits)             // .. or out of range
2474      status=DEC_Invalid_operation;
2475     else {                                  // rhs is OK
2476      decNumberCopy(res, lhs);
2477      // convert -ve rotate to equivalent positive rotation
2478      if (rotate<0) rotate=set->digits+rotate;
2479      if (rotate!=0 && rotate!=set->digits   // zero or full rotation
2480       && !decNumberIsInfinite(res)) {       // lhs was infinite
2481        // left-rotate to do; 0 < rotate < set->digits
2482        uInt units, shift;                   // work
2483        uInt msudigits;                      // digits in result msu
2484        Unit *msu=res->lsu+D2U(res->digits)-1;    // current msu
2485        Unit *msumax=res->lsu+D2U(set->digits)-1; // rotation msu
2486        for (msu++; msu<=msumax; msu++) *msu=0;   // ensure high units=0
2487        res->digits=set->digits;                  // now full-length
2488        msudigits=MSUDIGITS(res->digits);         // actual digits in msu
2489
2490        // rotation here is done in-place, in three steps
2491        // 1. shift all to least up to one unit to unit-align final
2492        //    lsd [any digits shifted out are rotated to the left,
2493        //    abutted to the original msd (which may require split)]
2494        //
2495        //    [if there are no whole units left to rotate, the
2496        //    rotation is now complete]
2497        //
2498        // 2. shift to least, from below the split point only, so that
2499        //    the final msd is in the right place in its Unit [any
2500        //    digits shifted out will fit exactly in the current msu,
2501        //    left aligned, no split required]
2502        //
2503        // 3. rotate all the units by reversing left part, right
2504        //    part, and then whole
2505        //
2506        // example: rotate right 8 digits (2 units + 2), DECDPUN=3.
2507        //
2508        //   start: 00a bcd efg hij klm npq
2509        //
2510        //      1a  000 0ab cde fgh|ijk lmn [pq saved]
2511        //      1b  00p qab cde fgh|ijk lmn
2512        //
2513        //      2a  00p qab cde fgh|00i jkl [mn saved]
2514        //      2b  mnp qab cde fgh|00i jkl
2515        //
2516        //      3a  fgh cde qab mnp|00i jkl
2517        //      3b  fgh cde qab mnp|jkl 00i
2518        //      3c  00i jkl mnp qab cde fgh
2519
2520        // Step 1: amount to shift is the partial right-rotate count
2521        rotate=set->digits-rotate;      // make it right-rotate
2522        units=rotate/DECDPUN;           // whole units to rotate
2523        shift=rotate%DECDPUN;           // left-over digits count
2524        if (shift>0) {                  // not an exact number of units
2525          uInt save=res->lsu[0]%powers[shift];    // save low digit(s)
2526          decShiftToLeast(res->lsu, D2U(res->digits), shift);
2527          if (shift>msudigits) {        // msumax-1 needs >0 digits
2528            uInt rem=save%powers[shift-msudigits];// split save
2529            *msumax=(Unit)(save/powers[shift-msudigits]); // and insert
2530            *(msumax-1)=*(msumax-1)
2531                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); // ..
2532            }
2533           else { // all fits in msumax
2534            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); // [maybe *1]
2535            }
2536          } // digits shift needed
2537
2538        // If whole units to rotate...
2539        if (units>0) {                  // some to do
2540          // Step 2: the units to touch are the whole ones in rotate,
2541          //   if any, and the shift is DECDPUN-msudigits (which may be
2542          //   0, again)
2543          shift=DECDPUN-msudigits;
2544          if (shift>0) {                // not an exact number of units
2545            uInt save=res->lsu[0]%powers[shift];  // save low digit(s)
2546            decShiftToLeast(res->lsu, units, shift);
2547            *msumax=*msumax+(Unit)(save*powers[msudigits]);
2548            } // partial shift needed
2549
2550          // Step 3: rotate the units array using triple reverse
2551          // (reversing is easy and fast)
2552          decReverse(res->lsu+units, msumax);     // left part
2553          decReverse(res->lsu, res->lsu+units-1); // right part
2554          decReverse(res->lsu, msumax);           // whole
2555          } // whole units to rotate
2556        // the rotation may have left an undetermined number of zeros
2557        // on the left, so true length needs to be calculated
2558        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2559        } // rotate needed
2560      } // rhs OK
2561    } // numerics
2562  if (status!=0) decStatus(res, status, set);
2563  return res;
2564  } // decNumberRotate
2565
2566/* ------------------------------------------------------------------ */
2567/* decNumberSameQuantum -- test for equal exponents                   */
2568/*                                                                    */
2569/*   res is the result number, which will contain either 0 or 1       */
2570/*   lhs is a number to test                                          */
2571/*   rhs is the second (usually a pattern)                            */
2572/*                                                                    */
2573/* No errors are possible and no context is needed.                   */
2574/* ------------------------------------------------------------------ */
2575decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2576                                 const decNumber *rhs) {
2577  Unit ret=0;                      // return value
2578
2579  #if DECCHECK
2580  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2581  #endif
2582
2583  if (SPECIALARGS) {
2584    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2585     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2586     // [anything else with a special gives 0]
2587    }
2588   else if (lhs->exponent==rhs->exponent) ret=1;
2589
2590  decNumberZero(res);              // OK to overwrite an operand now
2591  *res->lsu=ret;
2592  return res;
2593  } // decNumberSameQuantum
2594
2595/* ------------------------------------------------------------------ */
2596/* decNumberScaleB -- multiply by a power of 10                       */
2597/*                                                                    */
2598/* This computes C = A x 10**B where B is an integer (q=0) with       */
2599/* maximum magnitude 2*(emax+digits)                                  */
2600/*                                                                    */
2601/*   res is C, the result.  C may be A or B                           */
2602/*   lhs is A, the number to adjust                                   */
2603/*   rhs is B, the requested power of ten to use                      */
2604/*   set is the context                                               */
2605/*                                                                    */
2606/* C must have space for set->digits digits.                          */
2607/*                                                                    */
2608/* The result may underflow or overflow.                              */
2609/* ------------------------------------------------------------------ */
2610decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2611                            const decNumber *rhs, decContext *set) {
2612  Int  reqexp;                // requested exponent change [B]
2613  uInt status=0;              // accumulator
2614  Int  residue;               // work
2615
2616  #if DECCHECK
2617  if (decCheckOperands(res, lhs, rhs, set)) return res;
2618  #endif
2619
2620  // Handle special values except lhs infinite
2621  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2622    decNaNs(res, lhs, rhs, set, &status);
2623    // rhs must be an integer
2624   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2625    status=DEC_Invalid_operation;
2626   else {
2627    // lhs is a number; rhs is a finite with q==0
2628    reqexp=decGetInt(rhs);                   // [cannot fail]
2629    // maximum range is larger than getInt can handle, so this is
2630    // more restrictive than the specification
2631    if (reqexp==BADINT                       // something bad ..
2632     || reqexp==BIGODD || reqexp==BIGEVEN    // it was huge
2633     || (abs(reqexp)+1)/2>(set->digits+set->emax)) // .. or out of range
2634      status=DEC_Invalid_operation;
2635     else {                                  // rhs is OK
2636      decNumberCopy(res, lhs);               // all done if infinite lhs
2637      if (!decNumberIsInfinite(res)) {       // prepare to scale
2638        Int exp=res->exponent;               // save for overflow test
2639        res->exponent+=reqexp;               // adjust the exponent
2640        if (((exp^reqexp)>=0)                // same sign ...
2641         && ((exp^res->exponent)<0)) {       // .. but result had different
2642          // the calculation overflowed, so force right treatment
2643          if (exp<0) res->exponent=DEC_MIN_EMIN-DEC_MAX_DIGITS;
2644           else      res->exponent=DEC_MAX_EMAX+1;
2645          }
2646        residue=0;
2647        decFinalize(res, set, &residue, &status); // final check
2648        } // finite LHS
2649      } // rhs OK
2650    } // rhs finite
2651  if (status!=0) decStatus(res, status, set);
2652  return res;
2653  } // decNumberScaleB
2654
2655/* ------------------------------------------------------------------ */
2656/* decNumberShift -- shift the coefficient of a Number left or right  */
2657/*                                                                    */
2658/*   This computes C = A << B or C = A >> -B  (in base ten).          */
2659/*                                                                    */
2660/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2661/*   lhs is A                                                         */
2662/*   rhs is B, the number of digits to shift (-ve to right)           */
2663/*   set is the context                                               */
2664/*                                                                    */
2665/* The digits of the coefficient of A are shifted to the left (if B   */
2666/* is positive) or to the right (if B is negative) without adjusting  */
2667/* the exponent or the sign of A.                                     */
2668/*                                                                    */
2669/* B must be an integer (q=0) and in the range -set->digits through   */
2670/* +set->digits.                                                      */
2671/* C must have space for set->digits digits.                          */
2672/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2673/* B must be valid).  No status is set unless B is invalid or an      */
2674/* operand is an sNaN.                                                */
2675/* ------------------------------------------------------------------ */
2676decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2677                           const decNumber *rhs, decContext *set) {
2678  uInt status=0;              // accumulator
2679  Int  shift;                 // rhs as an Int
2680
2681  #if DECCHECK
2682  if (decCheckOperands(res, lhs, rhs, set)) return res;
2683  #endif
2684
2685  // NaNs propagate as normal
2686  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2687    decNaNs(res, lhs, rhs, set, &status);
2688   // rhs must be an integer
2689   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2690    status=DEC_Invalid_operation;
2691   else { // both numeric, rhs is an integer
2692    shift=decGetInt(rhs);                    // [cannot fail]
2693    if (shift==BADINT                        // something bad ..
2694     || shift==BIGODD || shift==BIGEVEN      // .. very big ..
2695     || abs(shift)>set->digits)              // .. or out of range
2696      status=DEC_Invalid_operation;
2697     else {                                  // rhs is OK
2698      decNumberCopy(res, lhs);
2699      if (shift!=0 && !decNumberIsInfinite(res)) { // something to do
2700        if (shift>0) {                       // to left
2701          if (shift==set->digits) {          // removing all
2702            *res->lsu=0;                     // so place 0
2703            res->digits=1;                   // ..
2704            }
2705           else {                            //
2706            // first remove leading digits if necessary
2707            if (res->digits+shift>set->digits) {
2708              decDecap(res, res->digits+shift-set->digits);
2709              // that updated res->digits; may have gone to 1 (for a
2710              // single digit or for zero
2711              }
2712            if (res->digits>1 || *res->lsu)  // if non-zero..
2713              res->digits=decShiftToMost(res->lsu, res->digits, shift);
2714            } // partial left
2715          } // left
2716         else { // to right
2717          if (-shift>=res->digits) {         // discarding all
2718            *res->lsu=0;                     // so place 0
2719            res->digits=1;                   // ..
2720            }
2721           else {
2722            decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2723            res->digits-=(-shift);
2724            }
2725          } // to right
2726        } // non-0 non-Inf shift
2727      } // rhs OK
2728    } // numerics
2729  if (status!=0) decStatus(res, status, set);
2730  return res;
2731  } // decNumberShift
2732
2733/* ------------------------------------------------------------------ */
2734/* decNumberSquareRoot -- square root operator                        */
2735/*                                                                    */
2736/*   This computes C = squareroot(A)                                  */
2737/*                                                                    */
2738/*   res is C, the result.  C may be A                                */
2739/*   rhs is A                                                         */
2740/*   set is the context; note that rounding mode has no effect        */
2741/*                                                                    */
2742/* C must have space for set->digits digits.                          */
2743/* ------------------------------------------------------------------ */
2744/* This uses the following varying-precision algorithm in:            */
2745/*                                                                    */
2746/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2747/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2748/*   pp229-237, ACM, September 1985.                                  */
2749/*                                                                    */
2750/* The square-root is calculated using Newton's method, after which   */
2751/* a check is made to ensure the result is correctly rounded.         */
2752/*                                                                    */
2753/* % [Reformatted original Numerical Turing source code follows.]     */
2754/* function sqrt(x : real) : real                                     */
2755/* % sqrt(x) returns the properly rounded approximation to the square */
2756/* % root of x, in the precision of the calling environment, or it    */
2757/* % fails if x < 0.                                                  */
2758/* % t e hull and a abrham, august, 1984                              */
2759/* if x <= 0 then                                                     */
2760/*   if x < 0 then                                                    */
2761/*     assert false                                                   */
2762/*   else                                                             */
2763/*     result 0                                                       */
2764/*   end if                                                           */
2765/* end if                                                             */
2766/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2767/* var e := getexp(x)     % exponent part of x                        */
2768/* var approx : real                                                  */
2769/* if e mod 2 = 0  then                                               */
2770/*   approx := .259 + .819 * f   % approx to root of f                */
2771/* else                                                               */
2772/*   f := f/l0                   % adjustments                        */
2773/*   e := e + 1                  %   for odd                          */
2774/*   approx := .0819 + 2.59 * f  %   exponent                         */
2775/* end if                                                             */
2776/*                                                                    */
2777/* var p:= 3                                                          */
2778/* const maxp := currentprecision + 2                                 */
2779/* loop                                                               */
2780/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2781/*   precision p                                                      */
2782/*   approx := .5 * (approx + f/approx)                               */
2783/*   exit when p = maxp                                               */
2784/* end loop                                                           */
2785/*                                                                    */
2786/* % approx is now within 1 ulp of the properly rounded square root   */
2787/* % of f; to ensure proper rounding, compare squares of (approx -    */
2788/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2789/* p := currentprecision                                              */
2790/* begin                                                              */
2791/*   precision p + 2                                                  */
2792/*   const approxsubhalf := approx - setexp(.5, -p)                   */
2793/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2794/*     approx := approx - setexp(.l, -p + 1)                          */
2795/*   else                                                             */
2796/*     const approxaddhalf := approx + setexp(.5, -p)                 */
2797/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2798/*       approx := approx + setexp(.l, -p + 1)                        */
2799/*     end if                                                         */
2800/*   end if                                                           */
2801/* end                                                                */
2802/* result setexp(approx, e div 2)  % fix exponent                     */
2803/* end sqrt                                                           */
2804/* ------------------------------------------------------------------ */
2805decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2806                                decContext *set) {
2807  decContext workset, approxset;   // work contexts
2808  decNumber dzero;                 // used for constant zero
2809  Int  maxp;                       // largest working precision
2810  Int  workp;                      // working precision
2811  Int  residue=0;                  // rounding residue
2812  uInt status=0, ignore=0;         // status accumulators
2813  uInt rstatus;                    // ..
2814  Int  exp;                        // working exponent
2815  Int  ideal;                      // ideal (preferred) exponent
2816  Int  needbytes;                  // work
2817  Int  dropped;                    // ..
2818
2819  #if DECSUBSET
2820  decNumber *allocrhs=NULL;        // non-NULL if rounded rhs allocated
2821  #endif
2822  // buffer for f [needs +1 in case DECBUFFER 0]
2823  decNumber buff[D2N(DECBUFFER+1)];
2824  // buffer for a [needs +2 to match likely maxp]
2825  decNumber bufa[D2N(DECBUFFER+2)];
2826  // buffer for temporary, b [must be same size as a]
2827  decNumber bufb[D2N(DECBUFFER+2)];
2828  decNumber *allocbuff=NULL;       // -> allocated buff, iff allocated
2829  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
2830  decNumber *allocbufb=NULL;       // -> allocated bufb, iff allocated
2831  decNumber *f=buff;               // reduced fraction
2832  decNumber *a=bufa;               // approximation to result
2833  decNumber *b=bufb;               // intermediate result
2834  // buffer for temporary variable, up to 3 digits
2835  decNumber buft[D2N(3)];
2836  decNumber *t=buft;               // up-to-3-digit constant or work
2837
2838  #if DECCHECK
2839  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2840  #endif
2841
2842  do {                             // protect allocated storage
2843    #if DECSUBSET
2844    if (!set->extended) {
2845      // reduce operand and set lostDigits status, as needed
2846      if (rhs->digits>set->digits) {
2847        allocrhs=decRoundOperand(rhs, set, &status);
2848        if (allocrhs==NULL) break;
2849        // [Note: 'f' allocation below could reuse this buffer if
2850        // used, but as this is rare they are kept separate for clarity.]
2851        rhs=allocrhs;
2852        }
2853      }
2854    #endif
2855    // [following code does not require input rounding]
2856
2857    // handle infinities and NaNs
2858    if (SPECIALARG) {
2859      if (decNumberIsInfinite(rhs)) {         // an infinity
2860        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2861         else decNumberCopy(res, rhs);        // +Infinity
2862        }
2863       else decNaNs(res, rhs, NULL, set, &status); // a NaN
2864      break;
2865      }
2866
2867    // calculate the ideal (preferred) exponent [floor(exp/2)]
2868    // [It would be nicer to write: ideal=rhs->exponent>>1, but this
2869    // generates a compiler warning.  Generated code is the same.]
2870    ideal=(rhs->exponent&~1)/2;         // target
2871
2872    // handle zeros
2873    if (ISZERO(rhs)) {
2874      decNumberCopy(res, rhs);          // could be 0 or -0
2875      res->exponent=ideal;              // use the ideal [safe]
2876      // use decFinish to clamp any out-of-range exponent, etc.
2877      decFinish(res, set, &residue, &status);
2878      break;
2879      }
2880
2881    // any other -x is an oops
2882    if (decNumberIsNegative(rhs)) {
2883      status|=DEC_Invalid_operation;
2884      break;
2885      }
2886
2887    // space is needed for three working variables
2888    //   f -- the same precision as the RHS, reduced to 0.01->0.99...
2889    //   a -- Hull's approximation -- precision, when assigned, is
2890    //        currentprecision+1 or the input argument precision,
2891    //        whichever is larger (+2 for use as temporary)
2892    //   b -- intermediate temporary result (same size as a)
2893    // if any is too long for local storage, then allocate
2894    workp=MAXI(set->digits+1, rhs->digits);  // actual rounding precision
2895    workp=MAXI(workp, 7);                    // at least 7 for low cases
2896    maxp=workp+2;                            // largest working precision
2897
2898    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2899    if (needbytes>(Int)sizeof(buff)) {
2900      allocbuff=(decNumber *)malloc(needbytes);
2901      if (allocbuff==NULL) {  // hopeless -- abandon
2902        status|=DEC_Insufficient_storage;
2903        break;}
2904      f=allocbuff;            // use the allocated space
2905      }
2906    // a and b both need to be able to hold a maxp-length number
2907    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2908    if (needbytes>(Int)sizeof(bufa)) {            // [same applies to b]
2909      allocbufa=(decNumber *)malloc(needbytes);
2910      allocbufb=(decNumber *)malloc(needbytes);
2911      if (allocbufa==NULL || allocbufb==NULL) {   // hopeless
2912        status|=DEC_Insufficient_storage;
2913        break;}
2914      a=allocbufa;            // use the allocated spaces
2915      b=allocbufb;            // ..
2916      }
2917
2918    // copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1
2919    decNumberCopy(f, rhs);
2920    exp=f->exponent+f->digits;               // adjusted to Hull rules
2921    f->exponent=-(f->digits);                // to range
2922
2923    // set up working context
2924    decContextDefault(&workset, DEC_INIT_DECIMAL64);
2925    workset.emax=DEC_MAX_EMAX;
2926    workset.emin=DEC_MIN_EMIN;
2927
2928    // [Until further notice, no error is possible and status bits
2929    // (Rounded, etc.) should be ignored, not accumulated.]
2930
2931    // Calculate initial approximation, and allow for odd exponent
2932    workset.digits=workp;                    // p for initial calculation
2933    t->bits=0; t->digits=3;
2934    a->bits=0; a->digits=3;
2935    if ((exp & 1)==0) {                      // even exponent
2936      // Set t=0.259, a=0.819
2937      t->exponent=-3;
2938      a->exponent=-3;
2939      #if DECDPUN>=3
2940        t->lsu[0]=259;
2941        a->lsu[0]=819;
2942      #elif DECDPUN==2
2943        t->lsu[0]=59; t->lsu[1]=2;
2944        a->lsu[0]=19; a->lsu[1]=8;
2945      #else
2946        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2947        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2948      #endif
2949      }
2950     else {                                  // odd exponent
2951      // Set t=0.0819, a=2.59
2952      f->exponent--;                         // f=f/10
2953      exp++;                                 // e=e+1
2954      t->exponent=-4;
2955      a->exponent=-2;
2956      #if DECDPUN>=3
2957        t->lsu[0]=819;
2958        a->lsu[0]=259;
2959      #elif DECDPUN==2
2960        t->lsu[0]=19; t->lsu[1]=8;
2961        a->lsu[0]=59; a->lsu[1]=2;
2962      #else
2963        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2964        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2965      #endif
2966      }
2967
2968    decMultiplyOp(a, a, f, &workset, &ignore);    // a=a*f
2969    decAddOp(a, a, t, &workset, 0, &ignore);      // ..+t
2970    // [a is now the initial approximation for sqrt(f), calculated with
2971    // currentprecision, which is also a's precision.]
2972
2973    // the main calculation loop
2974    decNumberZero(&dzero);                   // make 0
2975    decNumberZero(t);                        // set t = 0.5
2976    t->lsu[0]=5;                             // ..
2977    t->exponent=-1;                          // ..
2978    workset.digits=3;                        // initial p
2979    for (; workset.digits<maxp;) {
2980      // set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]
2981      workset.digits=MINI(workset.digits*2-2, maxp);
2982      // a = 0.5 * (a + f/a)
2983      // [calculated at p then rounded to currentprecision]
2984      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); // b=f/a
2985      decAddOp(b, b, a, &workset, 0, &ignore);         // b=b+a
2986      decMultiplyOp(a, b, t, &workset, &ignore);       // a=b*0.5
2987      } // loop
2988
2989    // Here, 0.1 <= a < 1 [Hull], and a has maxp digits
2990    // now reduce to length, etc.; this needs to be done with a
2991    // having the correct exponent so as to handle subnormals
2992    // correctly
2993    approxset=*set;                          // get emin, emax, etc.
2994    approxset.round=DEC_ROUND_HALF_EVEN;
2995    a->exponent+=exp/2;                      // set correct exponent
2996    rstatus=0;                               // clear status
2997    residue=0;                               // .. and accumulator
2998    decCopyFit(a, a, &approxset, &residue, &rstatus);  // reduce (if needed)
2999    decFinish(a, &approxset, &residue, &rstatus);      // clean and finalize
3000
3001    // Overflow was possible if the input exponent was out-of-range,
3002    // in which case quit
3003    if (rstatus&DEC_Overflow) {
3004      status=rstatus;                        // use the status as-is
3005      decNumberCopy(res, a);                 // copy to result
3006      break;
3007      }
3008
3009    // Preserve status except Inexact/Rounded
3010    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3011
3012    // Carry out the Hull correction
3013    a->exponent-=exp/2;                      // back to 0.1->1
3014
3015    // a is now at final precision and within 1 ulp of the properly
3016    // rounded square root of f; to ensure proper rounding, compare
3017    // squares of (a - l/2 ulp) and (a + l/2 ulp) with f.
3018    // Here workset.digits=maxp and t=0.5, and a->digits determines
3019    // the ulp
3020    workset.digits--;                             // maxp-1 is OK now
3021    t->exponent=-a->digits-1;                     // make 0.5 ulp
3022    decAddOp(b, a, t, &workset, DECNEG, &ignore); // b = a - 0.5 ulp
3023    workset.round=DEC_ROUND_UP;
3024    decMultiplyOp(b, b, b, &workset, &ignore);    // b = mulru(b, b)
3025    decCompareOp(b, f, b, &workset, COMPARE, &ignore); // b ? f, reversed
3026    if (decNumberIsNegative(b)) {                 // f < b [i.e., b > f]
3027      // this is the more common adjustment, though both are rare
3028      t->exponent++;                              // make 1.0 ulp
3029      t->lsu[0]=1;                                // ..
3030      decAddOp(a, a, t, &workset, DECNEG, &ignore); // a = a - 1 ulp
3031      // assign to approx [round to length]
3032      approxset.emin-=exp/2;                      // adjust to match a
3033      approxset.emax-=exp/2;
3034      decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3035      }
3036     else {
3037      decAddOp(b, a, t, &workset, 0, &ignore);    // b = a + 0.5 ulp
3038      workset.round=DEC_ROUND_DOWN;
3039      decMultiplyOp(b, b, b, &workset, &ignore);  // b = mulrd(b, b)
3040      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   // b ? f
3041      if (decNumberIsNegative(b)) {               // b < f
3042        t->exponent++;                            // make 1.0 ulp
3043        t->lsu[0]=1;                              // ..
3044        decAddOp(a, a, t, &workset, 0, &ignore);  // a = a + 1 ulp
3045        // assign to approx [round to length]
3046        approxset.emin-=exp/2;                    // adjust to match a
3047        approxset.emax-=exp/2;
3048        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3049        }
3050      }
3051    // [no errors are possible in the above, and rounding/inexact during
3052    // estimation are irrelevant, so status was not accumulated]
3053
3054    // Here, 0.1 <= a < 1  (still), so adjust back
3055    a->exponent+=exp/2;                      // set correct exponent
3056
3057    // count droppable zeros [after any subnormal rounding] by
3058    // trimming a copy
3059    decNumberCopy(b, a);
3060    decTrim(b, set, 1, 1, &dropped);         // [drops trailing zeros]
3061
3062    // Set Inexact and Rounded.  The answer can only be exact if
3063    // it is short enough so that squaring it could fit in workp
3064    // digits, so this is the only (relatively rare) condition that
3065    // a careful check is needed
3066    if (b->digits*2-1 > workp) {             // cannot fit
3067      status|=DEC_Inexact|DEC_Rounded;
3068      }
3069     else {                                  // could be exact/unrounded
3070      uInt mstatus=0;                        // local status
3071      decMultiplyOp(b, b, b, &workset, &mstatus); // try the multiply
3072      if (mstatus&DEC_Overflow) {            // result just won't fit
3073        status|=DEC_Inexact|DEC_Rounded;
3074        }
3075       else {                                // plausible
3076        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); // b ? rhs
3077        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; // not equal
3078         else {                              // is Exact
3079          // here, dropped is the count of trailing zeros in 'a'
3080          // use closest exponent to ideal...
3081          Int todrop=ideal-a->exponent;      // most that can be dropped
3082          if (todrop<0) status|=DEC_Rounded; // ideally would add 0s
3083           else {                            // unrounded
3084            // there are some to drop, but emax may not allow all
3085            Int maxexp=set->emax-set->digits+1;
3086            Int maxdrop=maxexp-a->exponent;
3087            if (todrop>maxdrop && set->clamp) { // apply clamping
3088              todrop=maxdrop;
3089              status|=DEC_Clamped;
3090              }
3091            if (dropped<todrop) {            // clamp to those available
3092              todrop=dropped;
3093              status|=DEC_Clamped;
3094              }
3095            if (todrop>0) {                  // have some to drop
3096              decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3097              a->exponent+=todrop;           // maintain numerical value
3098              a->digits-=todrop;             // new length
3099              }
3100            }
3101          }
3102        }
3103      }
3104
3105    // double-check Underflow, as perhaps the result could not have
3106    // been subnormal (initial argument too big), or it is now Exact
3107    if (status&DEC_Underflow) {
3108      Int ae=rhs->exponent+rhs->digits-1;    // adjusted exponent
3109      // check if truly subnormal
3110      #if DECEXTFLAG                         // DEC_Subnormal too
3111        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3112      #else
3113        if (ae>=set->emin*2) status&=~DEC_Underflow;
3114      #endif
3115      // check if truly inexact
3116      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3117      }
3118
3119    decNumberCopy(res, a);                   // a is now the result
3120    } while(0);                              // end protected
3121
3122  if (allocbuff!=NULL) free(allocbuff);      // drop any storage used
3123  if (allocbufa!=NULL) free(allocbufa);      // ..
3124  if (allocbufb!=NULL) free(allocbufb);      // ..
3125  #if DECSUBSET
3126  if (allocrhs !=NULL) free(allocrhs);       // ..
3127  #endif
3128  if (status!=0) decStatus(res, status, set);// then report status
3129  #if DECCHECK
3130  decCheckInexact(res, set);
3131  #endif
3132  return res;
3133  } // decNumberSquareRoot
3134
3135/* ------------------------------------------------------------------ */
3136/* decNumberSubtract -- subtract two Numbers                          */
3137/*                                                                    */
3138/*   This computes C = A - B                                          */
3139/*                                                                    */
3140/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3141/*   lhs is A                                                         */
3142/*   rhs is B                                                         */
3143/*   set is the context                                               */
3144/*                                                                    */
3145/* C must have space for set->digits digits.                          */
3146/* ------------------------------------------------------------------ */
3147decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3148                              const decNumber *rhs, decContext *set) {
3149  uInt status=0;                        // accumulator
3150
3151  decAddOp(res, lhs, rhs, set, DECNEG, &status);
3152  if (status!=0) decStatus(res, status, set);
3153  #if DECCHECK
3154  decCheckInexact(res, set);
3155  #endif
3156  return res;
3157  } // decNumberSubtract
3158
3159/* ------------------------------------------------------------------ */
3160/* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3161/* decNumberToIntegralValue -- round-to-integral-value                */
3162/*                                                                    */
3163/*   res is the result                                                */
3164/*   rhs is input number                                              */
3165/*   set is the context                                               */
3166/*                                                                    */
3167/* res must have space for any value of rhs.                          */
3168/*                                                                    */
3169/* This implements the IEEE special operators and therefore treats    */
3170/* special values as valid.  For finite numbers it returns            */
3171/* rescale(rhs, 0) if rhs->exponent is <0.                            */
3172/* Otherwise the result is rhs (so no error is possible, except for   */
3173/* sNaN).                                                             */
3174/*                                                                    */
3175/* The context is used for rounding mode and status after sNaN, but   */
3176/* the digits setting is ignored.  The Exact version will signal      */
3177/* Inexact if the result differs numerically from rhs; the other      */
3178/* never signals Inexact.                                             */
3179/* ------------------------------------------------------------------ */
3180decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3181                                     decContext *set) {
3182  decNumber dn;
3183  decContext workset;              // working context
3184  uInt status=0;                   // accumulator
3185
3186  #if DECCHECK
3187  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3188  #endif
3189
3190  // handle infinities and NaNs
3191  if (SPECIALARG) {
3192    if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); // an Infinity
3193     else decNaNs(res, rhs, NULL, set, &status); // a NaN
3194    }
3195   else { // finite
3196    // have a finite number; no error possible (res must be big enough)
3197    if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3198    // that was easy, but if negative exponent there is work to do...
3199    workset=*set;                  // clone rounding, etc.
3200    workset.digits=rhs->digits;    // no length rounding
3201    workset.traps=0;               // no traps
3202    decNumberZero(&dn);            // make a number with exponent 0
3203    decNumberQuantize(res, rhs, &dn, &workset);
3204    status|=workset.status;
3205    }
3206  if (status!=0) decStatus(res, status, set);
3207  return res;
3208  } // decNumberToIntegralExact
3209
3210decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3211                                     decContext *set) {
3212  decContext workset=*set;         // working context
3213  workset.traps=0;                 // no traps
3214  decNumberToIntegralExact(res, rhs, &workset);
3215  // this never affects set, except for sNaNs; NaN will have been set
3216  // or propagated already, so no need to call decStatus
3217  set->status|=workset.status&DEC_Invalid_operation;
3218  return res;
3219  } // decNumberToIntegralValue
3220
3221/* ------------------------------------------------------------------ */
3222/* decNumberXor -- XOR two Numbers, digitwise                         */
3223/*                                                                    */
3224/*   This computes C = A ^ B                                          */
3225/*                                                                    */
3226/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3227/*   lhs is A                                                         */
3228/*   rhs is B                                                         */
3229/*   set is the context (used for result length and error report)     */
3230/*                                                                    */
3231/* C must have space for set->digits digits.                          */
3232/*                                                                    */
3233/* Logical function restrictions apply (see above); a NaN is          */
3234/* returned with Invalid_operation if a restriction is violated.      */
3235/* ------------------------------------------------------------------ */
3236decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3237                         const decNumber *rhs, decContext *set) {
3238  const Unit *ua, *ub;                  // -> operands
3239  const Unit *msua, *msub;              // -> operand msus
3240  Unit  *uc, *msuc;                     // -> result and its msu
3241  Int   msudigs;                        // digits in res msu
3242  #if DECCHECK
3243  if (decCheckOperands(res, lhs, rhs, set)) return res;
3244  #endif
3245
3246  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3247   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3248    decStatus(res, DEC_Invalid_operation, set);
3249    return res;
3250    }
3251  // operands are valid
3252  ua=lhs->lsu;                          // bottom-up
3253  ub=rhs->lsu;                          // ..
3254  uc=res->lsu;                          // ..
3255  msua=ua+D2U(lhs->digits)-1;           // -> msu of lhs
3256  msub=ub+D2U(rhs->digits)-1;           // -> msu of rhs
3257  msuc=uc+D2U(set->digits)-1;           // -> msu of result
3258  msudigs=MSUDIGITS(set->digits);       // [faster than remainder]
3259  for (; uc<=msuc; ua++, ub++, uc++) {  // Unit loop
3260    Unit a, b;                          // extract units
3261    if (ua>msua) a=0;
3262     else a=*ua;
3263    if (ub>msub) b=0;
3264     else b=*ub;
3265    *uc=0;                              // can now write back
3266    if (a|b) {                          // maybe 1 bits to examine
3267      Int i, j;
3268      // This loop could be unrolled and/or use BIN2BCD tables
3269      for (i=0; i<DECDPUN; i++) {
3270        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     // effect XOR
3271        j=a%10;
3272        a=a/10;
3273        j|=b%10;
3274        b=b/10;
3275        if (j>1) {
3276          decStatus(res, DEC_Invalid_operation, set);
3277          return res;
3278          }
3279        if (uc==msuc && i==msudigs-1) break;      // just did final digit
3280        } // each digit
3281      } // non-zero
3282    } // each unit
3283  // [here uc-1 is the msu of the result]
3284  res->digits=decGetDigits(res->lsu, uc-res->lsu);
3285  res->exponent=0;                      // integer
3286  res->bits=0;                          // sign=0
3287  return res;  // [no status to set]
3288  } // decNumberXor
3289
3290
3291/* ================================================================== */
3292/* Utility routines                                                   */
3293/* ================================================================== */
3294
3295/* ------------------------------------------------------------------ */
3296/* decNumberClass -- return the decClass of a decNumber               */
3297/*   dn -- the decNumber to test                                      */
3298/*   set -- the context to use for Emin                               */
3299/*   returns the decClass enum                                        */
3300/* ------------------------------------------------------------------ */
3301enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3302  if (decNumberIsSpecial(dn)) {
3303    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3304    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3305    // must be an infinity
3306    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3307    return DEC_CLASS_POS_INF;
3308    }
3309  // is finite
3310  if (decNumberIsNormal(dn, set)) { // most common
3311    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3312    return DEC_CLASS_POS_NORMAL;
3313    }
3314  // is subnormal or zero
3315  if (decNumberIsZero(dn)) {    // most common
3316    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3317    return DEC_CLASS_POS_ZERO;
3318    }
3319  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3320  return DEC_CLASS_POS_SUBNORMAL;
3321  } // decNumberClass
3322
3323/* ------------------------------------------------------------------ */
3324/* decNumberClassToString -- convert decClass to a string             */
3325/*                                                                    */
3326/*  eclass is a valid decClass                                        */
3327/*  returns a constant string describing the class (max 13+1 chars)   */
3328/* ------------------------------------------------------------------ */
3329const char *decNumberClassToString(enum decClass eclass) {
3330  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3331  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3332  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3333  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3334  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3335  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3336  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3337  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3338  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3339  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3340  return DEC_ClassString_UN;           // Unknown
3341  } // decNumberClassToString
3342
3343/* ------------------------------------------------------------------ */
3344/* decNumberCopy -- copy a number                                     */
3345/*                                                                    */
3346/*   dest is the target decNumber                                     */
3347/*   src  is the source decNumber                                     */
3348/*   returns dest                                                     */
3349/*                                                                    */
3350/* (dest==src is allowed and is a no-op)                              */
3351/* All fields are updated as required.  This is a utility operation,  */
3352/* so special values are unchanged and no error is possible.          */
3353/* ------------------------------------------------------------------ */
3354decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3355
3356  #if DECCHECK
3357  if (src==NULL) return decNumberZero(dest);
3358  #endif
3359
3360  if (dest==src) return dest;                // no copy required
3361
3362  // Use explicit assignments here as structure assignment could copy
3363  // more than just the lsu (for small DECDPUN).  This would not affect
3364  // the value of the results, but could disturb test harness spill
3365  // checking.
3366  dest->bits=src->bits;
3367  dest->exponent=src->exponent;
3368  dest->digits=src->digits;
3369  dest->lsu[0]=src->lsu[0];
3370  if (src->digits>DECDPUN) {                 // more Units to come
3371    const Unit *smsup, *s;                   // work
3372    Unit  *d;                                // ..
3373    // memcpy for the remaining Units would be safe as they cannot
3374    // overlap.  However, this explicit loop is faster in short cases.
3375    d=dest->lsu+1;                           // -> first destination
3376    smsup=src->lsu+D2U(src->digits);         // -> source msu+1
3377    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3378    }
3379  return dest;
3380  } // decNumberCopy
3381
3382/* ------------------------------------------------------------------ */
3383/* decNumberCopyAbs -- quiet absolute value operator                  */
3384/*                                                                    */
3385/*   This sets C = abs(A)                                             */
3386/*                                                                    */
3387/*   res is C, the result.  C may be A                                */
3388/*   rhs is A                                                         */
3389/*                                                                    */
3390/* C must have space for set->digits digits.                          */
3391/* No exception or error can occur; this is a quiet bitwise operation.*/
3392/* See also decNumberAbs for a checking version of this.              */
3393/* ------------------------------------------------------------------ */
3394decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3395  #if DECCHECK
3396  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3397  #endif
3398  decNumberCopy(res, rhs);
3399  res->bits&=~DECNEG;                   // turn off sign
3400  return res;
3401  } // decNumberCopyAbs
3402
3403/* ------------------------------------------------------------------ */
3404/* decNumberCopyNegate -- quiet negate value operator                 */
3405/*                                                                    */
3406/*   This sets C = negate(A)                                          */
3407/*                                                                    */
3408/*   res is C, the result.  C may be A                                */
3409/*   rhs is A                                                         */
3410/*                                                                    */
3411/* C must have space for set->digits digits.                          */
3412/* No exception or error can occur; this is a quiet bitwise operation.*/
3413/* See also decNumberMinus for a checking version of this.            */
3414/* ------------------------------------------------------------------ */
3415decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3416  #if DECCHECK
3417  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3418  #endif
3419  decNumberCopy(res, rhs);
3420  res->bits^=DECNEG;                    // invert the sign
3421  return res;
3422  } // decNumberCopyNegate
3423
3424/* ------------------------------------------------------------------ */
3425/* decNumberCopySign -- quiet copy and set sign operator              */
3426/*                                                                    */
3427/*   This sets C = A with the sign of B                               */
3428/*                                                                    */
3429/*   res is C, the result.  C may be A                                */
3430/*   lhs is A                                                         */
3431/*   rhs is B                                                         */
3432/*                                                                    */
3433/* C must have space for set->digits digits.                          */
3434/* No exception or error can occur; this is a quiet bitwise operation.*/
3435/* ------------------------------------------------------------------ */
3436decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3437                              const decNumber *rhs) {
3438  uByte sign;                           // rhs sign
3439  #if DECCHECK
3440  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3441  #endif
3442  sign=rhs->bits & DECNEG;              // save sign bit
3443  decNumberCopy(res, lhs);
3444  res->bits&=~DECNEG;                   // clear the sign
3445  res->bits|=sign;                      // set from rhs
3446  return res;
3447  } // decNumberCopySign
3448
3449/* ------------------------------------------------------------------ */
3450/* decNumberGetBCD -- get the coefficient in BCD8                     */
3451/*   dn is the source decNumber                                       */
3452/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3453/*     most-significant at offset 0                                   */
3454/*   returns bcd                                                      */
3455/*                                                                    */
3456/* bcd must have at least dn->digits bytes.  No error is possible; if */
3457/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3458/* ------------------------------------------------------------------ */
3459uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3460  uByte *ub=bcd+dn->digits-1;      // -> lsd
3461  const Unit *up=dn->lsu;          // Unit pointer, -> lsu
3462
3463  #if DECDPUN==1                   // trivial simple copy
3464    for (; ub>=bcd; ub--, up++) *ub=*up;
3465  #else                            // chopping needed
3466    uInt u=*up;                    // work
3467    uInt cut=DECDPUN;              // downcounter through unit
3468    for (; ub>=bcd; ub--) {
3469      *ub=(uByte)(u%10);           // [*6554 trick inhibits, here]
3470      u=u/10;
3471      cut--;
3472      if (cut>0) continue;         // more in this unit
3473      up++;
3474      u=*up;
3475      cut=DECDPUN;
3476      }
3477  #endif
3478  return bcd;
3479  } // decNumberGetBCD
3480
3481/* ------------------------------------------------------------------ */
3482/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3483/*   dn is the target decNumber                                       */
3484/*   bcd is the uInt array that will source n BCD bytes, most-        */
3485/*     significant at offset 0                                        */
3486/*   n is the number of digits in the source BCD array (bcd)          */
3487/*   returns dn                                                       */
3488/*                                                                    */
3489/* dn must have space for at least n digits.  No error is possible;   */
3490/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3491/* and bcd[0] zero.                                                   */
3492/* ------------------------------------------------------------------ */
3493decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3494  Unit *up=dn->lsu+D2U(dn->digits)-1;   // -> msu [target pointer]
3495  const uByte *ub=bcd;                  // -> source msd
3496
3497  #if DECDPUN==1                        // trivial simple copy
3498    for (; ub<bcd+n; ub++, up--) *up=*ub;
3499  #else                                 // some assembly needed
3500    // calculate how many digits in msu, and hence first cut
3501    Int cut=MSUDIGITS(n);               // [faster than remainder]
3502    for (;up>=dn->lsu; up--) {          // each Unit from msu
3503      *up=0;                            // will take <=DECDPUN digits
3504      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3505      cut=DECDPUN;                      // next Unit has all digits
3506      }
3507  #endif
3508  dn->digits=n;                         // set digit count
3509  return dn;
3510  } // decNumberSetBCD
3511
3512/* ------------------------------------------------------------------ */
3513/* decNumberIsNormal -- test normality of a decNumber                 */
3514/*   dn is the decNumber to test                                      */
3515/*   set is the context to use for Emin                               */
3516/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3517/* ------------------------------------------------------------------ */
3518Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3519  Int ae;                               // adjusted exponent
3520  #if DECCHECK
3521  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3522  #endif
3523
3524  if (decNumberIsSpecial(dn)) return 0; // not finite
3525  if (decNumberIsZero(dn)) return 0;    // not non-zero
3526
3527  ae=dn->exponent+dn->digits-1;         // adjusted exponent
3528  if (ae<set->emin) return 0;           // is subnormal
3529  return 1;
3530  } // decNumberIsNormal
3531
3532/* ------------------------------------------------------------------ */
3533/* decNumberIsSubnormal -- test subnormality of a decNumber           */
3534/*   dn is the decNumber to test                                      */
3535/*   set is the context to use for Emin                               */
3536/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3537/* ------------------------------------------------------------------ */
3538Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3539  Int ae;                               // adjusted exponent
3540  #if DECCHECK
3541  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3542  #endif
3543
3544  if (decNumberIsSpecial(dn)) return 0; // not finite
3545  if (decNumberIsZero(dn)) return 0;    // not non-zero
3546
3547  ae=dn->exponent+dn->digits-1;         // adjusted exponent
3548  if (ae<set->emin) return 1;           // is subnormal
3549  return 0;
3550  } // decNumberIsSubnormal
3551
3552/* ------------------------------------------------------------------ */
3553/* decNumberTrim -- remove insignificant zeros                        */
3554/*                                                                    */
3555/*   dn is the number to trim                                         */
3556/*   returns dn                                                       */
3557/*                                                                    */
3558/* All fields are updated as required.  This is a utility operation,  */
3559/* so special values are unchanged and no error is possible.  The     */
3560/* zeros are removed unconditionally.                                 */
3561/* ------------------------------------------------------------------ */
3562decNumber * decNumberTrim(decNumber *dn) {
3563  Int  dropped;                    // work
3564  decContext set;                  // ..
3565  #if DECCHECK
3566  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3567  #endif
3568  decContextDefault(&set, DEC_INIT_BASE);    // clamp=0
3569  return decTrim(dn, &set, 0, 1, &dropped);
3570  } // decNumberTrim
3571
3572/* ------------------------------------------------------------------ */
3573/* decNumberVersion -- return the name and version of this module     */
3574/*                                                                    */
3575/* No error is possible.                                              */
3576/* ------------------------------------------------------------------ */
3577const char * decNumberVersion(void) {
3578  return DECVERSION;
3579  } // decNumberVersion
3580
3581/* ------------------------------------------------------------------ */
3582/* decNumberZero -- set a number to 0                                 */
3583/*                                                                    */
3584/*   dn is the number to set, with space for one digit                */
3585/*   returns dn                                                       */
3586/*                                                                    */
3587/* No error is possible.                                              */
3588/* ------------------------------------------------------------------ */
3589// Memset is not used as it is much slower in some environments.
3590decNumber * decNumberZero(decNumber *dn) {
3591
3592  #if DECCHECK
3593  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3594  #endif
3595
3596  dn->bits=0;
3597  dn->exponent=0;
3598  dn->digits=1;
3599  dn->lsu[0]=0;
3600  return dn;
3601  } // decNumberZero
3602
3603/* ================================================================== */
3604/* Local routines                                                     */
3605/* ================================================================== */
3606
3607/* ------------------------------------------------------------------ */
3608/* decToString -- lay out a number into a string                      */
3609/*                                                                    */
3610/*   dn     is the number to lay out                                  */
3611/*   string is where to lay out the number                            */
3612/*   eng    is 1 if Engineering, 0 if Scientific                      */
3613/*                                                                    */
3614/* string must be at least dn->digits+14 characters long              */
3615/* No error is possible.                                              */
3616/*                                                                    */
3617/* Note that this routine can generate a -0 or 0.000.  These are      */
3618/* never generated in subset to-number or arithmetic, but can occur   */
3619/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3620/* ------------------------------------------------------------------ */
3621// If DECCHECK is enabled the string "?" is returned if a number is
3622// invalid.
3623static void decToString(const decNumber *dn, char *string, Flag eng) {
3624  Int exp=dn->exponent;       // local copy
3625  Int e;                      // E-part value
3626  Int pre;                    // digits before the '.'
3627  Int cut;                    // for counting digits in a Unit
3628  char *c=string;             // work [output pointer]
3629  const Unit *up=dn->lsu+D2U(dn->digits)-1; // -> msu [input pointer]
3630  uInt u, pow;                // work
3631
3632  #if DECCHECK
3633  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3634    strcpy(string, "?");
3635    return;}
3636  #endif
3637
3638  if (decNumberIsNegative(dn)) {   // Negatives get a minus
3639    *c='-';
3640    c++;
3641    }
3642  if (dn->bits&DECSPECIAL) {       // Is a special value
3643    if (decNumberIsInfinite(dn)) {
3644      strcpy(c,   "Inf");
3645      strcpy(c+3, "inity");
3646      return;}
3647    // a NaN
3648    if (dn->bits&DECSNAN) {        // signalling NaN
3649      *c='s';
3650      c++;
3651      }
3652    strcpy(c, "NaN");
3653    c+=3;                          // step past
3654    // if not a clean non-zero coefficient, that's all there is in a
3655    // NaN string
3656    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3657    // [drop through to add integer]
3658    }
3659
3660  // calculate how many digits in msu, and hence first cut
3661  cut=MSUDIGITS(dn->digits);       // [faster than remainder]
3662  cut--;                           // power of ten for digit
3663
3664  if (exp==0) {                    // simple integer [common fastpath]
3665    for (;up>=dn->lsu; up--) {     // each Unit from msu
3666      u=*up;                       // contains DECDPUN digits to lay out
3667      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3668      cut=DECDPUN-1;               // next Unit has all digits
3669      }
3670    *c='\0';                       // terminate the string
3671    return;}
3672
3673  /* non-0 exponent -- assume plain form */
3674  pre=dn->digits+exp;              // digits before '.'
3675  e=0;                             // no E
3676  if ((exp>0) || (pre<-5)) {       // need exponential form
3677    e=exp+dn->digits-1;            // calculate E value
3678    pre=1;                         // assume one digit before '.'
3679    if (eng && (e!=0)) {           // engineering: may need to adjust
3680      Int adj;                     // adjustment
3681      // The C remainder operator is undefined for negative numbers, so
3682      // a positive remainder calculation must be used here
3683      if (e<0) {
3684        adj=(-e)%3;
3685        if (adj!=0) adj=3-adj;
3686        }
3687       else { // e>0
3688        adj=e%3;
3689        }
3690      e=e-adj;
3691      // if dealing with zero still produce an exponent which is a
3692      // multiple of three, as expected, but there will only be the
3693      // one zero before the E, still.  Otherwise note the padding.
3694      if (!ISZERO(dn)) pre+=adj;
3695       else {  // is zero
3696        if (adj!=0) {              // 0.00Esnn needed
3697          e=e+3;
3698          pre=-(2-adj);
3699          }
3700        } // zero
3701      } // eng
3702    } // need exponent
3703
3704  /* lay out the digits of the coefficient, adding 0s and . as needed */
3705  u=*up;
3706  if (pre>0) {                     // xxx.xxx or xx00 (engineering) form
3707    Int n=pre;
3708    for (; pre>0; pre--, c++, cut--) {
3709      if (cut<0) {                 // need new Unit
3710        if (up==dn->lsu) break;    // out of input digits (pre>digits)
3711        up--;
3712        cut=DECDPUN-1;
3713        u=*up;
3714        }
3715      TODIGIT(u, cut, c, pow);
3716      }
3717    if (n<dn->digits) {            // more to come, after '.'
3718      *c='.'; c++;
3719      for (;; c++, cut--) {
3720        if (cut<0) {               // need new Unit
3721          if (up==dn->lsu) break;  // out of input digits
3722          up--;
3723          cut=DECDPUN-1;
3724          u=*up;
3725          }
3726        TODIGIT(u, cut, c, pow);
3727        }
3728      }
3729     else for (; pre>0; pre--, c++) *c='0'; // 0 padding (for engineering) needed
3730    }
3731   else {                          // 0.xxx or 0.000xxx form
3732    *c='0'; c++;
3733    *c='.'; c++;
3734    for (; pre<0; pre++, c++) *c='0';   // add any 0's after '.'
3735    for (; ; c++, cut--) {
3736      if (cut<0) {                 // need new Unit
3737        if (up==dn->lsu) break;    // out of input digits
3738        up--;
3739        cut=DECDPUN-1;
3740        u=*up;
3741        }
3742      TODIGIT(u, cut, c, pow);
3743      }
3744    }
3745
3746  /* Finally add the E-part, if needed.  It will never be 0, has a
3747     base maximum and minimum of +999999999 through -999999999, but
3748     could range down to -1999999998 for anormal numbers */
3749  if (e!=0) {
3750    Flag had=0;               // 1=had non-zero
3751    *c='E'; c++;
3752    *c='+'; c++;              // assume positive
3753    u=e;                      // ..
3754    if (e<0) {
3755      *(c-1)='-';             // oops, need -
3756      u=-e;                   // uInt, please
3757      }
3758    // lay out the exponent [_itoa or equivalent is not ANSI C]
3759    for (cut=9; cut>=0; cut--) {
3760      TODIGIT(u, cut, c, pow);
3761      if (*c=='0' && !had) continue;    // skip leading zeros
3762      had=1;                            // had non-0
3763      c++;                              // step for next
3764      } // cut
3765    }
3766  *c='\0';          // terminate the string (all paths)
3767  return;
3768  } // decToString
3769
3770/* ------------------------------------------------------------------ */
3771/* decAddOp -- add/subtract operation                                 */
3772/*                                                                    */
3773/*   This computes C = A + B                                          */
3774/*                                                                    */
3775/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3776/*   lhs is A                                                         */
3777/*   rhs is B                                                         */
3778/*   set is the context                                               */
3779/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3780/*   status accumulates status for the caller                         */
3781/*                                                                    */
3782/* C must have space for set->digits digits.                          */
3783/* Inexact in status must be 0 for correct Exact zero sign in result  */
3784/* ------------------------------------------------------------------ */
3785/* If possible, the coefficient is calculated directly into C.        */
3786/* However, if:                                                       */
3787/*   -- a digits+1 calculation is needed because the numbers are      */
3788/*      unaligned and span more than set->digits digits               */
3789/*   -- a carry to digits+1 digits looks possible                     */
3790/*   -- C is the same as A or B, and the result would destructively   */
3791/*      overlap the A or B coefficient                                */
3792/* then the result must be calculated into a temporary buffer.  In    */
3793/* this case a local (stack) buffer is used if possible, and only if  */
3794/* too long for that does malloc become the final resort.             */
3795/*                                                                    */
3796/* Misalignment is handled as follows:                                */
3797/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3798/*   BPad: Apply the padding by a combination of shifting (whole      */
3799/*         units) and multiplication (part units).                    */
3800/*                                                                    */
3801/* Addition, especially x=x+1, is speed-critical.                     */
3802/* The static buffer is larger than might be expected to allow for    */
3803/* calls from higher-level funtions (notable exp).                    */
3804/* ------------------------------------------------------------------ */
3805static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3806                            const decNumber *rhs, decContext *set,
3807                            uByte negate, uInt *status) {
3808  #if DECSUBSET
3809  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
3810  decNumber *allocrhs=NULL;        // .., rhs
3811  #endif
3812  Int   rhsshift;                  // working shift (in Units)
3813  Int   maxdigits;                 // longest logical length
3814  Int   mult;                      // multiplier
3815  Int   residue;                   // rounding accumulator
3816  uByte bits;                      // result bits
3817  Flag  diffsign;                  // non-0 if arguments have different sign
3818  Unit  *acc;                      // accumulator for result
3819  Unit  accbuff[SD2U(DECBUFFER*2+20)]; // local buffer [*2+20 reduces many
3820                                   // allocations when called from
3821                                   // other operations, notable exp]
3822  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
3823  Int   reqdigits=set->digits;     // local copy; requested DIGITS
3824  Int   padding;                   // work
3825
3826  #if DECCHECK
3827  if (decCheckOperands(res, lhs, rhs, set)) return res;
3828  #endif
3829
3830  do {                             // protect allocated storage
3831    #if DECSUBSET
3832    if (!set->extended) {
3833      // reduce operands and set lostDigits status, as needed
3834      if (lhs->digits>reqdigits) {
3835        alloclhs=decRoundOperand(lhs, set, status);
3836        if (alloclhs==NULL) break;
3837        lhs=alloclhs;
3838        }
3839      if (rhs->digits>reqdigits) {
3840        allocrhs=decRoundOperand(rhs, set, status);
3841        if (allocrhs==NULL) break;
3842        rhs=allocrhs;
3843        }
3844      }
3845    #endif
3846    // [following code does not require input rounding]
3847
3848    // note whether signs differ [used all paths]
3849    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3850
3851    // handle infinities and NaNs
3852    if (SPECIALARGS) {                  // a special bit set
3853      if (SPECIALARGS & (DECSNAN | DECNAN))  // a NaN
3854        decNaNs(res, lhs, rhs, set, status);
3855       else { // one or two infinities
3856        if (decNumberIsInfinite(lhs)) { // LHS is infinity
3857          // two infinities with different signs is invalid
3858          if (decNumberIsInfinite(rhs) && diffsign) {
3859            *status|=DEC_Invalid_operation;
3860            break;
3861            }
3862          bits=lhs->bits & DECNEG;      // get sign from LHS
3863          }
3864         else bits=(rhs->bits^negate) & DECNEG;// RHS must be Infinity
3865        bits|=DECINF;
3866        decNumberZero(res);
3867        res->bits=bits;                 // set +/- infinity
3868        } // an infinity
3869      break;
3870      }
3871
3872    // Quick exit for add 0s; return the non-0, modified as need be
3873    if (ISZERO(lhs)) {
3874      Int adjust;                       // work
3875      Int lexp=lhs->exponent;           // save in case LHS==RES
3876      bits=lhs->bits;                   // ..
3877      residue=0;                        // clear accumulator
3878      decCopyFit(res, rhs, set, &residue, status); // copy (as needed)
3879      res->bits^=negate;                // flip if rhs was negated
3880      #if DECSUBSET
3881      if (set->extended) {              // exponents on zeros count
3882      #endif
3883        // exponent will be the lower of the two
3884        adjust=lexp-res->exponent;      // adjustment needed [if -ve]
3885        if (ISZERO(res)) {              // both 0: special IEEE 754 rules
3886          if (adjust<0) res->exponent=lexp;  // set exponent
3887          // 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0
3888          if (diffsign) {
3889            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3890             else res->bits=DECNEG;     // preserve 0 sign
3891            }
3892          }
3893         else { // non-0 res
3894          if (adjust<0) {     // 0-padding needed
3895            if ((res->digits-adjust)>set->digits) {
3896              adjust=res->digits-set->digits;     // to fit exactly
3897              *status|=DEC_Rounded;               // [but exact]
3898              }
3899            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3900            res->exponent+=adjust;                // set the exponent.
3901            }
3902          } // non-0 res
3903      #if DECSUBSET
3904        } // extended
3905      #endif
3906      decFinish(res, set, &residue, status);      // clean and finalize
3907      break;}
3908
3909    if (ISZERO(rhs)) {                  // [lhs is non-zero]
3910      Int adjust;                       // work
3911      Int rexp=rhs->exponent;           // save in case RHS==RES
3912      bits=rhs->bits;                   // be clean
3913      residue=0;                        // clear accumulator
3914      decCopyFit(res, lhs, set, &residue, status); // copy (as needed)
3915      #if DECSUBSET
3916      if (set->extended) {              // exponents on zeros count
3917      #endif
3918        // exponent will be the lower of the two
3919        // [0-0 case handled above]
3920        adjust=rexp-res->exponent;      // adjustment needed [if -ve]
3921        if (adjust<0) {     // 0-padding needed
3922          if ((res->digits-adjust)>set->digits) {
3923            adjust=res->digits-set->digits;     // to fit exactly
3924            *status|=DEC_Rounded;               // [but exact]
3925            }
3926          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3927          res->exponent+=adjust;                // set the exponent.
3928          }
3929      #if DECSUBSET
3930        } // extended
3931      #endif
3932      decFinish(res, set, &residue, status);      // clean and finalize
3933      break;}
3934
3935    // [NB: both fastpath and mainpath code below assume these cases
3936    // (notably 0-0) have already been handled]
3937
3938    // calculate the padding needed to align the operands
3939    padding=rhs->exponent-lhs->exponent;
3940
3941    // Fastpath cases where the numbers are aligned and normal, the RHS
3942    // is all in one unit, no operand rounding is needed, and no carry,
3943    // lengthening, or borrow is needed
3944    if (padding==0
3945        && rhs->digits<=DECDPUN
3946        && rhs->exponent>=set->emin     // [some normals drop through]
3947        && rhs->exponent<=set->emax-set->digits+1 // [could clamp]
3948        && rhs->digits<=reqdigits
3949        && lhs->digits<=reqdigits) {
3950      Int partial=*lhs->lsu;
3951      if (!diffsign) {                  // adding
3952        partial+=*rhs->lsu;
3953        if ((partial<=DECDPUNMAX)       // result fits in unit
3954         && (lhs->digits>=DECDPUN ||    // .. and no digits-count change
3955             partial<(Int)powers[lhs->digits])) { // ..
3956          if (res!=lhs) decNumberCopy(res, lhs);  // not in place
3957          *res->lsu=(Unit)partial;      // [copy could have overwritten RHS]
3958          break;
3959          }
3960        // else drop out for careful add
3961        }
3962       else {                           // signs differ
3963        partial-=*rhs->lsu;
3964        if (partial>0) { // no borrow needed, and non-0 result
3965          if (res!=lhs) decNumberCopy(res, lhs);  // not in place
3966          *res->lsu=(Unit)partial;
3967          // this could have reduced digits [but result>0]
3968          res->digits=decGetDigits(res->lsu, D2U(res->digits));
3969          break;
3970          }
3971        // else drop out for careful subtract
3972        }
3973      }
3974
3975    // Now align (pad) the lhs or rhs so they can be added or
3976    // subtracted, as necessary.  If one number is much larger than
3977    // the other (that is, if in plain form there is a least one
3978    // digit between the lowest digit of one and the highest of the
3979    // other) padding with up to DIGITS-1 trailing zeros may be
3980    // needed; then apply rounding (as exotic rounding modes may be
3981    // affected by the residue).
3982    rhsshift=0;               // rhs shift to left (padding) in Units
3983    bits=lhs->bits;           // assume sign is that of LHS
3984    mult=1;                   // likely multiplier
3985
3986    // [if padding==0 the operands are aligned; no padding is needed]
3987    if (padding!=0) {
3988      // some padding needed; always pad the RHS, as any required
3989      // padding can then be effected by a simple combination of
3990      // shifts and a multiply
3991      Flag swapped=0;
3992      if (padding<0) {                  // LHS needs the padding
3993        const decNumber *t;
3994        padding=-padding;               // will be +ve
3995        bits=(uByte)(rhs->bits^negate); // assumed sign is now that of RHS
3996        t=lhs; lhs=rhs; rhs=t;
3997        swapped=1;
3998        }
3999
4000      // If, after pad, rhs would be longer than lhs by digits+1 or
4001      // more then lhs cannot affect the answer, except as a residue,
4002      // so only need to pad up to a length of DIGITS+1.
4003      if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4004        // The RHS is sufficient
4005        // for residue use the relative sign indication...
4006        Int shift=reqdigits-rhs->digits;     // left shift needed
4007        residue=1;                           // residue for rounding
4008        if (diffsign) residue=-residue;      // signs differ
4009        // copy, shortening if necessary
4010        decCopyFit(res, rhs, set, &residue, status);
4011        // if it was already shorter, then need to pad with zeros
4012        if (shift>0) {
4013          res->digits=decShiftToMost(res->lsu, res->digits, shift);
4014          res->exponent-=shift;              // adjust the exponent.
4015          }
4016        // flip the result sign if unswapped and rhs was negated
4017        if (!swapped) res->bits^=negate;
4018        decFinish(res, set, &residue, status);    // done
4019        break;}
4020
4021      // LHS digits may affect result
4022      rhsshift=D2U(padding+1)-1;        // this much by Unit shift ..
4023      mult=powers[padding-(rhsshift*DECDPUN)]; // .. this by multiplication
4024      } // padding needed
4025
4026    if (diffsign) mult=-mult;           // signs differ
4027
4028    // determine the longer operand
4029    maxdigits=rhs->digits+padding;      // virtual length of RHS
4030    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4031
4032    // Decide on the result buffer to use; if possible place directly
4033    // into result.
4034    acc=res->lsu;                       // assume add direct to result
4035    // If destructive overlap, or the number is too long, or a carry or
4036    // borrow to DIGITS+1 might be possible, a buffer must be used.
4037    // [Might be worth more sophisticated tests when maxdigits==reqdigits]
4038    if ((maxdigits>=reqdigits)          // is, or could be, too large
4039     || (res==rhs && rhsshift>0)) {     // destructive overlap
4040      // buffer needed, choose it; units for maxdigits digits will be
4041      // needed, +1 Unit for carry or borrow
4042      Int need=D2U(maxdigits)+1;
4043      acc=accbuff;                      // assume use local buffer
4044      if (need*sizeof(Unit)>sizeof(accbuff)) {
4045        // printf("malloc add %ld %ld\n", need, sizeof(accbuff));
4046        allocacc=(Unit *)malloc(need*sizeof(Unit));
4047        if (allocacc==NULL) {           // hopeless -- abandon
4048          *status|=DEC_Insufficient_storage;
4049          break;}
4050        acc=allocacc;
4051        }
4052      }
4053
4054    res->bits=(uByte)(bits&DECNEG);     // it's now safe to overwrite..
4055    res->exponent=lhs->exponent;        // .. operands (even if aliased)
4056
4057    #if DECTRACE
4058      decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4059      decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4060      printf("  :h: %ld %ld\n", rhsshift, mult);
4061    #endif
4062
4063    // add [A+B*m] or subtract [A+B*(-m)]
4064    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4065                              rhs->lsu, D2U(rhs->digits),
4066                              rhsshift, acc, mult)
4067               *DECDPUN;           // [units -> digits]
4068    if (res->digits<0) {           // borrowed...
4069      res->digits=-res->digits;
4070      res->bits^=DECNEG;           // flip the sign
4071      }
4072    #if DECTRACE
4073      decDumpAr('+', acc, D2U(res->digits));
4074    #endif
4075
4076    // If a buffer was used the result must be copied back, possibly
4077    // shortening.  (If no buffer was used then the result must have
4078    // fit, so can't need rounding and residue must be 0.)
4079    residue=0;                     // clear accumulator
4080    if (acc!=res->lsu) {
4081      #if DECSUBSET
4082      if (set->extended) {         // round from first significant digit
4083      #endif
4084        // remove leading zeros that were added due to rounding up to
4085        // integral Units -- before the test for rounding.
4086        if (res->digits>reqdigits)
4087          res->digits=decGetDigits(acc, D2U(res->digits));
4088        decSetCoeff(res, set, acc, res->digits, &residue, status);
4089      #if DECSUBSET
4090        }
4091       else { // subset arithmetic rounds from original significant digit
4092        // May have an underestimate.  This only occurs when both
4093        // numbers fit in DECDPUN digits and are padding with a
4094        // negative multiple (-10, -100...) and the top digit(s) become
4095        // 0.  (This only matters when using X3.274 rules where the
4096        // leading zero could be included in the rounding.)
4097        if (res->digits<maxdigits) {
4098          *(acc+D2U(res->digits))=0; // ensure leading 0 is there
4099          res->digits=maxdigits;
4100          }
4101         else {
4102          // remove leading zeros that added due to rounding up to
4103          // integral Units (but only those in excess of the original
4104          // maxdigits length, unless extended) before test for rounding.
4105          if (res->digits>reqdigits) {
4106            res->digits=decGetDigits(acc, D2U(res->digits));
4107            if (res->digits<maxdigits) res->digits=maxdigits;
4108            }
4109          }
4110        decSetCoeff(res, set, acc, res->digits, &residue, status);
4111        // Now apply rounding if needed before removing leading zeros.
4112        // This is safe because subnormals are not a possibility
4113        if (residue!=0) {
4114          decApplyRound(res, set, residue, status);
4115          residue=0;                 // did what needed to be done
4116          }
4117        } // subset
4118      #endif
4119      } // used buffer
4120
4121    // strip leading zeros [these were left on in case of subset subtract]
4122    res->digits=decGetDigits(res->lsu, D2U(res->digits));
4123
4124    // apply checks and rounding
4125    decFinish(res, set, &residue, status);
4126
4127    // "When the sum of two operands with opposite signs is exactly
4128    // zero, the sign of that sum shall be '+' in all rounding modes
4129    // except round toward -Infinity, in which mode that sign shall be
4130    // '-'."  [Subset zeros also never have '-', set by decFinish.]
4131    if (ISZERO(res) && diffsign
4132     #if DECSUBSET
4133     && set->extended
4134     #endif
4135     && (*status&DEC_Inexact)==0) {
4136      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   // sign -
4137                                  else res->bits&=~DECNEG;  // sign +
4138      }
4139    } while(0);                              // end protected
4140
4141  if (allocacc!=NULL) free(allocacc);        // drop any storage used
4142  #if DECSUBSET
4143  if (allocrhs!=NULL) free(allocrhs);        // ..
4144  if (alloclhs!=NULL) free(alloclhs);        // ..
4145  #endif
4146  return res;
4147  } // decAddOp
4148
4149/* ------------------------------------------------------------------ */
4150/* decDivideOp -- division operation                                  */
4151/*                                                                    */
4152/*  This routine performs the calculations for all four division      */
4153/*  operators (divide, divideInteger, remainder, remainderNear).      */
4154/*                                                                    */
4155/*  C=A op B                                                          */
4156/*                                                                    */
4157/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4158/*   lhs is A                                                         */
4159/*   rhs is B                                                         */
4160/*   set is the context                                               */
4161/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4162/*   status is the usual accumulator                                  */
4163/*                                                                    */
4164/* C must have space for set->digits digits.                          */
4165/*                                                                    */
4166/* ------------------------------------------------------------------ */
4167/*   The underlying algorithm of this routine is the same as in the   */
4168/*   1981 S/370 implementation, that is, non-restoring long division  */
4169/*   with bi-unit (rather than bi-digit) estimation for each unit     */
4170/*   multiplier.  In this pseudocode overview, complications for the  */
4171/*   Remainder operators and division residues for exact rounding are */
4172/*   omitted for clarity.                                             */
4173/*                                                                    */
4174/*     Prepare operands and handle special values                     */
4175/*     Test for x/0 and then 0/x                                      */
4176/*     Exp =Exp1 - Exp2                                               */
4177/*     Exp =Exp +len(var1) -len(var2)                                 */
4178/*     Sign=Sign1 * Sign2                                             */
4179/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4180/*     Pad Var2 to same length as Var1                                */
4181/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4182/*     have=0                                                         */
4183/*     Do until (have=digits+1 OR residue=0)                          */
4184/*       if exp<0 then if integer divide/residue then leave           */
4185/*       this_unit=0                                                  */
4186/*       Do forever                                                   */
4187/*          compare numbers                                           */
4188/*          if <0 then leave inner_loop                               */
4189/*          if =0 then (* quick exit without subtract *) do           */
4190/*             this_unit=this_unit+1; output this_unit                */
4191/*             leave outer_loop; end                                  */
4192/*          Compare lengths of numbers (mantissae):                   */
4193/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4194/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4195/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4196/*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4197/*          if mult=0 then mult=1                                     */
4198/*          this_unit=this_unit+mult                                  */
4199/*          subtract                                                  */
4200/*          end inner_loop                                            */
4201/*        if have\=0 | this_unit\=0 then do                           */
4202/*          output this_unit                                          */
4203/*          have=have+1; end                                          */
4204/*        var2=var2/10                                                */
4205/*        exp=exp-1                                                   */
4206/*        end outer_loop                                              */
4207/*     exp=exp+1   -- set the proper exponent                         */
4208/*     if have=0 then generate answer=0                               */
4209/*     Return (Result is defined by Var1)                             */
4210/*                                                                    */
4211/* ------------------------------------------------------------------ */
4212/* Two working buffers are needed during the division; one (digits+   */
4213/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4214/* long subtractions.  These are acc and var1 respectively.           */
4215/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4216/* The static buffers may be larger than might be expected to allow   */
4217/* for calls from higher-level funtions (notable exp).                */
4218/* ------------------------------------------------------------------ */
4219static decNumber * decDivideOp(decNumber *res,
4220                               const decNumber *lhs, const decNumber *rhs,
4221                               decContext *set, Flag op, uInt *status) {
4222  #if DECSUBSET
4223  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
4224  decNumber *allocrhs=NULL;        // .., rhs
4225  #endif
4226  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; // local buffer
4227  Unit  *acc=accbuff;              // -> accumulator array for result
4228  Unit  *allocacc=NULL;            // -> allocated buffer, iff allocated
4229  Unit  *accnext;                  // -> where next digit will go
4230  Int   acclength;                 // length of acc needed [Units]
4231  Int   accunits;                  // count of units accumulated
4232  Int   accdigits;                 // count of digits accumulated
4233
4234  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  // buffer for var1
4235  Unit  *var1=varbuff;             // -> var1 array for long subtraction
4236  Unit  *varalloc=NULL;            // -> allocated buffer, iff used
4237  Unit  *msu1;                     // -> msu of var1
4238
4239  const Unit *var2;                // -> var2 array
4240  const Unit *msu2;                // -> msu of var2
4241  Int   msu2plus;                  // msu2 plus one [does not vary]
4242  eInt  msu2pair;                  // msu2 pair plus one [does not vary]
4243
4244  Int   var1units, var2units;      // actual lengths
4245  Int   var2ulen;                  // logical length (units)
4246  Int   var1initpad=0;             // var1 initial padding (digits)
4247  Int   maxdigits;                 // longest LHS or required acc length
4248  Int   mult;                      // multiplier for subtraction
4249  Unit  thisunit;                  // current unit being accumulated
4250  Int   residue;                   // for rounding
4251  Int   reqdigits=set->digits;     // requested DIGITS
4252  Int   exponent;                  // working exponent
4253  Int   maxexponent=0;             // DIVIDE maximum exponent if unrounded
4254  uByte bits;                      // working sign
4255  Unit  *target;                   // work
4256  const Unit *source;              // ..
4257  uInt  const *pow;                // ..
4258  Int   shift, cut;                // ..
4259  #if DECSUBSET
4260  Int   dropped;                   // work
4261  #endif
4262
4263  #if DECCHECK
4264  if (decCheckOperands(res, lhs, rhs, set)) return res;
4265  #endif
4266
4267  do {                             // protect allocated storage
4268    #if DECSUBSET
4269    if (!set->extended) {
4270      // reduce operands and set lostDigits status, as needed
4271      if (lhs->digits>reqdigits) {
4272        alloclhs=decRoundOperand(lhs, set, status);
4273        if (alloclhs==NULL) break;
4274        lhs=alloclhs;
4275        }
4276      if (rhs->digits>reqdigits) {
4277        allocrhs=decRoundOperand(rhs, set, status);
4278        if (allocrhs==NULL) break;
4279        rhs=allocrhs;
4280        }
4281      }
4282    #endif
4283    // [following code does not require input rounding]
4284
4285    bits=(lhs->bits^rhs->bits)&DECNEG;  // assumed sign for divisions
4286
4287    // handle infinities and NaNs
4288    if (SPECIALARGS) {                  // a special bit set
4289      if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
4290        decNaNs(res, lhs, rhs, set, status);
4291        break;
4292        }
4293      // one or two infinities
4294      if (decNumberIsInfinite(lhs)) {   // LHS (dividend) is infinite
4295        if (decNumberIsInfinite(rhs) || // two infinities are invalid ..
4296            op & (REMAINDER | REMNEAR)) { // as is remainder of infinity
4297          *status|=DEC_Invalid_operation;
4298          break;
4299          }
4300        // [Note that infinity/0 raises no exceptions]
4301        decNumberZero(res);
4302        res->bits=bits|DECINF;          // set +/- infinity
4303        break;
4304        }
4305       else {                           // RHS (divisor) is infinite
4306        residue=0;
4307        if (op&(REMAINDER|REMNEAR)) {
4308          // result is [finished clone of] lhs
4309          decCopyFit(res, lhs, set, &residue, status);
4310          }
4311         else {  // a division
4312          decNumberZero(res);
4313          res->bits=bits;               // set +/- zero
4314          // for DIVIDEINT the exponent is always 0.  For DIVIDE, result
4315          // is a 0 with infinitely negative exponent, clamped to minimum
4316          if (op&DIVIDE) {
4317            res->exponent=set->emin-set->digits+1;
4318            *status|=DEC_Clamped;
4319            }
4320          }
4321        decFinish(res, set, &residue, status);
4322        break;
4323        }
4324      }
4325
4326    // handle 0 rhs (x/0)
4327    if (ISZERO(rhs)) {                  // x/0 is always exceptional
4328      if (ISZERO(lhs)) {
4329        decNumberZero(res);             // [after lhs test]
4330        *status|=DEC_Division_undefined;// 0/0 will become NaN
4331        }
4332       else {
4333        decNumberZero(res);
4334        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4335         else {
4336          *status|=DEC_Division_by_zero; // x/0
4337          res->bits=bits|DECINF;         // .. is +/- Infinity
4338          }
4339        }
4340      break;}
4341
4342    // handle 0 lhs (0/x)
4343    if (ISZERO(lhs)) {                  // 0/x [x!=0]
4344      #if DECSUBSET
4345      if (!set->extended) decNumberZero(res);
4346       else {
4347      #endif
4348        if (op&DIVIDE) {
4349          residue=0;
4350          exponent=lhs->exponent-rhs->exponent; // ideal exponent
4351          decNumberCopy(res, lhs);      // [zeros always fit]
4352          res->bits=bits;               // sign as computed
4353          res->exponent=exponent;       // exponent, too
4354          decFinalize(res, set, &residue, status);   // check exponent
4355          }
4356         else if (op&DIVIDEINT) {
4357          decNumberZero(res);           // integer 0
4358          res->bits=bits;               // sign as computed
4359          }
4360         else {                         // a remainder
4361          exponent=rhs->exponent;       // [save in case overwrite]
4362          decNumberCopy(res, lhs);      // [zeros always fit]
4363          if (exponent<res->exponent) res->exponent=exponent; // use lower
4364          }
4365      #if DECSUBSET
4366        }
4367      #endif
4368      break;}
4369
4370    // Precalculate exponent.  This starts off adjusted (and hence fits
4371    // in 31 bits) and becomes the usual unadjusted exponent as the
4372    // division proceeds.  The order of evaluation is important, here,
4373    // to avoid wrap.
4374    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4375
4376    // If the working exponent is -ve, then some quick exits are
4377    // possible because the quotient is known to be <1
4378    // [for REMNEAR, it needs to be < -1, as -0.5 could need work]
4379    if (exponent<0 && !(op==DIVIDE)) {
4380      if (op&DIVIDEINT) {
4381        decNumberZero(res);                  // integer part is 0
4382        #if DECSUBSET
4383        if (set->extended)
4384        #endif
4385          res->bits=bits;                    // set +/- zero
4386        break;}
4387      // fastpath remainders so long as the lhs has the smaller
4388      // (or equal) exponent
4389      if (lhs->exponent<=rhs->exponent) {
4390        if (op&REMAINDER || exponent<-1) {
4391          // It is REMAINDER or safe REMNEAR; result is [finished
4392          // clone of] lhs  (r = x - 0*y)
4393          residue=0;
4394          decCopyFit(res, lhs, set, &residue, status);
4395          decFinish(res, set, &residue, status);
4396          break;
4397          }
4398        // [unsafe REMNEAR drops through]
4399        }
4400      } // fastpaths
4401
4402    /* Long (slow) division is needed; roll up the sleeves... */
4403
4404    // The accumulator will hold the quotient of the division.
4405    // If it needs to be too long for stack storage, then allocate.
4406    acclength=D2U(reqdigits+DECDPUN);   // in Units
4407    if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4408      // printf("malloc dvacc %ld units\n", acclength);
4409      allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4410      if (allocacc==NULL) {             // hopeless -- abandon
4411        *status|=DEC_Insufficient_storage;
4412        break;}
4413      acc=allocacc;                     // use the allocated space
4414      }
4415
4416    // var1 is the padded LHS ready for subtractions.
4417    // If it needs to be too long for stack storage, then allocate.
4418    // The maximum units needed for var1 (long subtraction) is:
4419    // Enough for
4420    //     (rhs->digits+reqdigits-1) -- to allow full slide to right
4421    // or  (lhs->digits)             -- to allow for long lhs
4422    // whichever is larger
4423    //   +1                -- for rounding of slide to right
4424    //   +1                -- for leading 0s
4425    //   +1                -- for pre-adjust if a remainder or DIVIDEINT
4426    // [Note: unused units do not participate in decUnitAddSub data]
4427    maxdigits=rhs->digits+reqdigits-1;
4428    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4429    var1units=D2U(maxdigits)+2;
4430    // allocate a guard unit above msu1 for REMAINDERNEAR
4431    if (!(op&DIVIDE)) var1units++;
4432    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4433      // printf("malloc dvvar %ld units\n", var1units+1);
4434      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4435      if (varalloc==NULL) {             // hopeless -- abandon
4436        *status|=DEC_Insufficient_storage;
4437        break;}
4438      var1=varalloc;                    // use the allocated space
4439      }
4440
4441    // Extend the lhs and rhs to full long subtraction length.  The lhs
4442    // is truly extended into the var1 buffer, with 0 padding, so a
4443    // subtract in place is always possible.  The rhs (var2) has
4444    // virtual padding (implemented by decUnitAddSub).
4445    // One guard unit was allocated above msu1 for rem=rem+rem in
4446    // REMAINDERNEAR.
4447    msu1=var1+var1units-1;              // msu of var1
4448    source=lhs->lsu+D2U(lhs->digits)-1; // msu of input array
4449    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4450    for (; target>=var1; target--) *target=0;
4451
4452    // rhs (var2) is left-aligned with var1 at the start
4453    var2ulen=var1units;                 // rhs logical length (units)
4454    var2units=D2U(rhs->digits);         // rhs actual length (units)
4455    var2=rhs->lsu;                      // -> rhs array
4456    msu2=var2+var2units-1;              // -> msu of var2 [never changes]
4457    // now set up the variables which will be used for estimating the
4458    // multiplication factor.  If these variables are not exact, add
4459    // 1 to make sure that the multiplier is never overestimated.
4460    msu2plus=*msu2;                     // it's value ..
4461    if (var2units>1) msu2plus++;        // .. +1 if any more
4462    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);// top two pair ..
4463    if (var2units>1) {                  // .. [else treat 2nd as 0]
4464      msu2pair+=*(msu2-1);              // ..
4465      if (var2units>2) msu2pair++;      // .. +1 if any more
4466      }
4467
4468    // The calculation is working in units, which may have leading zeros,
4469    // but the exponent was calculated on the assumption that they are
4470    // both left-aligned.  Adjust the exponent to compensate: add the
4471    // number of leading zeros in var1 msu and subtract those in var2 msu.
4472    // [This is actually done by counting the digits and negating, as
4473    // lead1=DECDPUN-digits1, and similarly for lead2.]
4474    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4475    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4476
4477    // Now, if doing an integer divide or remainder, ensure that
4478    // the result will be Unit-aligned.  To do this, shift the var1
4479    // accumulator towards least if need be.  (It's much easier to
4480    // do this now than to reassemble the residue afterwards, if
4481    // doing a remainder.)  Also ensure the exponent is not negative.
4482    if (!(op&DIVIDE)) {
4483      Unit *u;                          // work
4484      // save the initial 'false' padding of var1, in digits
4485      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4486      // Determine the shift to do.
4487      if (exponent<0) cut=-exponent;
4488       else cut=DECDPUN-exponent%DECDPUN;
4489      decShiftToLeast(var1, var1units, cut);
4490      exponent+=cut;                    // maintain numerical value
4491      var1initpad-=cut;                 // .. and reduce padding
4492      // clean any most-significant units which were just emptied
4493      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4494      } // align
4495     else { // is DIVIDE
4496      maxexponent=lhs->exponent-rhs->exponent;    // save
4497      // optimization: if the first iteration will just produce 0,
4498      // preadjust to skip it [valid for DIVIDE only]
4499      if (*msu1<*msu2) {
4500        var2ulen--;                     // shift down
4501        exponent-=DECDPUN;              // update the exponent
4502        }
4503      }
4504
4505    // ---- start the long-division loops ------------------------------
4506    accunits=0;                         // no units accumulated yet
4507    accdigits=0;                        // .. or digits
4508    accnext=acc+acclength-1;            // -> msu of acc [NB: allows digits+1]
4509    for (;;) {                          // outer forever loop
4510      thisunit=0;                       // current unit assumed 0
4511      // find the next unit
4512      for (;;) {                        // inner forever loop
4513        // strip leading zero units [from either pre-adjust or from
4514        // subtract last time around].  Leave at least one unit.
4515        for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4516
4517        if (var1units<var2ulen) break;       // var1 too low for subtract
4518        if (var1units==var2ulen) {           // unit-by-unit compare needed
4519          // compare the two numbers, from msu
4520          const Unit *pv1, *pv2;
4521          Unit v2;                           // units to compare
4522          pv2=msu2;                          // -> msu
4523          for (pv1=msu1; ; pv1--, pv2--) {
4524            // v1=*pv1 -- always OK
4525            v2=0;                            // assume in padding
4526            if (pv2>=var2) v2=*pv2;          // in range
4527            if (*pv1!=v2) break;             // no longer the same
4528            if (pv1==var1) break;            // done; leave pv1 as is
4529            }
4530          // here when all inspected or a difference seen
4531          if (*pv1<v2) break;                // var1 too low to subtract
4532          if (*pv1==v2) {                    // var1 == var2
4533            // reach here if var1 and var2 are identical; subtraction
4534            // would increase digit by one, and the residue will be 0 so
4535            // the calculation is done; leave the loop with residue=0.
4536            thisunit++;                      // as though subtracted
4537            *var1=0;                         // set var1 to 0
4538            var1units=1;                     // ..
4539            break;  // from inner
4540            } // var1 == var2
4541          // *pv1>v2.  Prepare for real subtraction; the lengths are equal
4542          // Estimate the multiplier (there's always a msu1-1)...
4543          // Bring in two units of var2 to provide a good estimate.
4544          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4545          } // lengths the same
4546         else { // var1units > var2ulen, so subtraction is safe
4547          // The var2 msu is one unit towards the lsu of the var1 msu,
4548          // so only one unit for var2 can be used.
4549          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4550          }
4551        if (mult==0) mult=1;                 // must always be at least 1
4552        // subtraction needed; var1 is > var2
4553        thisunit=(Unit)(thisunit+mult);      // accumulate
4554        // subtract var1-var2, into var1; only the overlap needs
4555        // processing, as this is an in-place calculation
4556        shift=var2ulen-var2units;
4557        #if DECTRACE
4558          decDumpAr('1', &var1[shift], var1units-shift);
4559          decDumpAr('2', var2, var2units);
4560          printf("m=%ld\n", -mult);
4561        #endif
4562        decUnitAddSub(&var1[shift], var1units-shift,
4563                      var2, var2units, 0,
4564                      &var1[shift], -mult);
4565        #if DECTRACE
4566          decDumpAr('#', &var1[shift], var1units-shift);
4567        #endif
4568        // var1 now probably has leading zeros; these are removed at the
4569        // top of the inner loop.
4570        } // inner loop
4571
4572      // The next unit has been calculated in full; unless it's a
4573      // leading zero, add to acc
4574      if (accunits!=0 || thisunit!=0) {      // is first or non-zero
4575        *accnext=thisunit;                   // store in accumulator
4576        // account exactly for the new digits
4577        if (accunits==0) {
4578          accdigits++;                       // at least one
4579          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4580          }
4581         else accdigits+=DECDPUN;
4582        accunits++;                          // update count
4583        accnext--;                           // ready for next
4584        if (accdigits>reqdigits) break;      // have enough digits
4585        }
4586
4587      // if the residue is zero, the operation is done (unless divide
4588      // or divideInteger and still not enough digits yet)
4589      if (*var1==0 && var1units==1) {        // residue is 0
4590        if (op&(REMAINDER|REMNEAR)) break;
4591        if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4592        // [drop through if divideInteger]
4593        }
4594      // also done enough if calculating remainder or integer
4595      // divide and just did the last ('units') unit
4596      if (exponent==0 && !(op&DIVIDE)) break;
4597
4598      // to get here, var1 is less than var2, so divide var2 by the per-
4599      // Unit power of ten and go for the next digit
4600      var2ulen--;                            // shift down
4601      exponent-=DECDPUN;                     // update the exponent
4602      } // outer loop
4603
4604    // ---- division is complete ---------------------------------------
4605    // here: acc      has at least reqdigits+1 of good results (or fewer
4606    //                if early stop), starting at accnext+1 (its lsu)
4607    //       var1     has any residue at the stopping point
4608    //       accunits is the number of digits collected in acc
4609    if (accunits==0) {             // acc is 0
4610      accunits=1;                  // show have a unit ..
4611      accdigits=1;                 // ..
4612      *accnext=0;                  // .. whose value is 0
4613      }
4614     else accnext++;               // back to last placed
4615    // accnext now -> lowest unit of result
4616
4617    residue=0;                     // assume no residue
4618    if (op&DIVIDE) {
4619      // record the presence of any residue, for rounding
4620      if (*var1!=0 || var1units>1) residue=1;
4621       else { // no residue
4622        // Had an exact division; clean up spurious trailing 0s.
4623        // There will be at most DECDPUN-1, from the final multiply,
4624        // and then only if the result is non-0 (and even) and the
4625        // exponent is 'loose'.
4626        #if DECDPUN>1
4627        Unit lsu=*accnext;
4628        if (!(lsu&0x01) && (lsu!=0)) {
4629          // count the trailing zeros
4630          Int drop=0;
4631          for (;; drop++) {    // [will terminate because lsu!=0]
4632            if (exponent>=maxexponent) break;     // don't chop real 0s
4633            #if DECDPUN<=4
4634              if ((lsu-QUOT10(lsu, drop+1)
4635                  *powers[drop+1])!=0) break;     // found non-0 digit
4636            #else
4637              if (lsu%powers[drop+1]!=0) break;   // found non-0 digit
4638            #endif
4639            exponent++;
4640            }
4641          if (drop>0) {
4642            accunits=decShiftToLeast(accnext, accunits, drop);
4643            accdigits=decGetDigits(accnext, accunits);
4644            accunits=D2U(accdigits);
4645            // [exponent was adjusted in the loop]
4646            }
4647          } // neither odd nor 0
4648        #endif
4649        } // exact divide
4650      } // divide
4651     else /* op!=DIVIDE */ {
4652      // check for coefficient overflow
4653      if (accdigits+exponent>reqdigits) {
4654        *status|=DEC_Division_impossible;
4655        break;
4656        }
4657      if (op & (REMAINDER|REMNEAR)) {
4658        // [Here, the exponent will be 0, because var1 was adjusted
4659        // appropriately.]
4660        Int postshift;                       // work
4661        Flag wasodd=0;                       // integer was odd
4662        Unit *quotlsu;                       // for save
4663        Int  quotdigits;                     // ..
4664
4665        bits=lhs->bits;                      // remainder sign is always as lhs
4666
4667        // Fastpath when residue is truly 0 is worthwhile [and
4668        // simplifies the code below]
4669        if (*var1==0 && var1units==1) {      // residue is 0
4670          Int exp=lhs->exponent;             // save min(exponents)
4671          if (rhs->exponent<exp) exp=rhs->exponent;
4672          decNumberZero(res);                // 0 coefficient
4673          #if DECSUBSET
4674          if (set->extended)
4675          #endif
4676          res->exponent=exp;                 // .. with proper exponent
4677          res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4678          decFinish(res, set, &residue, status);   // might clamp
4679          break;
4680          }
4681        // note if the quotient was odd
4682        if (*accnext & 0x01) wasodd=1;       // acc is odd
4683        quotlsu=accnext;                     // save in case need to reinspect
4684        quotdigits=accdigits;                // ..
4685
4686        // treat the residue, in var1, as the value to return, via acc
4687        // calculate the unused zero digits.  This is the smaller of:
4688        //   var1 initial padding (saved above)
4689        //   var2 residual padding, which happens to be given by:
4690        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4691        // [the 'exponent' term accounts for the shifts during divide]
4692        if (var1initpad<postshift) postshift=var1initpad;
4693
4694        // shift var1 the requested amount, and adjust its digits
4695        var1units=decShiftToLeast(var1, var1units, postshift);
4696        accnext=var1;
4697        accdigits=decGetDigits(var1, var1units);
4698        accunits=D2U(accdigits);
4699
4700        exponent=lhs->exponent;         // exponent is smaller of lhs & rhs
4701        if (rhs->exponent<exponent) exponent=rhs->exponent;
4702
4703        // Now correct the result if doing remainderNear; if it
4704        // (looking just at coefficients) is > rhs/2, or == rhs/2 and
4705        // the integer was odd then the result should be rem-rhs.
4706        if (op&REMNEAR) {
4707          Int compare, tarunits;        // work
4708          Unit *up;                     // ..
4709          // calculate remainder*2 into the var1 buffer (which has
4710          // 'headroom' of an extra unit and hence enough space)
4711          // [a dedicated 'double' loop would be faster, here]
4712          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4713                                 0, accnext, 1);
4714          // decDumpAr('r', accnext, tarunits);
4715
4716          // Here, accnext (var1) holds tarunits Units with twice the
4717          // remainder's coefficient, which must now be compared to the
4718          // RHS.  The remainder's exponent may be smaller than the RHS's.
4719          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4720                                 rhs->exponent-exponent);
4721          if (compare==BADINT) {             // deep trouble
4722            *status|=DEC_Insufficient_storage;
4723            break;}
4724
4725          // now restore the remainder by dividing by two; the lsu
4726          // is known to be even.
4727          for (up=accnext; up<accnext+tarunits; up++) {
4728            Int half;              // half to add to lower unit
4729            half=*up & 0x01;
4730            *up/=2;                // [shift]
4731            if (!half) continue;
4732            *(up-1)+=(DECDPUNMAX+1)/2;
4733            }
4734          // [accunits still describes the original remainder length]
4735
4736          if (compare>0 || (compare==0 && wasodd)) { // adjustment needed
4737            Int exp, expunits, exprem;       // work
4738            // This is effectively causing round-up of the quotient,
4739            // so if it was the rare case where it was full and all
4740            // nines, it would overflow and hence division-impossible
4741            // should be raised
4742            Flag allnines=0;                 // 1 if quotient all nines
4743            if (quotdigits==reqdigits) {     // could be borderline
4744              for (up=quotlsu; ; up++) {
4745                if (quotdigits>DECDPUN) {
4746                  if (*up!=DECDPUNMAX) break;// non-nines
4747                  }
4748                 else {                      // this is the last Unit
4749                  if (*up==powers[quotdigits]-1) allnines=1;
4750                  break;
4751                  }
4752                quotdigits-=DECDPUN;         // checked those digits
4753                } // up
4754              } // borderline check
4755            if (allnines) {
4756              *status|=DEC_Division_impossible;
4757              break;}
4758
4759            // rem-rhs is needed; the sign will invert.  Again, var1
4760            // can safely be used for the working Units array.
4761            exp=rhs->exponent-exponent;      // RHS padding needed
4762            // Calculate units and remainder from exponent.
4763            expunits=exp/DECDPUN;
4764            exprem=exp%DECDPUN;
4765            // subtract [A+B*(-m)]; the result will always be negative
4766            accunits=-decUnitAddSub(accnext, accunits,
4767                                    rhs->lsu, D2U(rhs->digits),
4768                                    expunits, accnext, -(Int)powers[exprem]);
4769            accdigits=decGetDigits(accnext, accunits); // count digits exactly
4770            accunits=D2U(accdigits);    // and recalculate the units for copy
4771            // [exponent is as for original remainder]
4772            bits^=DECNEG;               // flip the sign
4773            }
4774          } // REMNEAR
4775        } // REMAINDER or REMNEAR
4776      } // not DIVIDE
4777
4778    // Set exponent and bits
4779    res->exponent=exponent;
4780    res->bits=(uByte)(bits&DECNEG);          // [cleaned]
4781
4782    // Now the coefficient.
4783    decSetCoeff(res, set, accnext, accdigits, &residue, status);
4784
4785    decFinish(res, set, &residue, status);   // final cleanup
4786
4787    #if DECSUBSET
4788    // If a divide then strip trailing zeros if subset [after round]
4789    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4790    #endif
4791    } while(0);                              // end protected
4792
4793  if (varalloc!=NULL) free(varalloc);   // drop any storage used
4794  if (allocacc!=NULL) free(allocacc);   // ..
4795  #if DECSUBSET
4796  if (allocrhs!=NULL) free(allocrhs);   // ..
4797  if (alloclhs!=NULL) free(alloclhs);   // ..
4798  #endif
4799  return res;
4800  } // decDivideOp
4801
4802/* ------------------------------------------------------------------ */
4803/* decMultiplyOp -- multiplication operation                          */
4804/*                                                                    */
4805/*  This routine performs the multiplication C=A x B.                 */
4806/*                                                                    */
4807/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4808/*   lhs is A                                                         */
4809/*   rhs is B                                                         */
4810/*   set is the context                                               */
4811/*   status is the usual accumulator                                  */
4812/*                                                                    */
4813/* C must have space for set->digits digits.                          */
4814/*                                                                    */
4815/* ------------------------------------------------------------------ */
4816/* 'Classic' multiplication is used rather than Karatsuba, as the     */
4817/* latter would give only a minor improvement for the short numbers   */
4818/* expected to be handled most (and uses much more memory).           */
4819/*                                                                    */
4820/* There are two major paths here: the general-purpose ('old code')   */
4821/* path which handles all DECDPUN values, and a fastpath version      */
4822/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4823/* than two calls to decUnitAddSub would be made.                     */
4824/*                                                                    */
4825/* The fastpath version lumps units together into 8-digit or 9-digit  */
4826/* chunks, and also uses a lazy carry strategy to minimise expensive  */
4827/* 64-bit divisions.  The chunks are then broken apart again into     */
4828/* units for continuing processing.  Despite this overhead, the       */
4829/* fastpath can speed up some 16-digit operations by 10x (and much    */
4830/* more for higher-precision calculations).                           */
4831/*                                                                    */
4832/* A buffer always has to be used for the accumulator; in the         */
4833/* fastpath, buffers are also always needed for the chunked copies of */
4834/* of the operand coefficients.                                       */
4835/* Static buffers are larger than needed just for multiply, to allow  */
4836/* for calls from other operations (notably exp).                     */
4837/* ------------------------------------------------------------------ */
4838#define FASTMUL (DECUSE64 && DECDPUN<5)
4839static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4840                                 const decNumber *rhs, decContext *set,
4841                                 uInt *status) {
4842  Int    accunits;                 // Units of accumulator in use
4843  Int    exponent;                 // work
4844  Int    residue=0;                // rounding residue
4845  uByte  bits;                     // result sign
4846  Unit  *acc;                      // -> accumulator Unit array
4847  Int    needbytes;                // size calculator
4848  void  *allocacc=NULL;            // -> allocated accumulator, iff allocated
4849  Unit  accbuff[SD2U(DECBUFFER*4+1)]; // buffer (+1 for DECBUFFER==0,
4850                                   // *4 for calls from other operations)
4851  const Unit *mer, *mermsup;       // work
4852  Int   madlength;                 // Units in multiplicand
4853  Int   shift;                     // Units to shift multiplicand by
4854
4855  #if FASTMUL
4856    // if DECDPUN is 1 or 3 work in base 10**9, otherwise
4857    // (DECDPUN is 2 or 4) then work in base 10**8
4858    #if DECDPUN & 1                // odd
4859      #define FASTBASE 1000000000  // base
4860      #define FASTDIGS          9  // digits in base
4861      #define FASTLAZY         18  // carry resolution point [1->18]
4862    #else
4863      #define FASTBASE  100000000
4864      #define FASTDIGS          8
4865      #define FASTLAZY       1844  // carry resolution point [1->1844]
4866    #endif
4867    // three buffers are used, two for chunked copies of the operands
4868    // (base 10**8 or base 10**9) and one base 2**64 accumulator with
4869    // lazy carry evaluation
4870    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4871    uInt  *zlhi=zlhibuff;                 // -> lhs array
4872    uInt  *alloclhi=NULL;                 // -> allocated buffer, iff allocated
4873    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; // buffer (+1 for DECBUFFER==0)
4874    uInt  *zrhi=zrhibuff;                 // -> rhs array
4875    uInt  *allocrhi=NULL;                 // -> allocated buffer, iff allocated
4876    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; // buffer (+1 for DECBUFFER==0)
4877    // [allocacc is shared for both paths, as only one will run]
4878    uLong *zacc=zaccbuff;          // -> accumulator array for exact result
4879    #if DECDPUN==1
4880    Int    zoff;                   // accumulator offset
4881    #endif
4882    uInt  *lip, *rip;              // item pointers
4883    uInt  *lmsi, *rmsi;            // most significant items
4884    Int    ilhs, irhs, iacc;       // item counts in the arrays
4885    Int    lazy;                   // lazy carry counter
4886    uLong  lcarry;                 // uLong carry
4887    uInt   carry;                  // carry (NB not uLong)
4888    Int    count;                  // work
4889    const  Unit *cup;              // ..
4890    Unit  *up;                     // ..
4891    uLong *lp;                     // ..
4892    Int    p;                      // ..
4893  #endif
4894
4895  #if DECSUBSET
4896    decNumber *alloclhs=NULL;      // -> allocated buffer, iff allocated
4897    decNumber *allocrhs=NULL;      // -> allocated buffer, iff allocated
4898  #endif
4899
4900  #if DECCHECK
4901  if (decCheckOperands(res, lhs, rhs, set)) return res;
4902  #endif
4903
4904  // precalculate result sign
4905  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4906
4907  // handle infinities and NaNs
4908  if (SPECIALARGS) {               // a special bit set
4909    if (SPECIALARGS & (DECSNAN | DECNAN)) { // one or two NaNs
4910      decNaNs(res, lhs, rhs, set, status);
4911      return res;}
4912    // one or two infinities; Infinity * 0 is invalid
4913    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4914      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4915      *status|=DEC_Invalid_operation;
4916      return res;}
4917    decNumberZero(res);
4918    res->bits=bits|DECINF;         // infinity
4919    return res;}
4920
4921  // For best speed, as in DMSRCN [the original Rexx numerics
4922  // module], use the shorter number as the multiplier (rhs) and
4923  // the longer as the multiplicand (lhs) to minimise the number of
4924  // adds (partial products)
4925  if (lhs->digits<rhs->digits) {   // swap...
4926    const decNumber *hold=lhs;
4927    lhs=rhs;
4928    rhs=hold;
4929    }
4930
4931  do {                             // protect allocated storage
4932    #if DECSUBSET
4933    if (!set->extended) {
4934      // reduce operands and set lostDigits status, as needed
4935      if (lhs->digits>set->digits) {
4936        alloclhs=decRoundOperand(lhs, set, status);
4937        if (alloclhs==NULL) break;
4938        lhs=alloclhs;
4939        }
4940      if (rhs->digits>set->digits) {
4941        allocrhs=decRoundOperand(rhs, set, status);
4942        if (allocrhs==NULL) break;
4943        rhs=allocrhs;
4944        }
4945      }
4946    #endif
4947    // [following code does not require input rounding]
4948
4949    #if FASTMUL                    // fastpath can be used
4950    // use the fast path if there are enough digits in the shorter
4951    // operand to make the setup and takedown worthwhile
4952    #define NEEDTWO (DECDPUN*2)    // within two decUnitAddSub calls
4953    if (rhs->digits>NEEDTWO) {     // use fastpath...
4954      // calculate the number of elements in each array
4955      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; // [ceiling]
4956      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; // ..
4957      iacc=ilhs+irhs;
4958
4959      // allocate buffers if required, as usual
4960      needbytes=ilhs*sizeof(uInt);
4961      if (needbytes>(Int)sizeof(zlhibuff)) {
4962        alloclhi=(uInt *)malloc(needbytes);
4963        zlhi=alloclhi;}
4964      needbytes=irhs*sizeof(uInt);
4965      if (needbytes>(Int)sizeof(zrhibuff)) {
4966        allocrhi=(uInt *)malloc(needbytes);
4967        zrhi=allocrhi;}
4968
4969      // Allocating the accumulator space needs a special case when
4970      // DECDPUN=1 because when converting the accumulator to Units
4971      // after the multiplication each 8-byte item becomes 9 1-byte
4972      // units.  Therefore iacc extra bytes are needed at the front
4973      // (rounded up to a multiple of 8 bytes), and the uLong
4974      // accumulator starts offset the appropriate number of units
4975      // to the right to avoid overwrite during the unchunking.
4976      needbytes=iacc*sizeof(uLong);
4977      #if DECDPUN==1
4978      zoff=(iacc+7)/8;        // items to offset by
4979      needbytes+=zoff*8;
4980      #endif
4981      if (needbytes>(Int)sizeof(zaccbuff)) {
4982        allocacc=(uLong *)malloc(needbytes);
4983        zacc=(uLong *)allocacc;}
4984      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4985        *status|=DEC_Insufficient_storage;
4986        break;}
4987
4988      acc=(Unit *)zacc;       // -> target Unit array
4989      #if DECDPUN==1
4990      zacc+=zoff;             // start uLong accumulator to right
4991      #endif
4992
4993      // assemble the chunked copies of the left and right sides
4994      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4995        for (p=0, *lip=0; p<FASTDIGS && count>0;
4996             p+=DECDPUN, cup++, count-=DECDPUN)
4997          *lip+=*cup*powers[p];
4998      lmsi=lip-1;     // save -> msi
4999      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5000        for (p=0, *rip=0; p<FASTDIGS && count>0;
5001             p+=DECDPUN, cup++, count-=DECDPUN)
5002          *rip+=*cup*powers[p];
5003      rmsi=rip-1;     // save -> msi
5004
5005      // zero the accumulator
5006      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5007
5008      /* Start the multiplication */
5009      // Resolving carries can dominate the cost of accumulating the
5010      // partial products, so this is only done when necessary.
5011      // Each uLong item in the accumulator can hold values up to
5012      // 2**64-1, and each partial product can be as large as
5013      // (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to
5014      // itself 18.4 times in a uLong without overflowing, so during
5015      // the main calculation resolution is carried out every 18th
5016      // add -- every 162 digits.  Similarly, when FASTDIGS=8, the
5017      // partial products can be added to themselves 1844.6 times in
5018      // a uLong without overflowing, so intermediate carry
5019      // resolution occurs only every 14752 digits.  Hence for common
5020      // short numbers usually only the one final carry resolution
5021      // occurs.
5022      // (The count is set via FASTLAZY to simplify experiments to
5023      // measure the value of this approach: a 35% improvement on a
5024      // [34x34] multiply.)
5025      lazy=FASTLAZY;                         // carry delay count
5026      for (rip=zrhi; rip<=rmsi; rip++) {     // over each item in rhs
5027        lp=zacc+(rip-zrhi);                  // where to add the lhs
5028        for (lip=zlhi; lip<=lmsi; lip++, lp++) { // over each item in lhs
5029          *lp+=(uLong)(*lip)*(*rip);         // [this should in-line]
5030          } // lip loop
5031        lazy--;
5032        if (lazy>0 && rip!=rmsi) continue;
5033        lazy=FASTLAZY;                       // reset delay count
5034        // spin up the accumulator resolving overflows
5035        for (lp=zacc; lp<zacc+iacc; lp++) {
5036          if (*lp<FASTBASE) continue;        // it fits
5037          lcarry=*lp/FASTBASE;               // top part [slow divide]
5038          // lcarry can exceed 2**32-1, so check again; this check
5039          // and occasional extra divide (slow) is well worth it, as
5040          // it allows FASTLAZY to be increased to 18 rather than 4
5041          // in the FASTDIGS=9 case
5042          if (lcarry<FASTBASE) carry=(uInt)lcarry;  // [usual]
5043           else { // two-place carry [fairly rare]
5044            uInt carry2=(uInt)(lcarry/FASTBASE);    // top top part
5045            *(lp+2)+=carry2;                        // add to item+2
5046            *lp-=((uLong)FASTBASE*FASTBASE*carry2); // [slow]
5047            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); // [inline]
5048            }
5049          *(lp+1)+=carry;                    // add to item above [inline]
5050          *lp-=((uLong)FASTBASE*carry);      // [inline]
5051          } // carry resolution
5052        } // rip loop
5053
5054      // The multiplication is complete; time to convert back into
5055      // units.  This can be done in-place in the accumulator and in
5056      // 32-bit operations, because carries were resolved after the
5057      // final add.  This needs N-1 divides and multiplies for
5058      // each item in the accumulator (which will become up to N
5059      // units, where 2<=N<=9).
5060      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5061        uInt item=(uInt)*lp;                 // decapitate to uInt
5062        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5063          uInt part=item/(DECDPUNMAX+1);
5064          *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5065          item=part;
5066          } // p
5067        *up=(Unit)item; up++;                // [final needs no division]
5068        } // lp
5069      accunits=up-acc;                       // count of units
5070      }
5071     else { // here to use units directly, without chunking ['old code']
5072    #endif
5073
5074      // if accumulator will be too long for local storage, then allocate
5075      acc=accbuff;                 // -> assume buffer for accumulator
5076      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5077      if (needbytes>(Int)sizeof(accbuff)) {
5078        allocacc=(Unit *)malloc(needbytes);
5079        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5080        acc=(Unit *)allocacc;                // use the allocated space
5081        }
5082
5083      /* Now the main long multiplication loop */
5084      // Unlike the equivalent in the IBM Java implementation, there
5085      // is no advantage in calculating from msu to lsu.  So, do it
5086      // by the book, as it were.
5087      // Each iteration calculates ACC=ACC+MULTAND*MULT
5088      accunits=1;                  // accumulator starts at '0'
5089      *acc=0;                      // .. (lsu=0)
5090      shift=0;                     // no multiplicand shift at first
5091      madlength=D2U(lhs->digits);  // this won't change
5092      mermsup=rhs->lsu+D2U(rhs->digits); // -> msu+1 of multiplier
5093
5094      for (mer=rhs->lsu; mer<mermsup; mer++) {
5095        // Here, *mer is the next Unit in the multiplier to use
5096        // If non-zero [optimization] add it...
5097        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5098                                            lhs->lsu, madlength, 0,
5099                                            &acc[shift], *mer)
5100                                            + shift;
5101         else { // extend acc with a 0; it will be used shortly
5102          *(acc+accunits)=0;       // [this avoids length of <=0 later]
5103          accunits++;
5104          }
5105        // multiply multiplicand by 10**DECDPUN for next Unit to left
5106        shift++;                   // add this for 'logical length'
5107        } // n
5108    #if FASTMUL
5109      } // unchunked units
5110    #endif
5111    // common end-path
5112    #if DECTRACE
5113      decDumpAr('*', acc, accunits);         // Show exact result
5114    #endif
5115
5116    // acc now contains the exact result of the multiplication,
5117    // possibly with a leading zero unit; build the decNumber from
5118    // it, noting if any residue
5119    res->bits=bits;                          // set sign
5120    res->digits=decGetDigits(acc, accunits); // count digits exactly
5121
5122    // There can be a 31-bit wrap in calculating the exponent.
5123    // This can only happen if both input exponents are negative and
5124    // both their magnitudes are large.  If there was a wrap, set a
5125    // safe very negative exponent, from which decFinalize() will
5126    // raise a hard underflow shortly.
5127    exponent=lhs->exponent+rhs->exponent;    // calculate exponent
5128    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5129      exponent=-2*DECNUMMAXE;                // force underflow
5130    res->exponent=exponent;                  // OK to overwrite now
5131
5132
5133    // Set the coefficient.  If any rounding, residue records
5134    decSetCoeff(res, set, acc, res->digits, &residue, status);
5135    decFinish(res, set, &residue, status);   // final cleanup
5136    } while(0);                         // end protected
5137
5138  if (allocacc!=NULL) free(allocacc);   // drop any storage used
5139  #if DECSUBSET
5140  if (allocrhs!=NULL) free(allocrhs);   // ..
5141  if (alloclhs!=NULL) free(alloclhs);   // ..
5142  #endif
5143  #if FASTMUL
5144  if (allocrhi!=NULL) free(allocrhi);   // ..
5145  if (alloclhi!=NULL) free(alloclhi);   // ..
5146  #endif
5147  return res;
5148  } // decMultiplyOp
5149
5150/* ------------------------------------------------------------------ */
5151/* decExpOp -- effect exponentiation                                  */
5152/*                                                                    */
5153/*   This computes C = exp(A)                                         */
5154/*                                                                    */
5155/*   res is C, the result.  C may be A                                */
5156/*   rhs is A                                                         */
5157/*   set is the context; note that rounding mode has no effect        */
5158/*                                                                    */
5159/* C must have space for set->digits digits. status is updated but    */
5160/* not set.                                                           */
5161/*                                                                    */
5162/* Restrictions:                                                      */
5163/*                                                                    */
5164/*   digits, emax, and -emin in the context must be less than         */
5165/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5166/*   bounds or a zero.  This is an internal routine, so these         */
5167/*   restrictions are contractual and not enforced.                   */
5168/*                                                                    */
5169/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5170/* almost always be correctly rounded, but may be up to 1 ulp in      */
5171/* error in rare cases.                                               */
5172/*                                                                    */
5173/* Finite results will always be full precision and Inexact, except   */
5174/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5175/* ------------------------------------------------------------------ */
5176/* This approach used here is similar to the algorithm described in   */
5177/*                                                                    */
5178/*   Variable Precision Exponential Function, T. E. Hull and          */
5179/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5180/*   pp79-91, ACM, June 1986.                                         */
5181/*                                                                    */
5182/* with the main difference being that the iterations in the series   */
5183/* evaluation are terminated dynamically (which does not require the  */
5184/* extra variable-precision variables which are expensive in this     */
5185/* context).                                                          */
5186/*                                                                    */
5187/* The error analysis in Hull & Abrham's paper applies except for the */
5188/* round-off error accumulation during the series evaluation.  This   */
5189/* code does not precalculate the number of iterations and so cannot  */
5190/* use Horner's scheme.  Instead, the accumulation is done at double- */
5191/* precision, which ensures that the additions of the terms are exact */
5192/* and do not accumulate round-off (and any round-off errors in the   */
5193/* terms themselves move 'to the right' faster than they can          */
5194/* accumulate).  This code also extends the calculation by allowing,  */
5195/* in the spirit of other decNumber operators, the input to be more   */
5196/* precise than the result (the precision used is based on the more   */
5197/* precise of the input or requested result).                         */
5198/*                                                                    */
5199/* Implementation notes:                                              */
5200/*                                                                    */
5201/* 1. This is separated out as decExpOp so it can be called from      */
5202/*    other Mathematical functions (notably Ln) with a wider range    */
5203/*    than normal.  In particular, it can handle the slightly wider   */
5204/*    (double) range needed by Ln (which has to be able to calculate  */
5205/*    exp(-x) where x can be the tiniest number (Ntiny).              */
5206/*                                                                    */
5207/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5208/*    iterations by appoximately a third with additional (although    */
5209/*    diminishing) returns as the range is reduced to even smaller    */
5210/*    fractions.  However, h (the power of 10 used to correct the     */
5211/*    result at the end, see below) must be kept <=8 as otherwise     */
5212/*    the final result cannot be computed.  Hence the leverage is a   */
5213/*    sliding value (8-h), where potentially the range is reduced     */
5214/*    more for smaller values.                                        */
5215/*                                                                    */
5216/*    The leverage that can be applied in this way is severely        */
5217/*    limited by the cost of the raise-to-the power at the end,       */
5218/*    which dominates when the number of iterations is small (less    */
5219/*    than ten) or when rhs is short.  As an example, the adjustment  */
5220/*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5221/*                                                                    */
5222/* 3. The restrictions (especially precision) could be raised with    */
5223/*    care, but the full decNumber range seems very hard within the   */
5224/*    32-bit limits.                                                  */
5225/*                                                                    */
5226/* 4. The working precisions for the static buffers are twice the     */
5227/*    obvious size to allow for calls from decNumberPower.            */
5228/* ------------------------------------------------------------------ */
5229decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5230                         decContext *set, uInt *status) {
5231  uInt ignore=0;                   // working status
5232  Int h;                           // adjusted exponent for 0.xxxx
5233  Int p;                           // working precision
5234  Int residue;                     // rounding residue
5235  uInt needbytes;                  // for space calculations
5236  const decNumber *x=rhs;          // (may point to safe copy later)
5237  decContext aset, tset, dset;     // working contexts
5238  Int comp;                        // work
5239
5240  // the argument is often copied to normalize it, so (unusually) it
5241  // is treated like other buffers, using DECBUFFER, +1 in case
5242  // DECBUFFER is 0
5243  decNumber bufr[D2N(DECBUFFER*2+1)];
5244  decNumber *allocrhs=NULL;        // non-NULL if rhs buffer allocated
5245
5246  // the working precision will be no more than set->digits+8+1
5247  // so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER
5248  // is 0 (and twice that for the accumulator)
5249
5250  // buffer for t, term (working precision plus)
5251  decNumber buft[D2N(DECBUFFER*2+9+1)];
5252  decNumber *allocbuft=NULL;       // -> allocated buft, iff allocated
5253  decNumber *t=buft;               // term
5254  // buffer for a, accumulator (working precision * 2), at least 9
5255  decNumber bufa[D2N(DECBUFFER*4+18+1)];
5256  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5257  decNumber *a=bufa;               // accumulator
5258  // decNumber for the divisor term; this needs at most 9 digits
5259  // and so can be fixed size [16 so can use standard context]
5260  decNumber bufd[D2N(16)];
5261  decNumber *d=bufd;               // divisor
5262  decNumber numone;                // constant 1
5263
5264  #if DECCHECK
5265  Int iterations=0;                // for later sanity check
5266  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5267  #endif
5268
5269  do {                                  // protect allocated storage
5270    if (SPECIALARG) {                   // handle infinities and NaNs
5271      if (decNumberIsInfinite(rhs)) {   // an infinity
5272        if (decNumberIsNegative(rhs))   // -Infinity -> +0
5273          decNumberZero(res);
5274         else decNumberCopy(res, rhs);  // +Infinity -> self
5275        }
5276       else decNaNs(res, rhs, NULL, set, status); // a NaN
5277      break;}
5278
5279    if (ISZERO(rhs)) {                  // zeros -> exact 1
5280      decNumberZero(res);               // make clean 1
5281      *res->lsu=1;                      // ..
5282      break;}                           // [no status to set]
5283
5284    // e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path
5285    // positive and negative tiny cases which will result in inexact
5286    // 1.  This also allows the later add-accumulate to always be
5287    // exact (because its length will never be more than twice the
5288    // working precision).
5289    // The comparator (tiny) needs just one digit, so use the
5290    // decNumber d for it (reused as the divisor, etc., below); its
5291    // exponent is such that if x is positive it will have
5292    // set->digits-1 zeros between the decimal point and the digit,
5293    // which is 4, and if x is negative one more zero there as the
5294    // more precise result will be of the form 0.9999999 rather than
5295    // 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0
5296    // or 0.00000004 if digits=7 and x<0.  If RHS not larger than
5297    // this then the result will be 1.000000
5298    decNumberZero(d);                   // clean
5299    *d->lsu=4;                          // set 4 ..
5300    d->exponent=-set->digits;           // * 10**(-d)
5301    if (decNumberIsNegative(rhs)) d->exponent--;  // negative case
5302    comp=decCompare(d, rhs, 1);         // signless compare
5303    if (comp==BADINT) {
5304      *status|=DEC_Insufficient_storage;
5305      break;}
5306    if (comp>=0) {                      // rhs < d
5307      Int shift=set->digits-1;
5308      decNumberZero(res);               // set 1
5309      *res->lsu=1;                      // ..
5310      res->digits=decShiftToMost(res->lsu, 1, shift);
5311      res->exponent=-shift;                  // make 1.0000...
5312      *status|=DEC_Inexact | DEC_Rounded;    // .. inexactly
5313      break;} // tiny
5314
5315    // set up the context to be used for calculating a, as this is
5316    // used on both paths below
5317    decContextDefault(&aset, DEC_INIT_DECIMAL64);
5318    // accumulator bounds are as requested (could underflow)
5319    aset.emax=set->emax;                // usual bounds
5320    aset.emin=set->emin;                // ..
5321    aset.clamp=0;                       // and no concrete format
5322
5323    // calculate the adjusted (Hull & Abrham) exponent (where the
5324    // decimal point is just to the left of the coefficient msd)
5325    h=rhs->exponent+rhs->digits;
5326    // if h>8 then 10**h cannot be calculated safely; however, when
5327    // h=8 then exp(|rhs|) will be at least exp(1E+7) which is at
5328    // least 6.59E+4342944, so (due to the restriction on Emax/Emin)
5329    // overflow (or underflow to 0) is guaranteed -- so this case can
5330    // be handled by simply forcing the appropriate excess
5331    if (h>8) {                          // overflow/underflow
5332      // set up here so Power call below will over or underflow to
5333      // zero; set accumulator to either 2 or 0.02
5334      // [stack buffer for a is always big enough for this]
5335      decNumberZero(a);
5336      *a->lsu=2;                        // not 1 but < exp(1)
5337      if (decNumberIsNegative(rhs)) a->exponent=-2; // make 0.02
5338      h=8;                              // clamp so 10**h computable
5339      p=9;                              // set a working precision
5340      }
5341     else {                             // h<=8
5342      Int maxlever=(rhs->digits>8?1:0);
5343      // [could/should increase this for precisions >40 or so, too]
5344
5345      // if h is 8, cannot normalize to a lower upper limit because
5346      // the final result will not be computable (see notes above),
5347      // but leverage can be applied whenever h is less than 8.
5348      // Apply as much as possible, up to a MAXLEVER digits, which
5349      // sets the tradeoff against the cost of the later a**(10**h).
5350      // As h is increased, the working precision below also
5351      // increases to compensate for the "constant digits at the
5352      // front" effect.
5353      Int lever=MINI(8-h, maxlever);    // leverage attainable
5354      Int use=-rhs->digits-lever;       // exponent to use for RHS
5355      h+=lever;                         // apply leverage selected
5356      if (h<0) {                        // clamp
5357        use+=h;                         // [may end up subnormal]
5358        h=0;
5359        }
5360      // Take a copy of RHS if it needs normalization (true whenever x>=1)
5361      if (rhs->exponent!=use) {
5362        decNumber *newrhs=bufr;         // assume will fit on stack
5363        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5364        if (needbytes>sizeof(bufr)) {   // need malloc space
5365          allocrhs=(decNumber *)malloc(needbytes);
5366          if (allocrhs==NULL) {         // hopeless -- abandon
5367            *status|=DEC_Insufficient_storage;
5368            break;}
5369          newrhs=allocrhs;              // use the allocated space
5370          }
5371        decNumberCopy(newrhs, rhs);     // copy to safe space
5372        newrhs->exponent=use;           // normalize; now <1
5373        x=newrhs;                       // ready for use
5374        // decNumberShow(x);
5375        }
5376
5377      // Now use the usual power series to evaluate exp(x).  The
5378      // series starts as 1 + x + x^2/2 ... so prime ready for the
5379      // third term by setting the term variable t=x, the accumulator
5380      // a=1, and the divisor d=2.
5381
5382      // First determine the working precision.  From Hull & Abrham
5383      // this is set->digits+h+2.  However, if x is 'over-precise' we
5384      // need to allow for all its digits to potentially participate
5385      // (consider an x where all the excess digits are 9s) so in
5386      // this case use x->digits+h+2
5387      p=MAXI(x->digits, set->digits)+h+2;    // [h<=8]
5388
5389      // a and t are variable precision, and depend on p, so space
5390      // must be allocated for them if necessary
5391
5392      // the accumulator needs to be able to hold 2p digits so that
5393      // the additions on the second and subsequent iterations are
5394      // sufficiently exact.
5395      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5396      if (needbytes>sizeof(bufa)) {     // need malloc space
5397        allocbufa=(decNumber *)malloc(needbytes);
5398        if (allocbufa==NULL) {          // hopeless -- abandon
5399          *status|=DEC_Insufficient_storage;
5400          break;}
5401        a=allocbufa;                    // use the allocated space
5402        }
5403      // the term needs to be able to hold p digits (which is
5404      // guaranteed to be larger than x->digits, so the initial copy
5405      // is safe); it may also be used for the raise-to-power
5406      // calculation below, which needs an extra two digits
5407      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5408      if (needbytes>sizeof(buft)) {     // need malloc space
5409        allocbuft=(decNumber *)malloc(needbytes);
5410        if (allocbuft==NULL) {          // hopeless -- abandon
5411          *status|=DEC_Insufficient_storage;
5412          break;}
5413        t=allocbuft;                    // use the allocated space
5414        }
5415
5416      decNumberCopy(t, x);              // term=x
5417      decNumberZero(a); *a->lsu=1;      // accumulator=1
5418      decNumberZero(d); *d->lsu=2;      // divisor=2
5419      decNumberZero(&numone); *numone.lsu=1; // constant 1 for increment
5420
5421      // set up the contexts for calculating a, t, and d
5422      decContextDefault(&tset, DEC_INIT_DECIMAL64);
5423      dset=tset;
5424      // accumulator bounds are set above, set precision now
5425      aset.digits=p*2;                  // double
5426      // term bounds avoid any underflow or overflow
5427      tset.digits=p;
5428      tset.emin=DEC_MIN_EMIN;           // [emax is plenty]
5429      // [dset.digits=16, etc., are sufficient]
5430
5431      // finally ready to roll
5432      for (;;) {
5433        #if DECCHECK
5434        iterations++;
5435        #endif
5436        // only the status from the accumulation is interesting
5437        // [but it should remain unchanged after first add]
5438        decAddOp(a, a, t, &aset, 0, status);           // a=a+t
5439        decMultiplyOp(t, t, x, &tset, &ignore);        // t=t*x
5440        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  // t=t/d
5441        // the iteration ends when the term cannot affect the result,
5442        // if rounded to p digits, which is when its value is smaller
5443        // than the accumulator by p+1 digits.  There must also be
5444        // full precision in a.
5445        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5446            && (a->digits>=p)) break;
5447        decAddOp(d, d, &numone, &dset, 0, &ignore);    // d=d+1
5448        } // iterate
5449
5450      #if DECCHECK
5451      // just a sanity check; comment out test to show always
5452      if (iterations>p+3)
5453        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5454               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5455      #endif
5456      } // h<=8
5457
5458    // apply postconditioning: a=a**(10**h) -- this is calculated
5459    // at a slightly higher precision than Hull & Abrham suggest
5460    if (h>0) {
5461      Int seenbit=0;               // set once a 1-bit is seen
5462      Int i;                       // counter
5463      Int n=powers[h];             // always positive
5464      aset.digits=p+2;             // sufficient precision
5465      // avoid the overhead and many extra digits of decNumberPower
5466      // as all that is needed is the short 'multipliers' loop; here
5467      // accumulate the answer into t
5468      decNumberZero(t); *t->lsu=1; // acc=1
5469      for (i=1;;i++){              // for each bit [top bit ignored]
5470        // abandon if have had overflow or terminal underflow
5471        if (*status & (DEC_Overflow|DEC_Underflow)) { // interesting?
5472          if (*status&DEC_Overflow || ISZERO(t)) break;}
5473        n=n<<1;                    // move next bit to testable position
5474        if (n<0) {                 // top bit is set
5475          seenbit=1;               // OK, have a significant bit
5476          decMultiplyOp(t, t, a, &aset, status); // acc=acc*x
5477          }
5478        if (i==31) break;          // that was the last bit
5479        if (!seenbit) continue;    // no need to square 1
5480        decMultiplyOp(t, t, t, &aset, status); // acc=acc*acc [square]
5481        } /*i*/ // 32 bits
5482      // decNumberShow(t);
5483      a=t;                         // and carry on using t instead of a
5484      }
5485
5486    // Copy and round the result to res
5487    residue=1;                          // indicate dirt to right ..
5488    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5489    aset.digits=set->digits;            // [use default rounding]
5490    decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5491    decFinish(res, set, &residue, status);       // cleanup/set flags
5492    } while(0);                         // end protected
5493
5494  if (allocrhs !=NULL) free(allocrhs);  // drop any storage used
5495  if (allocbufa!=NULL) free(allocbufa); // ..
5496  if (allocbuft!=NULL) free(allocbuft); // ..
5497  // [status is handled by caller]
5498  return res;
5499  } // decExpOp
5500
5501/* ------------------------------------------------------------------ */
5502/* Initial-estimate natural logarithm table                           */
5503/*                                                                    */
5504/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5505/*           The result is a 4-digit encode of the coefficient (c=the */
5506/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5507/*           exponent (e=the bottom 2 bits encoding 0-3)              */
5508/*                                                                    */
5509/*           The resulting value is given by:                         */
5510/*                                                                    */
5511/*             v = -c * 10**(-e-3)                                    */
5512/*                                                                    */
5513/*           where e and c are extracted from entry k = LNnn[x-10]    */
5514/*           where x is truncated (NB) into the range 10 through 99,  */
5515/*           and then c = k>>2 and e = k&3.                           */
5516/* ------------------------------------------------------------------ */
5517const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5518  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5519  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5520 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5521 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5522 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5523 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5524 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5525  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5526 10130,  6046, 20055};
5527
5528/* ------------------------------------------------------------------ */
5529/* decLnOp -- effect natural logarithm                                */
5530/*                                                                    */
5531/*   This computes C = ln(A)                                          */
5532/*                                                                    */
5533/*   res is C, the result.  C may be A                                */
5534/*   rhs is A                                                         */
5535/*   set is the context; note that rounding mode has no effect        */
5536/*                                                                    */
5537/* C must have space for set->digits digits.                          */
5538/*                                                                    */
5539/* Notable cases:                                                     */
5540/*   A<0 -> Invalid                                                   */
5541/*   A=0 -> -Infinity (Exact)                                         */
5542/*   A=+Infinity -> +Infinity (Exact)                                 */
5543/*   A=1 exactly -> 0 (Exact)                                         */
5544/*                                                                    */
5545/* Restrictions (as for Exp):                                         */
5546/*                                                                    */
5547/*   digits, emax, and -emin in the context must be less than         */
5548/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5549/*   bounds or a zero.  This is an internal routine, so these         */
5550/*   restrictions are contractual and not enforced.                   */
5551/*                                                                    */
5552/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5553/* almost always be correctly rounded, but may be up to 1 ulp in      */
5554/* error in rare cases.                                               */
5555/* ------------------------------------------------------------------ */
5556/* The result is calculated using Newton's method, with each          */
5557/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5558/* Epperson 1989.                                                     */
5559/*                                                                    */
5560/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5561/* This has to be calculated at the sum of the precision of x and the */
5562/* working precision.                                                 */
5563/*                                                                    */
5564/* Implementation notes:                                              */
5565/*                                                                    */
5566/* 1. This is separated out as decLnOp so it can be called from       */
5567/*    other Mathematical functions (e.g., Log 10) with a wider range  */
5568/*    than normal.  In particular, it can handle the slightly wider   */
5569/*    (+9+2) range needed by a power function.                        */
5570/*                                                                    */
5571/* 2. The speed of this function is about 10x slower than exp, as     */
5572/*    it typically needs 4-6 iterations for short numbers, and the    */
5573/*    extra precision needed adds a squaring effect, twice.           */
5574/*                                                                    */
5575/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5576/*    as these are common requests.  ln(10) is used by log10(x).      */
5577/*                                                                    */
5578/* 4. An iteration might be saved by widening the LNnn table, and     */
5579/*    would certainly save at least one if it were made ten times     */
5580/*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5581/*    However, for most practical evaluations, at least four or five  */
5582/*    iterations will be neede -- so this would only speed up by      */
5583/*    20-25% and that probably does not justify increasing the table  */
5584/*    size.                                                           */
5585/*                                                                    */
5586/* 5. The static buffers are larger than might be expected to allow   */
5587/*    for calls from decNumberPower.                                  */
5588/* ------------------------------------------------------------------ */
5589decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5590                    decContext *set, uInt *status) {
5591  uInt ignore=0;                   // working status accumulator
5592  uInt needbytes;                  // for space calculations
5593  Int residue;                     // rounding residue
5594  Int r;                           // rhs=f*10**r [see below]
5595  Int p;                           // working precision
5596  Int pp;                          // precision for iteration
5597  Int t;                           // work
5598
5599  // buffers for a (accumulator, typically precision+2) and b
5600  // (adjustment calculator, same size)
5601  decNumber bufa[D2N(DECBUFFER+12)];
5602  decNumber *allocbufa=NULL;       // -> allocated bufa, iff allocated
5603  decNumber *a=bufa;               // accumulator/work
5604  decNumber bufb[D2N(DECBUFFER*2+2)];
5605  decNumber *allocbufb=NULL;       // -> allocated bufa, iff allocated
5606  decNumber *b=bufb;               // adjustment/work
5607
5608  decNumber  numone;               // constant 1
5609  decNumber  cmp;                  // work
5610  decContext aset, bset;           // working contexts
5611
5612  #if DECCHECK
5613  Int iterations=0;                // for later sanity check
5614  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5615  #endif
5616
5617  do {                                  // protect allocated storage
5618    if (SPECIALARG) {                   // handle infinities and NaNs
5619      if (decNumberIsInfinite(rhs)) {   // an infinity
5620        if (decNumberIsNegative(rhs))   // -Infinity -> error
5621          *status|=DEC_Invalid_operation;
5622         else decNumberCopy(res, rhs);  // +Infinity -> self
5623        }
5624       else decNaNs(res, rhs, NULL, set, status); // a NaN
5625      break;}
5626
5627    if (ISZERO(rhs)) {                  // +/- zeros -> -Infinity
5628      decNumberZero(res);               // make clean
5629      res->bits=DECINF|DECNEG;          // set - infinity
5630      break;}                           // [no status to set]
5631
5632    // Non-zero negatives are bad...
5633    if (decNumberIsNegative(rhs)) {     // -x -> error
5634      *status|=DEC_Invalid_operation;
5635      break;}
5636
5637    // Here, rhs is positive, finite, and in range
5638
5639    // lookaside fastpath code for ln(2) and ln(10) at common lengths
5640    if (rhs->exponent==0 && set->digits<=40) {
5641      #if DECDPUN==1
5642      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { // ln(10)
5643      #else
5644      if (rhs->lsu[0]==10 && rhs->digits==2) {                  // ln(10)
5645      #endif
5646        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5647        #define LN10 "2.302585092994045684017991454684364207601"
5648        decNumberFromString(res, LN10, &aset);
5649        *status|=(DEC_Inexact | DEC_Rounded); // is inexact
5650        break;}
5651      if (rhs->lsu[0]==2 && rhs->digits==1) { // ln(2)
5652        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5653        #define LN2 "0.6931471805599453094172321214581765680755"
5654        decNumberFromString(res, LN2, &aset);
5655        *status|=(DEC_Inexact | DEC_Rounded);
5656        break;}
5657      } // integer and short
5658
5659    // Determine the working precision.  This is normally the
5660    // requested precision + 2, with a minimum of 9.  However, if
5661    // the rhs is 'over-precise' then allow for all its digits to
5662    // potentially participate (consider an rhs where all the excess
5663    // digits are 9s) so in this case use rhs->digits+2.
5664    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5665
5666    // Allocate space for the accumulator and the high-precision
5667    // adjustment calculator, if necessary.  The accumulator must
5668    // be able to hold p digits, and the adjustment up to
5669    // rhs->digits+p digits.  They are also made big enough for 16
5670    // digits so that they can be used for calculating the initial
5671    // estimate.
5672    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5673    if (needbytes>sizeof(bufa)) {     // need malloc space
5674      allocbufa=(decNumber *)malloc(needbytes);
5675      if (allocbufa==NULL) {          // hopeless -- abandon
5676        *status|=DEC_Insufficient_storage;
5677        break;}
5678      a=allocbufa;                    // use the allocated space
5679      }
5680    pp=p+rhs->digits;
5681    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5682    if (needbytes>sizeof(bufb)) {     // need malloc space
5683      allocbufb=(decNumber *)malloc(needbytes);
5684      if (allocbufb==NULL) {          // hopeless -- abandon
5685        *status|=DEC_Insufficient_storage;
5686        break;}
5687      b=allocbufb;                    // use the allocated space
5688      }
5689
5690    // Prepare an initial estimate in acc. Calculate this by
5691    // considering the coefficient of x to be a normalized fraction,
5692    // f, with the decimal point at far left and multiplied by
5693    // 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and
5694    //   ln(x) = ln(f) + ln(10)*r
5695    // Get the initial estimate for ln(f) from a small lookup
5696    // table (see above) indexed by the first two digits of f,
5697    // truncated.
5698
5699    decContextDefault(&aset, DEC_INIT_DECIMAL64); // 16-digit extended
5700    r=rhs->exponent+rhs->digits;        // 'normalised' exponent
5701    decNumberFromInt32(a, r);           // a=r
5702    decNumberFromInt32(b, 2302585);     // b=ln(10) (2.302585)
5703    b->exponent=-6;                     //  ..
5704    decMultiplyOp(a, a, b, &aset, &ignore);  // a=a*b
5705    // now get top two digits of rhs into b by simple truncate and
5706    // force to integer
5707    residue=0;                          // (no residue)
5708    aset.digits=2; aset.round=DEC_ROUND_DOWN;
5709    decCopyFit(b, rhs, &aset, &residue, &ignore); // copy & shorten
5710    b->exponent=0;                      // make integer
5711    t=decGetInt(b);                     // [cannot fail]
5712    if (t<10) t=X10(t);                 // adjust single-digit b
5713    t=LNnn[t-10];                       // look up ln(b)
5714    decNumberFromInt32(b, t>>2);        // b=ln(b) coefficient
5715    b->exponent=-(t&3)-3;               // set exponent
5716    b->bits=DECNEG;                     // ln(0.10)->ln(0.99) always -ve
5717    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; // restore
5718    decAddOp(a, a, b, &aset, 0, &ignore); // acc=a+b
5719    // the initial estimate is now in a, with up to 4 digits correct.
5720    // When rhs is at or near Nmax the estimate will be low, so we
5721    // will approach it from below, avoiding overflow when calling exp.
5722
5723    decNumberZero(&numone); *numone.lsu=1;   // constant 1 for adjustment
5724
5725    // accumulator bounds are as requested (could underflow, but
5726    // cannot overflow)
5727    aset.emax=set->emax;
5728    aset.emin=set->emin;
5729    aset.clamp=0;                       // no concrete format
5730    // set up a context to be used for the multiply and subtract
5731    bset=aset;
5732    bset.emax=DEC_MAX_MATH*2;           // use double bounds for the
5733    bset.emin=-DEC_MAX_MATH*2;          // adjustment calculation
5734                                        // [see decExpOp call below]
5735    // for each iteration double the number of digits to calculate,
5736    // up to a maximum of p
5737    pp=9;                               // initial precision
5738    // [initially 9 as then the sequence starts 7+2, 16+2, and
5739    // 34+2, which is ideal for standard-sized numbers]
5740    aset.digits=pp;                     // working context
5741    bset.digits=pp+rhs->digits;         // wider context
5742    for (;;) {                          // iterate
5743      #if DECCHECK
5744      iterations++;
5745      if (iterations>24) break;         // consider 9 * 2**24
5746      #endif
5747      // calculate the adjustment (exp(-a)*x-1) into b.  This is a
5748      // catastrophic subtraction but it really is the difference
5749      // from 1 that is of interest.
5750      // Use the internal entry point to Exp as it allows the double
5751      // range for calculating exp(-a) when a is the tiniest subnormal.
5752      a->bits^=DECNEG;                  // make -a
5753      decExpOp(b, a, &bset, &ignore);   // b=exp(-a)
5754      a->bits^=DECNEG;                  // restore sign of a
5755      // now multiply by rhs and subtract 1, at the wider precision
5756      decMultiplyOp(b, b, rhs, &bset, &ignore);        // b=b*rhs
5757      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); // b=b-1
5758
5759      // the iteration ends when the adjustment cannot affect the
5760      // result by >=0.5 ulp (at the requested digits), which
5761      // is when its value is smaller than the accumulator by
5762      // set->digits+1 digits (or it is zero) -- this is a looser
5763      // requirement than for Exp because all that happens to the
5764      // accumulator after this is the final rounding (but note that
5765      // there must also be full precision in a, or a=0).
5766
5767      if (decNumberIsZero(b) ||
5768          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5769        if (a->digits==p) break;
5770        if (decNumberIsZero(a)) {
5771          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); // rhs=1 ?
5772          if (cmp.lsu[0]==0) a->exponent=0;            // yes, exact 0
5773           else *status|=(DEC_Inexact | DEC_Rounded);  // no, inexact
5774          break;
5775          }
5776        // force padding if adjustment has gone to 0 before full length
5777        if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5778        }
5779
5780      // not done yet ...
5781      decAddOp(a, a, b, &aset, 0, &ignore);  // a=a+b for next estimate
5782      if (pp==p) continue;                   // precision is at maximum
5783      // lengthen the next calculation
5784      pp=pp*2;                               // double precision
5785      if (pp>p) pp=p;                        // clamp to maximum
5786      aset.digits=pp;                        // working context
5787      bset.digits=pp+rhs->digits;            // wider context
5788      } // Newton's iteration
5789
5790    #if DECCHECK
5791    // just a sanity check; remove the test to show always
5792    if (iterations>24)
5793      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5794            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5795    #endif
5796
5797    // Copy and round the result to res
5798    residue=1;                          // indicate dirt to right
5799    if (ISZERO(a)) residue=0;           // .. unless underflowed to 0
5800    aset.digits=set->digits;            // [use default rounding]
5801    decCopyFit(res, a, &aset, &residue, status); // copy & shorten
5802    decFinish(res, set, &residue, status);       // cleanup/set flags
5803    } while(0);                         // end protected
5804
5805  if (allocbufa!=NULL) free(allocbufa); // drop any storage used
5806  if (allocbufb!=NULL) free(allocbufb); // ..
5807  // [status is handled by caller]
5808  return res;
5809  } // decLnOp
5810
5811/* ------------------------------------------------------------------ */
5812/* decQuantizeOp  -- force exponent to requested value                */
5813/*                                                                    */
5814/*   This computes C = op(A, B), where op adjusts the coefficient     */
5815/*   of C (by rounding or shifting) such that the exponent (-scale)   */
5816/*   of C has the value B or matches the exponent of B.               */
5817/*   The numerical value of C will equal A, except for the effects of */
5818/*   any rounding that occurred.                                      */
5819/*                                                                    */
5820/*   res is C, the result.  C may be A or B                           */
5821/*   lhs is A, the number to adjust                                   */
5822/*   rhs is B, the requested exponent                                 */
5823/*   set is the context                                               */
5824/*   quant is 1 for quantize or 0 for rescale                         */
5825/*   status is the status accumulator (this can be called without     */
5826/*          risk of control loss)                                     */
5827/*                                                                    */
5828/* C must have space for set->digits digits.                          */
5829/*                                                                    */
5830/* Unless there is an error or the result is infinite, the exponent   */
5831/* after the operation is guaranteed to be that requested.            */
5832/* ------------------------------------------------------------------ */
5833static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5834                                 const decNumber *rhs, decContext *set,
5835                                 Flag quant, uInt *status) {
5836  #if DECSUBSET
5837  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
5838  decNumber *allocrhs=NULL;        // .., rhs
5839  #endif
5840  const decNumber *inrhs=rhs;      // save original rhs
5841  Int   reqdigits=set->digits;     // requested DIGITS
5842  Int   reqexp;                    // requested exponent [-scale]
5843  Int   residue=0;                 // rounding residue
5844  Int   etiny=set->emin-(reqdigits-1);
5845
5846  #if DECCHECK
5847  if (decCheckOperands(res, lhs, rhs, set)) return res;
5848  #endif
5849
5850  do {                             // protect allocated storage
5851    #if DECSUBSET
5852    if (!set->extended) {
5853      // reduce operands and set lostDigits status, as needed
5854      if (lhs->digits>reqdigits) {
5855        alloclhs=decRoundOperand(lhs, set, status);
5856        if (alloclhs==NULL) break;
5857        lhs=alloclhs;
5858        }
5859      if (rhs->digits>reqdigits) { // [this only checks lostDigits]
5860        allocrhs=decRoundOperand(rhs, set, status);
5861        if (allocrhs==NULL) break;
5862        rhs=allocrhs;
5863        }
5864      }
5865    #endif
5866    // [following code does not require input rounding]
5867
5868    // Handle special values
5869    if (SPECIALARGS) {
5870      // NaNs get usual processing
5871      if (SPECIALARGS & (DECSNAN | DECNAN))
5872        decNaNs(res, lhs, rhs, set, status);
5873      // one infinity but not both is bad
5874      else if ((lhs->bits ^ rhs->bits) & DECINF)
5875        *status|=DEC_Invalid_operation;
5876      // both infinity: return lhs
5877      else decNumberCopy(res, lhs);          // [nop if in place]
5878      break;
5879      }
5880
5881    // set requested exponent
5882    if (quant) reqexp=inrhs->exponent;  // quantize -- match exponents
5883     else {                             // rescale -- use value of rhs
5884      // Original rhs must be an integer that fits and is in range,
5885      // which could be from -1999999997 to +999999999, thanks to
5886      // subnormals
5887      reqexp=decGetInt(inrhs);               // [cannot fail]
5888      }
5889
5890    #if DECSUBSET
5891    if (!set->extended) etiny=set->emin;     // no subnormals
5892    #endif
5893
5894    if (reqexp==BADINT                       // bad (rescale only) or ..
5895     || reqexp==BIGODD || reqexp==BIGEVEN    // very big (ditto) or ..
5896     || (reqexp<etiny)                       // < lowest
5897     || (reqexp>set->emax)) {                // > emax
5898      *status|=DEC_Invalid_operation;
5899      break;}
5900
5901    // the RHS has been processed, so it can be overwritten now if necessary
5902    if (ISZERO(lhs)) {                       // zero coefficient unchanged
5903      decNumberCopy(res, lhs);               // [nop if in place]
5904      res->exponent=reqexp;                  // .. just set exponent
5905      #if DECSUBSET
5906      if (!set->extended) res->bits=0;       // subset specification; no -0
5907      #endif
5908      }
5909     else {                                  // non-zero lhs
5910      Int adjust=reqexp-lhs->exponent;       // digit adjustment needed
5911      // if adjusted coefficient will definitely not fit, give up now
5912      if ((lhs->digits-adjust)>reqdigits) {
5913        *status|=DEC_Invalid_operation;
5914        break;
5915        }
5916
5917      if (adjust>0) {                        // increasing exponent
5918        // this will decrease the length of the coefficient by adjust
5919        // digits, and must round as it does so
5920        decContext workset;                  // work
5921        workset=*set;                        // clone rounding, etc.
5922        workset.digits=lhs->digits-adjust;   // set requested length
5923        // [note that the latter can be <1, here]
5924        decCopyFit(res, lhs, &workset, &residue, status); // fit to result
5925        decApplyRound(res, &workset, residue, status);    // .. and round
5926        residue=0;                                        // [used]
5927        // If just rounded a 999s case, exponent will be off by one;
5928        // adjust back (after checking space), if so.
5929        if (res->exponent>reqexp) {
5930          // re-check needed, e.g., for quantize(0.9999, 0.001) under
5931          // set->digits==3
5932          if (res->digits==reqdigits) {      // cannot shift by 1
5933            *status&=~(DEC_Inexact | DEC_Rounded); // [clean these]
5934            *status|=DEC_Invalid_operation;
5935            break;
5936            }
5937          res->digits=decShiftToMost(res->lsu, res->digits, 1); // shift
5938          res->exponent--;                   // (re)adjust the exponent.
5939          }
5940        #if DECSUBSET
5941        if (ISZERO(res) && !set->extended) res->bits=0; // subset; no -0
5942        #endif
5943        } // increase
5944       else /* adjust<=0 */ {                // decreasing or = exponent
5945        // this will increase the length of the coefficient by -adjust
5946        // digits, by adding zero or more trailing zeros; this is
5947        // already checked for fit, above
5948        decNumberCopy(res, lhs);             // [it will fit]
5949        // if padding needed (adjust<0), add it now...
5950        if (adjust<0) {
5951          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5952          res->exponent+=adjust;             // adjust the exponent
5953          }
5954        } // decrease
5955      } // non-zero
5956
5957    // Check for overflow [do not use Finalize in this case, as an
5958    // overflow here is a "don't fit" situation]
5959    if (res->exponent>set->emax-res->digits+1) {  // too big
5960      *status|=DEC_Invalid_operation;
5961      break;
5962      }
5963     else {
5964      decFinalize(res, set, &residue, status);    // set subnormal flags
5965      *status&=~DEC_Underflow;          // suppress Underflow [as per 754]
5966      }
5967    } while(0);                         // end protected
5968
5969  #if DECSUBSET
5970  if (allocrhs!=NULL) free(allocrhs);   // drop any storage used
5971  if (alloclhs!=NULL) free(alloclhs);   // ..
5972  #endif
5973  return res;
5974  } // decQuantizeOp
5975
5976/* ------------------------------------------------------------------ */
5977/* decCompareOp -- compare, min, or max two Numbers                   */
5978/*                                                                    */
5979/*   This computes C = A ? B and carries out one of four operations:  */
5980/*     COMPARE    -- returns the signum (as a number) giving the      */
5981/*                   result of a comparison unless one or both        */
5982/*                   operands is a NaN (in which case a NaN results)  */
5983/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5984/*                   Invalid operation.                               */
5985/*     COMPMAX    -- returns the larger of the operands, using the    */
5986/*                   754 maxnum operation                             */
5987/*     COMPMAXMAG -- ditto, comparing absolute values                 */
5988/*     COMPMIN    -- the 754 minnum operation                         */
5989/*     COMPMINMAG -- ditto, comparing absolute values                 */
5990/*     COMTOTAL   -- returns the signum (as a number) giving the      */
5991/*                   result of a comparison using 754 total ordering  */
5992/*                                                                    */
5993/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
5994/*   lhs is A                                                         */
5995/*   rhs is B                                                         */
5996/*   set is the context                                               */
5997/*   op  is the operation flag                                        */
5998/*   status is the usual accumulator                                  */
5999/*                                                                    */
6000/* C must have space for one digit for COMPARE or set->digits for     */
6001/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6002/* ------------------------------------------------------------------ */
6003/* The emphasis here is on speed for common cases, and avoiding       */
6004/* coefficient comparison if possible.                                */
6005/* ------------------------------------------------------------------ */
6006decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6007                         const decNumber *rhs, decContext *set,
6008                         Flag op, uInt *status) {
6009  #if DECSUBSET
6010  decNumber *alloclhs=NULL;        // non-NULL if rounded lhs allocated
6011  decNumber *allocrhs=NULL;        // .., rhs
6012  #endif
6013  Int   result=0;                  // default result value
6014  uByte merged;                    // work
6015
6016  #if DECCHECK
6017  if (decCheckOperands(res, lhs, rhs, set)) return res;
6018  #endif
6019
6020  do {                             // protect allocated storage
6021    #if DECSUBSET
6022    if (!set->extended) {
6023      // reduce operands and set lostDigits status, as needed
6024      if (lhs->digits>set->digits) {
6025        alloclhs=decRoundOperand(lhs, set, status);
6026        if (alloclhs==NULL) {result=BADINT; break;}
6027        lhs=alloclhs;
6028        }
6029      if (rhs->digits>set->digits) {
6030        allocrhs=decRoundOperand(rhs, set, status);
6031        if (allocrhs==NULL) {result=BADINT; break;}
6032        rhs=allocrhs;
6033        }
6034      }
6035    #endif
6036    // [following code does not require input rounding]
6037
6038    // If total ordering then handle differing signs 'up front'
6039    if (op==COMPTOTAL) {                // total ordering
6040      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6041        result=-1;
6042        break;
6043        }
6044      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6045        result=+1;
6046        break;
6047        }
6048      }
6049
6050    // handle NaNs specially; let infinities drop through
6051    // This assumes sNaN (even just one) leads to NaN.
6052    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6053    if (merged) {                       // a NaN bit set
6054      if (op==COMPARE);                 // result will be NaN
6055       else if (op==COMPSIG)            // treat qNaN as sNaN
6056        *status|=DEC_Invalid_operation | DEC_sNaN;
6057       else if (op==COMPTOTAL) {        // total ordering, always finite
6058        // signs are known to be the same; compute the ordering here
6059        // as if the signs are both positive, then invert for negatives
6060        if (!decNumberIsNaN(lhs)) result=-1;
6061         else if (!decNumberIsNaN(rhs)) result=+1;
6062         // here if both NaNs
6063         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6064         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6065         else { // both NaN or both sNaN
6066          // now it just depends on the payload
6067          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6068                                rhs->lsu, D2U(rhs->digits), 0);
6069          // [Error not possible, as these are 'aligned']
6070          } // both same NaNs
6071        if (decNumberIsNegative(lhs)) result=-result;
6072        break;
6073        } // total order
6074
6075       else if (merged & DECSNAN);           // sNaN -> qNaN
6076       else { // here if MIN or MAX and one or two quiet NaNs
6077        // min or max -- 754 rules ignore single NaN
6078        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6079          // just one NaN; force choice to be the non-NaN operand
6080          op=COMPMAX;
6081          if (lhs->bits & DECNAN) result=-1; // pick rhs
6082                             else result=+1; // pick lhs
6083          break;
6084          }
6085        } // max or min
6086      op=COMPNAN;                            // use special path
6087      decNaNs(res, lhs, rhs, set, status);   // propagate NaN
6088      break;
6089      }
6090    // have numbers
6091    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6092     else result=decCompare(lhs, rhs, 0);    // sign matters
6093    } while(0);                              // end protected
6094
6095  if (result==BADINT) *status|=DEC_Insufficient_storage; // rare
6096   else {
6097    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { // returning signum
6098      if (op==COMPTOTAL && result==0) {
6099        // operands are numerically equal or same NaN (and same sign,
6100        // tested first); if identical, leave result 0
6101        if (lhs->exponent!=rhs->exponent) {
6102          if (lhs->exponent<rhs->exponent) result=-1;
6103           else result=+1;
6104          if (decNumberIsNegative(lhs)) result=-result;
6105          } // lexp!=rexp
6106        } // total-order by exponent
6107      decNumberZero(res);               // [always a valid result]
6108      if (result!=0) {                  // must be -1 or +1
6109        *res->lsu=1;
6110        if (result<0) res->bits=DECNEG;
6111        }
6112      }
6113     else if (op==COMPNAN);             // special, drop through
6114     else {                             // MAX or MIN, non-NaN result
6115      Int residue=0;                    // rounding accumulator
6116      // choose the operand for the result
6117      const decNumber *choice;
6118      if (result==0) { // operands are numerically equal
6119        // choose according to sign then exponent (see 754)
6120        uByte slhs=(lhs->bits & DECNEG);
6121        uByte srhs=(rhs->bits & DECNEG);
6122        #if DECSUBSET
6123        if (!set->extended) {           // subset: force left-hand
6124          op=COMPMAX;
6125          result=+1;
6126          }
6127        else
6128        #endif
6129        if (slhs!=srhs) {          // signs differ
6130          if (slhs) result=-1;     // rhs is max
6131               else result=+1;     // lhs is max
6132          }
6133         else if (slhs && srhs) {  // both negative
6134          if (lhs->exponent<rhs->exponent) result=+1;
6135                                      else result=-1;
6136          // [if equal, use lhs, technically identical]
6137          }
6138         else {                    // both positive
6139          if (lhs->exponent>rhs->exponent) result=+1;
6140                                      else result=-1;
6141          // [ditto]
6142          }
6143        } // numerically equal
6144      // here result will be non-0; reverse if looking for MIN
6145      if (op==COMPMIN || op==COMPMINMAG) result=-result;
6146      choice=(result>0 ? lhs : rhs);    // choose
6147      // copy chosen to result, rounding if need be
6148      decCopyFit(res, choice, set, &residue, status);
6149      decFinish(res, set, &residue, status);
6150      }
6151    }
6152  #if DECSUBSET
6153  if (allocrhs!=NULL) free(allocrhs);   // free any storage used
6154  if (alloclhs!=NULL) free(alloclhs);   // ..
6155  #endif
6156  return res;
6157  } // decCompareOp
6158
6159/* ------------------------------------------------------------------ */
6160/* decCompare -- compare two decNumbers by numerical value            */
6161/*                                                                    */
6162/*  This routine compares A ? B without altering them.                */
6163/*                                                                    */
6164/*  Arg1 is A, a decNumber which is not a NaN                         */
6165/*  Arg2 is B, a decNumber which is not a NaN                         */
6166/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6167/*                                                                    */
6168/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6169/*  (the only possible failure is an allocation error)                */
6170/* ------------------------------------------------------------------ */
6171static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6172                      Flag abs) {
6173  Int   result;                    // result value
6174  Int   sigr;                      // rhs signum
6175  Int   compare;                   // work
6176
6177  result=1;                                  // assume signum(lhs)
6178  if (ISZERO(lhs)) result=0;
6179  if (abs) {
6180    if (ISZERO(rhs)) return result;          // LHS wins or both 0
6181    // RHS is non-zero
6182    if (result==0) return -1;                // LHS is 0; RHS wins
6183    // [here, both non-zero, result=1]
6184    }
6185   else {                                    // signs matter
6186    if (result && decNumberIsNegative(lhs)) result=-1;
6187    sigr=1;                                  // compute signum(rhs)
6188    if (ISZERO(rhs)) sigr=0;
6189     else if (decNumberIsNegative(rhs)) sigr=-1;
6190    if (result > sigr) return +1;            // L > R, return 1
6191    if (result < sigr) return -1;            // L < R, return -1
6192    if (result==0) return 0;                   // both 0
6193    }
6194
6195  // signums are the same; both are non-zero
6196  if ((lhs->bits | rhs->bits) & DECINF) {    // one or more infinities
6197    if (decNumberIsInfinite(rhs)) {
6198      if (decNumberIsInfinite(lhs)) result=0;// both infinite
6199       else result=-result;                  // only rhs infinite
6200      }
6201    return result;
6202    }
6203  // must compare the coefficients, allowing for exponents
6204  if (lhs->exponent>rhs->exponent) {         // LHS exponent larger
6205    // swap sides, and sign
6206    const decNumber *temp=lhs;
6207    lhs=rhs;
6208    rhs=temp;
6209    result=-result;
6210    }
6211  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6212                         rhs->lsu, D2U(rhs->digits),
6213                         rhs->exponent-lhs->exponent);
6214  if (compare!=BADINT) compare*=result;      // comparison succeeded
6215  return compare;
6216  } // decCompare
6217
6218/* ------------------------------------------------------------------ */
6219/* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6220/*                                                                    */
6221/*  This routine compares A ? B*10**E where A and B are unit arrays   */
6222/*  A is a plain integer                                              */
6223/*  B has an exponent of E (which must be non-negative)               */
6224/*                                                                    */
6225/*  Arg1 is A first Unit (lsu)                                        */
6226/*  Arg2 is A length in Units                                         */
6227/*  Arg3 is B first Unit (lsu)                                        */
6228/*  Arg4 is B length in Units                                         */
6229/*  Arg5 is E (0 if the units are aligned)                            */
6230/*                                                                    */
6231/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6232/*  (the only possible failure is an allocation error, which can      */
6233/*  only occur if E!=0)                                               */
6234/* ------------------------------------------------------------------ */
6235static Int decUnitCompare(const Unit *a, Int alength,
6236                          const Unit *b, Int blength, Int exp) {
6237  Unit  *acc;                      // accumulator for result
6238  Unit  accbuff[SD2U(DECBUFFER*2+1)]; // local buffer
6239  Unit  *allocacc=NULL;            // -> allocated acc buffer, iff allocated
6240  Int   accunits, need;            // units in use or needed for acc
6241  const Unit *l, *r, *u;           // work
6242  Int   expunits, exprem, result;  // ..
6243
6244  if (exp==0) {                    // aligned; fastpath
6245    if (alength>blength) return 1;
6246    if (alength<blength) return -1;
6247    // same number of units in both -- need unit-by-unit compare
6248    l=a+alength-1;
6249    r=b+alength-1;
6250    for (;l>=a; l--, r--) {
6251      if (*l>*r) return 1;
6252      if (*l<*r) return -1;
6253      }
6254    return 0;                      // all units match
6255    } // aligned
6256
6257  // Unaligned.  If one is >1 unit longer than the other, padded
6258  // approximately, then can return easily
6259  if (alength>blength+(Int)D2U(exp)) return 1;
6260  if (alength+1<blength+(Int)D2U(exp)) return -1;
6261
6262  // Need to do a real subtract.  For this, a result buffer is needed
6263  // even though only the sign is of interest.  Its length needs
6264  // to be the larger of alength and padded blength, +2
6265  need=blength+D2U(exp);                // maximum real length of B
6266  if (need<alength) need=alength;
6267  need+=2;
6268  acc=accbuff;                          // assume use local buffer
6269  if (need*sizeof(Unit)>sizeof(accbuff)) {
6270    allocacc=(Unit *)malloc(need*sizeof(Unit));
6271    if (allocacc==NULL) return BADINT;  // hopeless -- abandon
6272    acc=allocacc;
6273    }
6274  // Calculate units and remainder from exponent.
6275  expunits=exp/DECDPUN;
6276  exprem=exp%DECDPUN;
6277  // subtract [A+B*(-m)]
6278  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6279                         -(Int)powers[exprem]);
6280  // [UnitAddSub result may have leading zeros, even on zero]
6281  if (accunits<0) result=-1;            // negative result
6282   else {                               // non-negative result
6283    // check units of the result before freeing any storage
6284    for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6285    result=(*u==0 ? 0 : +1);
6286    }
6287  // clean up and return the result
6288  if (allocacc!=NULL) free(allocacc);   // drop any storage used
6289  return result;
6290  } // decUnitCompare
6291
6292/* ------------------------------------------------------------------ */
6293/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6294/*                                                                    */
6295/*  This routine performs the calculation:                            */
6296/*                                                                    */
6297/*  C=A+(B*M)                                                         */
6298/*                                                                    */
6299/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6300/*                                                                    */
6301/*  A may be shorter or longer than B.                                */
6302/*                                                                    */
6303/*  Leading zeros are not removed after a calculation.  The result is */
6304/*  either the same length as the longer of A and B (adding any       */
6305/*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6306/*                                                                    */
6307/*  A and B content are not altered unless C is also A or B.          */
6308/*  C may be the same array as A or B, but only if no zero padding is */
6309/*  requested (that is, C may be B only if bshift==0).                */
6310/*  C is filled from the lsu; only those units necessary to complete  */
6311/*  the calculation are referenced.                                   */
6312/*                                                                    */
6313/*  Arg1 is A first Unit (lsu)                                        */
6314/*  Arg2 is A length in Units                                         */
6315/*  Arg3 is B first Unit (lsu)                                        */
6316/*  Arg4 is B length in Units                                         */
6317/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6318/*  Arg6 is C first Unit (lsu)                                        */
6319/*  Arg7 is M, the multiplier                                         */
6320/*                                                                    */
6321/*  returns the count of Units written to C, which will be non-zero   */
6322/*  and negated if the result is negative.  That is, the sign of the  */
6323/*  returned Int is the sign of the result (positive for zero) and    */
6324/*  the absolute value of the Int is the count of Units.              */
6325/*                                                                    */
6326/*  It is the caller's responsibility to make sure that C size is     */
6327/*  safe, allowing space if necessary for a one-Unit carry.           */
6328/*                                                                    */
6329/*  This routine is severely performance-critical; *any* change here  */
6330/*  must be measured (timed) to assure no performance degradation.    */
6331/*  In particular, trickery here tends to be counter-productive, as   */
6332/*  increased complexity of code hurts register optimizations on      */
6333/*  register-poor architectures.  Avoiding divisions is nearly        */
6334/*  always a Good Idea, however.                                      */
6335/*                                                                    */
6336/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6337/* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6338/* ------------------------------------------------------------------ */
6339static Int decUnitAddSub(const Unit *a, Int alength,
6340                         const Unit *b, Int blength, Int bshift,
6341                         Unit *c, Int m) {
6342  const Unit *alsu=a;              // A lsu [need to remember it]
6343  Unit *clsu=c;                    // C ditto
6344  Unit *minC;                      // low water mark for C
6345  Unit *maxC;                      // high water mark for C
6346  eInt carry=0;                    // carry integer (could be Long)
6347  Int  add;                        // work
6348  #if DECDPUN<=4                   // myriadal, millenary, etc.
6349  Int  est;                        // estimated quotient
6350  #endif
6351
6352  #if DECTRACE
6353  if (alength<1 || blength<1)
6354    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6355  #endif
6356
6357  maxC=c+alength;                  // A is usually the longer
6358  minC=c+blength;                  // .. and B the shorter
6359  if (bshift!=0) {                 // B is shifted; low As copy across
6360    minC+=bshift;
6361    // if in place [common], skip copy unless there's a gap [rare]
6362    if (a==c && bshift<=alength) {
6363      c+=bshift;
6364      a+=bshift;
6365      }
6366     else for (; c<clsu+bshift; a++, c++) {  // copy needed
6367      if (a<alsu+alength) *c=*a;
6368       else *c=0;
6369      }
6370    }
6371  if (minC>maxC) { // swap
6372    Unit *hold=minC;
6373    minC=maxC;
6374    maxC=hold;
6375    }
6376
6377  // For speed, do the addition as two loops; the first where both A
6378  // and B contribute, and the second (if necessary) where only one or
6379  // other of the numbers contribute.
6380  // Carry handling is the same (i.e., duplicated) in each case.
6381  for (; c<minC; c++) {
6382    carry+=*a;
6383    a++;
6384    carry+=((eInt)*b)*m;                // [special-casing m=1/-1
6385    b++;                                // here is not a win]
6386    // here carry is new Unit of digits; it could be +ve or -ve
6387    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6388      *c=(Unit)carry;
6389      carry=0;
6390      continue;
6391      }
6392    #if DECDPUN==4                           // use divide-by-multiply
6393      if (carry>=0) {
6394        est=(((ueInt)carry>>11)*53687)>>18;
6395        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6396        carry=est;                           // likely quotient [89%]
6397        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6398        carry++;
6399        *c-=DECDPUNMAX+1;
6400        continue;
6401        }
6402      // negative case
6403      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6404      est=(((ueInt)carry>>11)*53687)>>18;
6405      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6406      carry=est-(DECDPUNMAX+1);              // correctly negative
6407      if (*c<DECDPUNMAX+1) continue;         // was OK
6408      carry++;
6409      *c-=DECDPUNMAX+1;
6410    #elif DECDPUN==3
6411      if (carry>=0) {
6412        est=(((ueInt)carry>>3)*16777)>>21;
6413        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6414        carry=est;                           // likely quotient [99%]
6415        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6416        carry++;
6417        *c-=DECDPUNMAX+1;
6418        continue;
6419        }
6420      // negative case
6421      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6422      est=(((ueInt)carry>>3)*16777)>>21;
6423      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6424      carry=est-(DECDPUNMAX+1);              // correctly negative
6425      if (*c<DECDPUNMAX+1) continue;         // was OK
6426      carry++;
6427      *c-=DECDPUNMAX+1;
6428    #elif DECDPUN<=2
6429      // Can use QUOT10 as carry <= 4 digits
6430      if (carry>=0) {
6431        est=QUOT10(carry, DECDPUN);
6432        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6433        carry=est;                           // quotient
6434        continue;
6435        }
6436      // negative case
6437      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6438      est=QUOT10(carry, DECDPUN);
6439      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6440      carry=est-(DECDPUNMAX+1);              // correctly negative
6441    #else
6442      // remainder operator is undefined if negative, so must test
6443      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   // fastpath carry +1
6444        *c=(Unit)(carry-(DECDPUNMAX+1));     // [helps additions]
6445        carry=1;
6446        continue;
6447        }
6448      if (carry>=0) {
6449        *c=(Unit)(carry%(DECDPUNMAX+1));
6450        carry=carry/(DECDPUNMAX+1);
6451        continue;
6452        }
6453      // negative case
6454      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6455      *c=(Unit)(carry%(DECDPUNMAX+1));
6456      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6457    #endif
6458    } // c
6459
6460  // now may have one or other to complete
6461  // [pretest to avoid loop setup/shutdown]
6462  if (c<maxC) for (; c<maxC; c++) {
6463    if (a<alsu+alength) {               // still in A
6464      carry+=*a;
6465      a++;
6466      }
6467     else {                             // inside B
6468      carry+=((eInt)*b)*m;
6469      b++;
6470      }
6471    // here carry is new Unit of digits; it could be +ve or -ve and
6472    // magnitude up to DECDPUNMAX squared
6473    if ((ueInt)carry<=DECDPUNMAX) {     // fastpath 0-DECDPUNMAX
6474      *c=(Unit)carry;
6475      carry=0;
6476      continue;
6477      }
6478    // result for this unit is negative or >DECDPUNMAX
6479    #if DECDPUN==4                           // use divide-by-multiply
6480      if (carry>=0) {
6481        est=(((ueInt)carry>>11)*53687)>>18;
6482        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6483        carry=est;                           // likely quotient [79.7%]
6484        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6485        carry++;
6486        *c-=DECDPUNMAX+1;
6487        continue;
6488        }
6489      // negative case
6490      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6491      est=(((ueInt)carry>>11)*53687)>>18;
6492      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6493      carry=est-(DECDPUNMAX+1);              // correctly negative
6494      if (*c<DECDPUNMAX+1) continue;         // was OK
6495      carry++;
6496      *c-=DECDPUNMAX+1;
6497    #elif DECDPUN==3
6498      if (carry>=0) {
6499        est=(((ueInt)carry>>3)*16777)>>21;
6500        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6501        carry=est;                           // likely quotient [99%]
6502        if (*c<DECDPUNMAX+1) continue;       // estimate was correct
6503        carry++;
6504        *c-=DECDPUNMAX+1;
6505        continue;
6506        }
6507      // negative case
6508      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6509      est=(((ueInt)carry>>3)*16777)>>21;
6510      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6511      carry=est-(DECDPUNMAX+1);              // correctly negative
6512      if (*c<DECDPUNMAX+1) continue;         // was OK
6513      carry++;
6514      *c-=DECDPUNMAX+1;
6515    #elif DECDPUN<=2
6516      if (carry>=0) {
6517        est=QUOT10(carry, DECDPUN);
6518        *c=(Unit)(carry-est*(DECDPUNMAX+1)); // remainder
6519        carry=est;                           // quotient
6520        continue;
6521        }
6522      // negative case
6523      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6524      est=QUOT10(carry, DECDPUN);
6525      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6526      carry=est-(DECDPUNMAX+1);              // correctly negative
6527    #else
6528      if ((ueInt)carry<(DECDPUNMAX+1)*2){    // fastpath carry 1
6529        *c=(Unit)(carry-(DECDPUNMAX+1));
6530        carry=1;
6531        continue;
6532        }
6533      // remainder operator is undefined if negative, so must test
6534      if (carry>=0) {
6535        *c=(Unit)(carry%(DECDPUNMAX+1));
6536        carry=carry/(DECDPUNMAX+1);
6537        continue;
6538        }
6539      // negative case
6540      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); // make positive
6541      *c=(Unit)(carry%(DECDPUNMAX+1));
6542      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6543    #endif
6544    } // c
6545
6546  // OK, all A and B processed; might still have carry or borrow
6547  // return number of Units in the result, negated if a borrow
6548  if (carry==0) return c-clsu;     // no carry, so no more to do
6549  if (carry>0) {                   // positive carry
6550    *c=(Unit)carry;                // place as new unit
6551    c++;                           // ..
6552    return c-clsu;
6553    }
6554  // -ve carry: it's a borrow; complement needed
6555  add=1;                           // temporary carry...
6556  for (c=clsu; c<maxC; c++) {
6557    add=DECDPUNMAX+add-*c;
6558    if (add<=DECDPUNMAX) {
6559      *c=(Unit)add;
6560      add=0;
6561      }
6562     else {
6563      *c=0;
6564      add=1;
6565      }
6566    }
6567  // add an extra unit iff it would be non-zero
6568  #if DECTRACE
6569    printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6570  #endif
6571  if ((add-carry-1)!=0) {
6572    *c=(Unit)(add-carry-1);
6573    c++;                      // interesting, include it
6574    }
6575  return clsu-c;              // -ve result indicates borrowed
6576  } // decUnitAddSub
6577
6578/* ------------------------------------------------------------------ */
6579/* decTrim -- trim trailing zeros or normalize                        */
6580/*                                                                    */
6581/*   dn is the number to trim or normalize                            */
6582/*   set is the context to use to check for clamp                     */
6583/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6584/*   noclamp is 1 to unconditional (unclamped) trim                   */
6585/*   dropped returns the number of discarded trailing zeros           */
6586/*   returns dn                                                       */
6587/*                                                                    */
6588/* If clamp is set in the context then the number of zeros trimmed    */
6589/* may be limited if the exponent is high.                            */
6590/* All fields are updated as required.  This is a utility operation,  */
6591/* so special values are unchanged and no error is possible.          */
6592/* ------------------------------------------------------------------ */
6593static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6594                           Flag noclamp, Int *dropped) {
6595  Int   d, exp;                    // work
6596  uInt  cut;                       // ..
6597  Unit  *up;                       // -> current Unit
6598
6599  #if DECCHECK
6600  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6601  #endif
6602
6603  *dropped=0;                           // assume no zeros dropped
6604  if ((dn->bits & DECSPECIAL)           // fast exit if special ..
6605    || (*dn->lsu & 0x01)) return dn;    // .. or odd
6606  if (ISZERO(dn)) {                     // .. or 0
6607    dn->exponent=0;                     // (sign is preserved)
6608    return dn;
6609    }
6610
6611  // have a finite number which is even
6612  exp=dn->exponent;
6613  cut=1;                           // digit (1-DECDPUN) in Unit
6614  up=dn->lsu;                      // -> current Unit
6615  for (d=0; d<dn->digits-1; d++) { // [don't strip the final digit]
6616    // slice by powers
6617    #if DECDPUN<=4
6618      uInt quot=QUOT10(*up, cut);
6619      if ((*up-quot*powers[cut])!=0) break;  // found non-0 digit
6620    #else
6621      if (*up%powers[cut]!=0) break;         // found non-0 digit
6622    #endif
6623    // have a trailing 0
6624    if (!all) {                    // trimming
6625      // [if exp>0 then all trailing 0s are significant for trim]
6626      if (exp<=0) {                // if digit might be significant
6627        if (exp==0) break;         // then quit
6628        exp++;                     // next digit might be significant
6629        }
6630      }
6631    cut++;                         // next power
6632    if (cut>DECDPUN) {             // need new Unit
6633      up++;
6634      cut=1;
6635      }
6636    } // d
6637  if (d==0) return dn;             // none to drop
6638
6639  // may need to limit drop if clamping
6640  if (set->clamp && !noclamp) {
6641    Int maxd=set->emax-set->digits+1-dn->exponent;
6642    if (maxd<=0) return dn;        // nothing possible
6643    if (d>maxd) d=maxd;
6644    }
6645
6646  // effect the drop
6647  decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6648  dn->exponent+=d;                 // maintain numerical value
6649  dn->digits-=d;                   // new length
6650  *dropped=d;                      // report the count
6651  return dn;
6652  } // decTrim
6653
6654/* ------------------------------------------------------------------ */
6655/* decReverse -- reverse a Unit array in place                        */
6656/*                                                                    */
6657/*   ulo    is the start of the array                                 */
6658/*   uhi    is the end of the array (highest Unit to include)         */
6659/*                                                                    */
6660/* The units ulo through uhi are reversed in place (if the number     */
6661/* of units is odd, the middle one is untouched).  Note that the      */
6662/* digit(s) in each unit are unaffected.                              */
6663/* ------------------------------------------------------------------ */
6664static void decReverse(Unit *ulo, Unit *uhi) {
6665  Unit temp;
6666  for (; ulo<uhi; ulo++, uhi--) {
6667    temp=*ulo;
6668    *ulo=*uhi;
6669    *uhi=temp;
6670    }
6671  return;
6672  } // decReverse
6673
6674/* ------------------------------------------------------------------ */
6675/* decShiftToMost -- shift digits in array towards most significant   */
6676/*                                                                    */
6677/*   uar    is the array                                              */
6678/*   digits is the count of digits in use in the array                */
6679/*   shift  is the number of zeros to pad with (least significant);   */
6680/*     it must be zero or positive                                    */
6681/*                                                                    */
6682/*   returns the new length of the integer in the array, in digits    */
6683/*                                                                    */
6684/* No overflow is permitted (that is, the uar array must be known to  */
6685/* be large enough to hold the result, after shifting).               */
6686/* ------------------------------------------------------------------ */
6687static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6688  Unit  *target, *source, *first;  // work
6689  Int   cut;                       // odd 0's to add
6690  uInt  next;                      // work
6691
6692  if (shift==0) return digits;     // [fastpath] nothing to do
6693  if ((digits+shift)<=DECDPUN) {   // [fastpath] single-unit case
6694    *uar=(Unit)(*uar*powers[shift]);
6695    return digits+shift;
6696    }
6697
6698  next=0;                          // all paths
6699  source=uar+D2U(digits)-1;        // where msu comes from
6700  target=source+D2U(shift);        // where upper part of first cut goes
6701  cut=DECDPUN-MSUDIGITS(shift);    // where to slice
6702  if (cut==0) {                    // unit-boundary case
6703    for (; source>=uar; source--, target--) *target=*source;
6704    }
6705   else {
6706    first=uar+D2U(digits+shift)-1; // where msu of source will end up
6707    for (; source>=uar; source--, target--) {
6708      // split the source Unit and accumulate remainder for next
6709      #if DECDPUN<=4
6710        uInt quot=QUOT10(*source, cut);
6711        uInt rem=*source-quot*powers[cut];
6712        next+=quot;
6713      #else
6714        uInt rem=*source%powers[cut];
6715        next+=*source/powers[cut];
6716      #endif
6717      if (target<=first) *target=(Unit)next;   // write to target iff valid
6718      next=rem*powers[DECDPUN-cut];            // save remainder for next Unit
6719      }
6720    } // shift-move
6721
6722  // propagate any partial unit to one below and clear the rest
6723  for (; target>=uar; target--) {
6724    *target=(Unit)next;
6725    next=0;
6726    }
6727  return digits+shift;
6728  } // decShiftToMost
6729
6730/* ------------------------------------------------------------------ */
6731/* decShiftToLeast -- shift digits in array towards least significant */
6732/*                                                                    */
6733/*   uar   is the array                                               */
6734/*   units is length of the array, in units                           */
6735/*   shift is the number of digits to remove from the lsu end; it     */
6736/*     must be zero or positive and <= than units*DECDPUN.            */
6737/*                                                                    */
6738/*   returns the new length of the integer in the array, in units     */
6739/*                                                                    */
6740/* Removed digits are discarded (lost).  Units not required to hold   */
6741/* the final result are unchanged.                                    */
6742/* ------------------------------------------------------------------ */
6743static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6744  Unit  *target, *up;              // work
6745  Int   cut, count;                // work
6746  Int   quot, rem;                 // for division
6747
6748  if (shift==0) return units;      // [fastpath] nothing to do
6749  if (shift==units*DECDPUN) {      // [fastpath] little to do
6750    *uar=0;                        // all digits cleared gives zero
6751    return 1;                      // leaves just the one
6752    }
6753
6754  target=uar;                      // both paths
6755  cut=MSUDIGITS(shift);
6756  if (cut==DECDPUN) {              // unit-boundary case; easy
6757    up=uar+D2U(shift);
6758    for (; up<uar+units; target++, up++) *target=*up;
6759    return target-uar;
6760    }
6761
6762  // messier
6763  up=uar+D2U(shift-cut);           // source; correct to whole Units
6764  count=units*DECDPUN-shift;       // the maximum new length
6765  #if DECDPUN<=4
6766    quot=QUOT10(*up, cut);
6767  #else
6768    quot=*up/powers[cut];
6769  #endif
6770  for (; ; target++) {
6771    *target=(Unit)quot;
6772    count-=(DECDPUN-cut);
6773    if (count<=0) break;
6774    up++;
6775    quot=*up;
6776    #if DECDPUN<=4
6777      quot=QUOT10(quot, cut);
6778      rem=*up-quot*powers[cut];
6779    #else
6780      rem=quot%powers[cut];
6781      quot=quot/powers[cut];
6782    #endif
6783    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6784    count-=cut;
6785    if (count<=0) break;
6786    }
6787  return target-uar+1;
6788  } // decShiftToLeast
6789
6790#if DECSUBSET
6791/* ------------------------------------------------------------------ */
6792/* decRoundOperand -- round an operand  [used for subset only]        */
6793/*                                                                    */
6794/*   dn is the number to round (dn->digits is > set->digits)          */
6795/*   set is the relevant context                                      */
6796/*   status is the status accumulator                                 */
6797/*                                                                    */
6798/*   returns an allocated decNumber with the rounded result.          */
6799/*                                                                    */
6800/* lostDigits and other status may be set by this.                    */
6801/*                                                                    */
6802/* Since the input is an operand, it must not be modified.            */
6803/* Instead, return an allocated decNumber, rounded as required.       */
6804/* It is the caller's responsibility to free the allocated storage.   */
6805/*                                                                    */
6806/* If no storage is available then the result cannot be used, so NULL */
6807/* is returned.                                                       */
6808/* ------------------------------------------------------------------ */
6809static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6810                                  uInt *status) {
6811  decNumber *res;                       // result structure
6812  uInt newstatus=0;                     // status from round
6813  Int  residue=0;                       // rounding accumulator
6814
6815  // Allocate storage for the returned decNumber, big enough for the
6816  // length specified by the context
6817  res=(decNumber *)malloc(sizeof(decNumber)
6818                          +(D2U(set->digits)-1)*sizeof(Unit));
6819  if (res==NULL) {
6820    *status|=DEC_Insufficient_storage;
6821    return NULL;
6822    }
6823  decCopyFit(res, dn, set, &residue, &newstatus);
6824  decApplyRound(res, set, residue, &newstatus);
6825
6826  // If that set Inexact then "lost digits" is raised...
6827  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6828  *status|=newstatus;
6829  return res;
6830  } // decRoundOperand
6831#endif
6832
6833/* ------------------------------------------------------------------ */
6834/* decCopyFit -- copy a number, truncating the coefficient if needed  */
6835/*                                                                    */
6836/*   dest is the target decNumber                                     */
6837/*   src  is the source decNumber                                     */
6838/*   set is the context [used for length (digits) and rounding mode]  */
6839/*   residue is the residue accumulator                               */
6840/*   status contains the current status to be updated                 */
6841/*                                                                    */
6842/* (dest==src is allowed and will be a no-op if fits)                 */
6843/* All fields are updated as required.                                */
6844/* ------------------------------------------------------------------ */
6845static void decCopyFit(decNumber *dest, const decNumber *src,
6846                       decContext *set, Int *residue, uInt *status) {
6847  dest->bits=src->bits;
6848  dest->exponent=src->exponent;
6849  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6850  } // decCopyFit
6851
6852/* ------------------------------------------------------------------ */
6853/* decSetCoeff -- set the coefficient of a number                     */
6854/*                                                                    */
6855/*   dn    is the number whose coefficient array is to be set.        */
6856/*         It must have space for set->digits digits                  */
6857/*   set   is the context [for size]                                  */
6858/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6859/*   len   is digits in the source coefficient [may be dn->digits]    */
6860/*   residue is the residue accumulator.  This has values as in       */
6861/*         decApplyRound, and will be unchanged unless the            */
6862/*         target size is less than len.  In this case, the           */
6863/*         coefficient is truncated and the residue is updated to     */
6864/*         reflect the previous residue and the dropped digits.       */
6865/*   status is the status accumulator, as usual                       */
6866/*                                                                    */
6867/* The coefficient may already be in the number, or it can be an      */
6868/* external intermediate array.  If it is in the number, lsu must ==  */
6869/* dn->lsu and len must == dn->digits.                                */
6870/*                                                                    */
6871/* Note that the coefficient length (len) may be < set->digits, and   */
6872/* in this case this merely copies the coefficient (or is a no-op     */
6873/* if dn->lsu==lsu).                                                  */
6874/*                                                                    */
6875/* Note also that (only internally, from decQuantizeOp and            */
6876/* decSetSubnormal) the value of set->digits may be less than one,    */
6877/* indicating a round to left.  This routine handles that case        */
6878/* correctly; caller ensures space.                                   */
6879/*                                                                    */
6880/* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6881/* updated as necessary.   dn->bits (sign) is unchanged.              */
6882/*                                                                    */
6883/* DEC_Rounded status is set if any digits are discarded.             */
6884/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6885/*                       incoming residue was non-0 (implies rounded) */
6886/* ------------------------------------------------------------------ */
6887// mapping array: maps 0-9 to canonical residues, so that a residue
6888// can be adjusted in the range [-1, +1] and achieve correct rounding
6889//                             0  1  2  3  4  5  6  7  8  9
6890static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6891static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6892                        Int len, Int *residue, uInt *status) {
6893  Int   discard;              // number of digits to discard
6894  uInt  cut;                  // cut point in Unit
6895  const Unit *up;             // work
6896  Unit  *target;              // ..
6897  Int   count;                // ..
6898  #if DECDPUN<=4
6899  uInt  temp;                 // ..
6900  #endif
6901
6902  discard=len-set->digits;    // digits to discard
6903  if (discard<=0) {           // no digits are being discarded
6904    if (dn->lsu!=lsu) {       // copy needed
6905      // copy the coefficient array to the result number; no shift needed
6906      count=len;              // avoids D2U
6907      up=lsu;
6908      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6909        *target=*up;
6910      dn->digits=len;         // set the new length
6911      }
6912    // dn->exponent and residue are unchanged, record any inexactitude
6913    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6914    return;
6915    }
6916
6917  // some digits must be discarded ...
6918  dn->exponent+=discard;      // maintain numerical value
6919  *status|=DEC_Rounded;       // accumulate Rounded status
6920  if (*residue>1) *residue=1; // previous residue now to right, so reduce
6921
6922  if (discard>len) {          // everything, +1, is being discarded
6923    // guard digit is 0
6924    // residue is all the number [NB could be all 0s]
6925    if (*residue<=0) {        // not already positive
6926      count=len;              // avoids D2U
6927      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { // found non-0
6928        *residue=1;
6929        break;                // no need to check any others
6930        }
6931      }
6932    if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
6933    *dn->lsu=0;               // coefficient will now be 0
6934    dn->digits=1;             // ..
6935    return;
6936    } // total discard
6937
6938  // partial discard [most common case]
6939  // here, at least the first (most significant) discarded digit exists
6940
6941  // spin up the number, noting residue during the spin, until get to
6942  // the Unit with the first discarded digit.  When reach it, extract
6943  // it and remember its position
6944  count=0;
6945  for (up=lsu;; up++) {
6946    count+=DECDPUN;
6947    if (count>=discard) break; // full ones all checked
6948    if (*up!=0) *residue=1;
6949    } // up
6950
6951  // here up -> Unit with first discarded digit
6952  cut=discard-(count-DECDPUN)-1;
6953  if (cut==DECDPUN-1) {       // unit-boundary case (fast)
6954    Unit half=(Unit)powers[DECDPUN]>>1;
6955    // set residue directly
6956    if (*up>=half) {
6957      if (*up>half) *residue=7;
6958      else *residue+=5;       // add sticky bit
6959      }
6960     else { // <half
6961      if (*up!=0) *residue=3; // [else is 0, leave as sticky bit]
6962      }
6963    if (set->digits<=0) {     // special for Quantize/Subnormal :-(
6964      *dn->lsu=0;             // .. result is 0
6965      dn->digits=1;           // ..
6966      }
6967     else {                   // shift to least
6968      count=set->digits;      // now digits to end up with
6969      dn->digits=count;       // set the new length
6970      up++;                   // move to next
6971      // on unit boundary, so shift-down copy loop is simple
6972      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6973        *target=*up;
6974      }
6975    } // unit-boundary case
6976
6977   else { // discard digit is in low digit(s), and not top digit
6978    uInt  discard1;                // first discarded digit
6979    uInt  quot, rem;               // for divisions
6980    if (cut==0) quot=*up;          // is at bottom of unit
6981     else /* cut>0 */ {            // it's not at bottom of unit
6982      #if DECDPUN<=4
6983        quot=QUOT10(*up, cut);
6984        rem=*up-quot*powers[cut];
6985      #else
6986        rem=*up%powers[cut];
6987        quot=*up/powers[cut];
6988      #endif
6989      if (rem!=0) *residue=1;
6990      }
6991    // discard digit is now at bottom of quot
6992    #if DECDPUN<=4
6993      temp=(quot*6554)>>16;        // fast /10
6994      // Vowels algorithm here not a win (9 instructions)
6995      discard1=quot-X10(temp);
6996      quot=temp;
6997    #else
6998      discard1=quot%10;
6999      quot=quot/10;
7000    #endif
7001    // here, discard1 is the guard digit, and residue is everything
7002    // else [use mapping array to accumulate residue safely]
7003    *residue+=resmap[discard1];
7004    cut++;                         // update cut
7005    // here: up -> Unit of the array with bottom digit
7006    //       cut is the division point for each Unit
7007    //       quot holds the uncut high-order digits for the current unit
7008    if (set->digits<=0) {          // special for Quantize/Subnormal :-(
7009      *dn->lsu=0;                  // .. result is 0
7010      dn->digits=1;                // ..
7011      }
7012     else {                        // shift to least needed
7013      count=set->digits;           // now digits to end up with
7014      dn->digits=count;            // set the new length
7015      // shift-copy the coefficient array to the result number
7016      for (target=dn->lsu; ; target++) {
7017        *target=(Unit)quot;
7018        count-=(DECDPUN-cut);
7019        if (count<=0) break;
7020        up++;
7021        quot=*up;
7022        #if DECDPUN<=4
7023          quot=QUOT10(quot, cut);
7024          rem=*up-quot*powers[cut];
7025        #else
7026          rem=quot%powers[cut];
7027          quot=quot/powers[cut];
7028        #endif
7029        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7030        count-=cut;
7031        if (count<=0) break;
7032        } // shift-copy loop
7033      } // shift to least
7034    } // not unit boundary
7035
7036  if (*residue!=0) *status|=DEC_Inexact; // record inexactitude
7037  return;
7038  } // decSetCoeff
7039
7040/* ------------------------------------------------------------------ */
7041/* decApplyRound -- apply pending rounding to a number                */
7042/*                                                                    */
7043/*   dn    is the number, with space for set->digits digits           */
7044/*   set   is the context [for size and rounding mode]                */
7045/*   residue indicates pending rounding, being any accumulated        */
7046/*         guard and sticky information.  It may be:                  */
7047/*         6-9: rounding digit is >5                                  */
7048/*         5:   rounding digit is exactly half-way                    */
7049/*         1-4: rounding digit is <5 and >0                           */
7050/*         0:   the coefficient is exact                              */
7051/*        -1:   as 1, but the hidden digits are subtractive, that     */
7052/*              is, of the opposite sign to dn.  In this case the     */
7053/*              coefficient must be non-0.  This case occurs when     */
7054/*              subtracting a small number (which can be reduced to   */
7055/*              a sticky bit); see decAddOp.                          */
7056/*   status is the status accumulator, as usual                       */
7057/*                                                                    */
7058/* This routine applies rounding while keeping the length of the      */
7059/* coefficient constant.  The exponent and status are unchanged       */
7060/* except if:                                                         */
7061/*                                                                    */
7062/*   -- the coefficient was increased and is all nines (in which      */
7063/*      case Overflow could occur, and is handled directly here so    */
7064/*      the caller does not need to re-test for overflow)             */
7065/*                                                                    */
7066/*   -- the coefficient was decreased and becomes all nines (in which */
7067/*      case Underflow could occur, and is also handled directly).    */
7068/*                                                                    */
7069/* All fields in dn are updated as required.                          */
7070/*                                                                    */
7071/* ------------------------------------------------------------------ */
7072static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7073                          uInt *status) {
7074  Int  bump;                  // 1 if coefficient needs to be incremented
7075                              // -1 if coefficient needs to be decremented
7076
7077  if (residue==0) return;     // nothing to apply
7078
7079  bump=0;                     // assume a smooth ride
7080
7081  // now decide whether, and how, to round, depending on mode
7082  switch (set->round) {
7083    case DEC_ROUND_05UP: {    // round zero or five up (for reround)
7084      // This is the same as DEC_ROUND_DOWN unless there is a
7085      // positive residue and the lsd of dn is 0 or 5, in which case
7086      // it is bumped; when residue is <0, the number is therefore
7087      // bumped down unless the final digit was 1 or 6 (in which
7088      // case it is bumped down and then up -- a no-op)
7089      Int lsd5=*dn->lsu%5;     // get lsd and quintate
7090      if (residue<0 && lsd5!=1) bump=-1;
7091       else if (residue>0 && lsd5==0) bump=1;
7092      // [bump==1 could be applied directly; use common path for clarity]
7093      break;} // r-05
7094
7095    case DEC_ROUND_DOWN: {
7096      // no change, except if negative residue
7097      if (residue<0) bump=-1;
7098      break;} // r-d
7099
7100    case DEC_ROUND_HALF_DOWN: {
7101      if (residue>5) bump=1;
7102      break;} // r-h-d
7103
7104    case DEC_ROUND_HALF_EVEN: {
7105      if (residue>5) bump=1;            // >0.5 goes up
7106       else if (residue==5) {           // exactly 0.5000...
7107        // 0.5 goes up iff [new] lsd is odd
7108        if (*dn->lsu & 0x01) bump=1;
7109        }
7110      break;} // r-h-e
7111
7112    case DEC_ROUND_HALF_UP: {
7113      if (residue>=5) bump=1;
7114      break;} // r-h-u
7115
7116    case DEC_ROUND_UP: {
7117      if (residue>0) bump=1;
7118      break;} // r-u
7119
7120    case DEC_ROUND_CEILING: {
7121      // same as _UP for positive numbers, and as _DOWN for negatives
7122      // [negative residue cannot occur on 0]
7123      if (decNumberIsNegative(dn)) {
7124        if (residue<0) bump=-1;
7125        }
7126       else {
7127        if (residue>0) bump=1;
7128        }
7129      break;} // r-c
7130
7131    case DEC_ROUND_FLOOR: {
7132      // same as _UP for negative numbers, and as _DOWN for positive
7133      // [negative residue cannot occur on 0]
7134      if (!decNumberIsNegative(dn)) {
7135        if (residue<0) bump=-1;
7136        }
7137       else {
7138        if (residue>0) bump=1;
7139        }
7140      break;} // r-f
7141
7142    default: {      // e.g., DEC_ROUND_MAX
7143      *status|=DEC_Invalid_context;
7144      #if DECTRACE || (DECCHECK && DECVERB)
7145      printf("Unknown rounding mode: %d\n", set->round);
7146      #endif
7147      break;}
7148    } // switch
7149
7150  // now bump the number, up or down, if need be
7151  if (bump==0) return;                       // no action required
7152
7153  // Simply use decUnitAddSub unless bumping up and the number is
7154  // all nines.  In this special case set to 100... explicitly
7155  // and adjust the exponent by one (as otherwise could overflow
7156  // the array)
7157  // Similarly handle all-nines result if bumping down.
7158  if (bump>0) {
7159    Unit *up;                                // work
7160    uInt count=dn->digits;                   // digits to be checked
7161    for (up=dn->lsu; ; up++) {
7162      if (count<=DECDPUN) {
7163        // this is the last Unit (the msu)
7164        if (*up!=powers[count]-1) break;     // not still 9s
7165        // here if it, too, is all nines
7166        *up=(Unit)powers[count-1];           // here 999 -> 100 etc.
7167        for (up=up-1; up>=dn->lsu; up--) *up=0; // others all to 0
7168        dn->exponent++;                      // and bump exponent
7169        // [which, very rarely, could cause Overflow...]
7170        if ((dn->exponent+dn->digits)>set->emax+1) {
7171          decSetOverflow(dn, set, status);
7172          }
7173        return;                              // done
7174        }
7175      // a full unit to check, with more to come
7176      if (*up!=DECDPUNMAX) break;            // not still 9s
7177      count-=DECDPUN;
7178      } // up
7179    } // bump>0
7180   else {                                    // -1
7181    // here checking for a pre-bump of 1000... (leading 1, all
7182    // other digits zero)
7183    Unit *up, *sup;                          // work
7184    uInt count=dn->digits;                   // digits to be checked
7185    for (up=dn->lsu; ; up++) {
7186      if (count<=DECDPUN) {
7187        // this is the last Unit (the msu)
7188        if (*up!=powers[count-1]) break;     // not 100..
7189        // here if have the 1000... case
7190        sup=up;                              // save msu pointer
7191        *up=(Unit)powers[count]-1;           // here 100 in msu -> 999
7192        // others all to all-nines, too
7193        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7194        dn->exponent--;                      // and bump exponent
7195
7196        // iff the number was at the subnormal boundary (exponent=etiny)
7197        // then the exponent is now out of range, so it will in fact get
7198        // clamped to etiny and the final 9 dropped.
7199        // printf(">> emin=%d exp=%d sdig=%d\n", set->emin,
7200        //        dn->exponent, set->digits);
7201        if (dn->exponent+1==set->emin-set->digits+1) {
7202          if (count==1 && dn->digits==1) *sup=0;  // here 9 -> 0[.9]
7203           else {
7204            *sup=(Unit)powers[count-1]-1;    // here 999.. in msu -> 99..
7205            dn->digits--;
7206            }
7207          dn->exponent++;
7208          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7209          }
7210        return;                              // done
7211        }
7212
7213      // a full unit to check, with more to come
7214      if (*up!=0) break;                     // not still 0s
7215      count-=DECDPUN;
7216      } // up
7217
7218    } // bump<0
7219
7220  // Actual bump needed.  Do it.
7221  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7222  } // decApplyRound
7223
7224#if DECSUBSET
7225/* ------------------------------------------------------------------ */
7226/* decFinish -- finish processing a number                            */
7227/*                                                                    */
7228/*   dn is the number                                                 */
7229/*   set is the context                                               */
7230/*   residue is the rounding accumulator (as in decApplyRound)        */
7231/*   status is the accumulator                                        */
7232/*                                                                    */
7233/* This finishes off the current number by:                           */
7234/*    1. If not extended:                                             */
7235/*       a. Converting a zero result to clean '0'                     */
7236/*       b. Reducing positive exponents to 0, if would fit in digits  */
7237/*    2. Checking for overflow and subnormals (always)                */
7238/* Note this is just Finalize when no subset arithmetic.              */
7239/* All fields are updated as required.                                */
7240/* ------------------------------------------------------------------ */
7241static void decFinish(decNumber *dn, decContext *set, Int *residue,
7242                      uInt *status) {
7243  if (!set->extended) {
7244    if ISZERO(dn) {                // value is zero
7245      dn->exponent=0;              // clean exponent ..
7246      dn->bits=0;                  // .. and sign
7247      return;                      // no error possible
7248      }
7249    if (dn->exponent>=0) {         // non-negative exponent
7250      // >0; reduce to integer if possible
7251      if (set->digits >= (dn->exponent+dn->digits)) {
7252        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7253        dn->exponent=0;
7254        }
7255      }
7256    } // !extended
7257
7258  decFinalize(dn, set, residue, status);
7259  } // decFinish
7260#endif
7261
7262/* ------------------------------------------------------------------ */
7263/* decFinalize -- final check, clamp, and round of a number           */
7264/*                                                                    */
7265/*   dn is the number                                                 */
7266/*   set is the context                                               */
7267/*   residue is the rounding accumulator (as in decApplyRound)        */
7268/*   status is the status accumulator                                 */
7269/*                                                                    */
7270/* This finishes off the current number by checking for subnormal     */
7271/* results, applying any pending rounding, checking for overflow,     */
7272/* and applying any clamping.                                         */
7273/* Underflow and overflow conditions are raised as appropriate.       */
7274/* All fields are updated as required.                                */
7275/* ------------------------------------------------------------------ */
7276static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7277                        uInt *status) {
7278  Int shift;                            // shift needed if clamping
7279  Int tinyexp=set->emin-dn->digits+1;   // precalculate subnormal boundary
7280
7281  // Must be careful, here, when checking the exponent as the
7282  // adjusted exponent could overflow 31 bits [because it may already
7283  // be up to twice the expected].
7284
7285  // First test for subnormal.  This must be done before any final
7286  // round as the result could be rounded to Nmin or 0.
7287  if (dn->exponent<=tinyexp) {          // prefilter
7288    Int comp;
7289    decNumber nmin;
7290    // A very nasty case here is dn == Nmin and residue<0
7291    if (dn->exponent<tinyexp) {
7292      // Go handle subnormals; this will apply round if needed.
7293      decSetSubnormal(dn, set, residue, status);
7294      return;
7295      }
7296    // Equals case: only subnormal if dn=Nmin and negative residue
7297    decNumberZero(&nmin);
7298    nmin.lsu[0]=1;
7299    nmin.exponent=set->emin;
7300    comp=decCompare(dn, &nmin, 1);                // (signless compare)
7301    if (comp==BADINT) {                           // oops
7302      *status|=DEC_Insufficient_storage;          // abandon...
7303      return;
7304      }
7305    if (*residue<0 && comp==0) {                  // neg residue and dn==Nmin
7306      decApplyRound(dn, set, *residue, status);   // might force down
7307      decSetSubnormal(dn, set, residue, status);
7308      return;
7309      }
7310    }
7311
7312  // now apply any pending round (this could raise overflow).
7313  if (*residue!=0) decApplyRound(dn, set, *residue, status);
7314
7315  // Check for overflow [redundant in the 'rare' case] or clamp
7316  if (dn->exponent<=set->emax-set->digits+1) return;   // neither needed
7317
7318
7319  // here when might have an overflow or clamp to do
7320  if (dn->exponent>set->emax-dn->digits+1) {           // too big
7321    decSetOverflow(dn, set, status);
7322    return;
7323    }
7324  // here when the result is normal but in clamp range
7325  if (!set->clamp) return;
7326
7327  // here when need to apply the IEEE exponent clamp (fold-down)
7328  shift=dn->exponent-(set->emax-set->digits+1);
7329
7330  // shift coefficient (if non-zero)
7331  if (!ISZERO(dn)) {
7332    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7333    }
7334  dn->exponent-=shift;   // adjust the exponent to match
7335  *status|=DEC_Clamped;  // and record the dirty deed
7336  return;
7337  } // decFinalize
7338
7339/* ------------------------------------------------------------------ */
7340/* decSetOverflow -- set number to proper overflow value              */
7341/*                                                                    */
7342/*   dn is the number (used for sign [only] and result)               */
7343/*   set is the context [used for the rounding mode, etc.]            */
7344/*   status contains the current status to be updated                 */
7345/*                                                                    */
7346/* This sets the sign of a number and sets its value to either        */
7347/* Infinity or the maximum finite value, depending on the sign of     */
7348/* dn and the rounding mode, following IEEE 754 rules.                */
7349/* ------------------------------------------------------------------ */
7350static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7351  Flag needmax=0;                  // result is maximum finite value
7352  uByte sign=dn->bits&DECNEG;      // clean and save sign bit
7353
7354  if (ISZERO(dn)) {                // zero does not overflow magnitude
7355    Int emax=set->emax;                      // limit value
7356    if (set->clamp) emax-=set->digits-1;     // lower if clamping
7357    if (dn->exponent>emax) {                 // clamp required
7358      dn->exponent=emax;
7359      *status|=DEC_Clamped;
7360      }
7361    return;
7362    }
7363
7364  decNumberZero(dn);
7365  switch (set->round) {
7366    case DEC_ROUND_DOWN: {
7367      needmax=1;                   // never Infinity
7368      break;} // r-d
7369    case DEC_ROUND_05UP: {
7370      needmax=1;                   // never Infinity
7371      break;} // r-05
7372    case DEC_ROUND_CEILING: {
7373      if (sign) needmax=1;         // Infinity if non-negative
7374      break;} // r-c
7375    case DEC_ROUND_FLOOR: {
7376      if (!sign) needmax=1;        // Infinity if negative
7377      break;} // r-f
7378    default: break;                // Infinity in all other cases
7379    }
7380  if (needmax) {
7381    decSetMaxValue(dn, set);
7382    dn->bits=sign;                 // set sign
7383    }
7384   else dn->bits=sign|DECINF;      // Value is +/-Infinity
7385  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7386  } // decSetOverflow
7387
7388/* ------------------------------------------------------------------ */
7389/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7390/*                                                                    */
7391/*   dn is the number to set                                          */
7392/*   set is the context [used for digits and emax]                    */
7393/*                                                                    */
7394/* This sets the number to the maximum positive value.                */
7395/* ------------------------------------------------------------------ */
7396static void decSetMaxValue(decNumber *dn, decContext *set) {
7397  Unit *up;                        // work
7398  Int count=set->digits;           // nines to add
7399  dn->digits=count;
7400  // fill in all nines to set maximum value
7401  for (up=dn->lsu; ; up++) {
7402    if (count>DECDPUN) *up=DECDPUNMAX;  // unit full o'nines
7403     else {                             // this is the msu
7404      *up=(Unit)(powers[count]-1);
7405      break;
7406      }
7407    count-=DECDPUN;                // filled those digits
7408    } // up
7409  dn->bits=0;                      // + sign
7410  dn->exponent=set->emax-set->digits+1;
7411  } // decSetMaxValue
7412
7413/* ------------------------------------------------------------------ */
7414/* decSetSubnormal -- process value whose exponent is <Emin           */
7415/*                                                                    */
7416/*   dn is the number (used as input as well as output; it may have   */
7417/*         an allowed subnormal value, which may need to be rounded)  */
7418/*   set is the context [used for the rounding mode]                  */
7419/*   residue is any pending residue                                   */
7420/*   status contains the current status to be updated                 */
7421/*                                                                    */
7422/* If subset mode, set result to zero and set Underflow flags.        */
7423/*                                                                    */
7424/* Value may be zero with a low exponent; this does not set Subnormal */
7425/* but the exponent will be clamped to Etiny.                         */
7426/*                                                                    */
7427/* Otherwise ensure exponent is not out of range, and round as        */
7428/* necessary.  Underflow is set if the result is Inexact.             */
7429/* ------------------------------------------------------------------ */
7430static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7431                            uInt *status) {
7432  decContext workset;         // work
7433  Int        etiny, adjust;   // ..
7434
7435  #if DECSUBSET
7436  // simple set to zero and 'hard underflow' for subset
7437  if (!set->extended) {
7438    decNumberZero(dn);
7439    // always full overflow
7440    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7441    return;
7442    }
7443  #endif
7444
7445  // Full arithmetic -- allow subnormals, rounded to minimum exponent
7446  // (Etiny) if needed
7447  etiny=set->emin-(set->digits-1);      // smallest allowed exponent
7448
7449  if ISZERO(dn) {                       // value is zero
7450    // residue can never be non-zero here
7451    #if DECCHECK
7452      if (*residue!=0) {
7453        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7454        *status|=DEC_Invalid_operation;
7455        }
7456    #endif
7457    if (dn->exponent<etiny) {           // clamp required
7458      dn->exponent=etiny;
7459      *status|=DEC_Clamped;
7460      }
7461    return;
7462    }
7463
7464  *status|=DEC_Subnormal;               // have a non-zero subnormal
7465  adjust=etiny-dn->exponent;            // calculate digits to remove
7466  if (adjust<=0) {                      // not out of range; unrounded
7467    // residue can never be non-zero here, except in the Nmin-residue
7468    // case (which is a subnormal result), so can take fast-path here
7469    // it may already be inexact (from setting the coefficient)
7470    if (*status&DEC_Inexact) *status|=DEC_Underflow;
7471    return;
7472    }
7473
7474  // adjust>0, so need to rescale the result so exponent becomes Etiny
7475  // [this code is similar to that in rescale]
7476  workset=*set;                         // clone rounding, etc.
7477  workset.digits=dn->digits-adjust;     // set requested length
7478  workset.emin-=adjust;                 // and adjust emin to match
7479  // [note that the latter can be <1, here, similar to Rescale case]
7480  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7481  decApplyRound(dn, &workset, *residue, status);
7482
7483  // Use 754 default rule: Underflow is set iff Inexact
7484  // [independent of whether trapped]
7485  if (*status&DEC_Inexact) *status|=DEC_Underflow;
7486
7487  // if rounded up a 999s case, exponent will be off by one; adjust
7488  // back if so [it will fit, because it was shortened earlier]
7489  if (dn->exponent>etiny) {
7490    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7491    dn->exponent--;                     // (re)adjust the exponent.
7492    }
7493
7494  // if rounded to zero, it is by definition clamped...
7495  if (ISZERO(dn)) *status|=DEC_Clamped;
7496  } // decSetSubnormal
7497
7498/* ------------------------------------------------------------------ */
7499/* decCheckMath - check entry conditions for a math function          */
7500/*                                                                    */
7501/*   This checks the context and the operand                          */
7502/*                                                                    */
7503/*   rhs is the operand to check                                      */
7504/*   set is the context to check                                      */
7505/*   status is unchanged if both are good                             */
7506/*                                                                    */
7507/* returns non-zero if status is changed, 0 otherwise                 */
7508/*                                                                    */
7509/* Restrictions enforced:                                             */
7510/*                                                                    */
7511/*   digits, emax, and -emin in the context must be less than         */
7512/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7513/*   non-zero.  Invalid_operation is set in the status if a           */
7514/*   restriction is violated.                                         */
7515/* ------------------------------------------------------------------ */
7516static uInt decCheckMath(const decNumber *rhs, decContext *set,
7517                         uInt *status) {
7518  uInt save=*status;                         // record
7519  if (set->digits>DEC_MAX_MATH
7520   || set->emax>DEC_MAX_MATH
7521   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7522   else if ((rhs->digits>DEC_MAX_MATH
7523     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7524     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7525     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7526  return (*status!=save);
7527  } // decCheckMath
7528
7529/* ------------------------------------------------------------------ */
7530/* decGetInt -- get integer from a number                             */
7531/*                                                                    */
7532/*   dn is the number [which will not be altered]                     */
7533/*                                                                    */
7534/*   returns one of:                                                  */
7535/*     BADINT if there is a non-zero fraction                         */
7536/*     the converted integer                                          */
7537/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7538/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7539/*                                                                    */
7540/* This checks and gets a whole number from the input decNumber.      */
7541/* The sign can be determined from dn by the caller when BIGEVEN or   */
7542/* BIGODD is returned.                                                */
7543/* ------------------------------------------------------------------ */
7544static Int decGetInt(const decNumber *dn) {
7545  Int  theInt;                          // result accumulator
7546  const Unit *up;                       // work
7547  Int  got;                             // digits (real or not) processed
7548  Int  ilength=dn->digits+dn->exponent; // integral length
7549  Flag neg=decNumberIsNegative(dn);     // 1 if -ve
7550
7551  // The number must be an integer that fits in 10 digits
7552  // Assert, here, that 10 is enough for any rescale Etiny
7553  #if DEC_MAX_EMAX > 999999999
7554    #error GetInt may need updating [for Emax]
7555  #endif
7556  #if DEC_MIN_EMIN < -999999999
7557    #error GetInt may need updating [for Emin]
7558  #endif
7559  if (ISZERO(dn)) return 0;             // zeros are OK, with any exponent
7560
7561  up=dn->lsu;                           // ready for lsu
7562  theInt=0;                             // ready to accumulate
7563  if (dn->exponent>=0) {                // relatively easy
7564    // no fractional part [usual]; allow for positive exponent
7565    got=dn->exponent;
7566    }
7567   else { // -ve exponent; some fractional part to check and discard
7568    Int count=-dn->exponent;            // digits to discard
7569    // spin up whole units until reach the Unit with the unit digit
7570    for (; count>=DECDPUN; up++) {
7571      if (*up!=0) return BADINT;        // non-zero Unit to discard
7572      count-=DECDPUN;
7573      }
7574    if (count==0) got=0;                // [a multiple of DECDPUN]
7575     else {                             // [not multiple of DECDPUN]
7576      Int rem;                          // work
7577      // slice off fraction digits and check for non-zero
7578      #if DECDPUN<=4
7579        theInt=QUOT10(*up, count);
7580        rem=*up-theInt*powers[count];
7581      #else
7582        rem=*up%powers[count];          // slice off discards
7583        theInt=*up/powers[count];
7584      #endif
7585      if (rem!=0) return BADINT;        // non-zero fraction
7586      // it looks good
7587      got=DECDPUN-count;                // number of digits so far
7588      up++;                             // ready for next
7589      }
7590    }
7591  // now it's known there's no fractional part
7592
7593  // tricky code now, to accumulate up to 9.3 digits
7594  if (got==0) {theInt=*up; got+=DECDPUN; up++;} // ensure lsu is there
7595
7596  if (ilength<11) {
7597    Int save=theInt;
7598    // collect any remaining unit(s)
7599    for (; got<ilength; up++) {
7600      theInt+=*up*powers[got];
7601      got+=DECDPUN;
7602      }
7603    if (ilength==10) {                  // need to check for wrap
7604      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7605         // [that test also disallows the BADINT result case]
7606       else if (neg && theInt>1999999997) ilength=11;
7607       else if (!neg && theInt>999999999) ilength=11;
7608      if (ilength==11) theInt=save;     // restore correct low bit
7609      }
7610    }
7611
7612  if (ilength>10) {                     // too big
7613    if (theInt&1) return BIGODD;        // bottom bit 1
7614    return BIGEVEN;                     // bottom bit 0
7615    }
7616
7617  if (neg) theInt=-theInt;              // apply sign
7618  return theInt;
7619  } // decGetInt
7620
7621/* ------------------------------------------------------------------ */
7622/* decDecap -- decapitate the coefficient of a number                 */
7623/*                                                                    */
7624/*   dn   is the number to be decapitated                             */
7625/*   drop is the number of digits to be removed from the left of dn;  */
7626/*     this must be <= dn->digits (if equal, the coefficient is       */
7627/*     set to 0)                                                      */
7628/*                                                                    */
7629/* Returns dn; dn->digits will be <= the initial digits less drop     */
7630/* (after removing drop digits there may be leading zero digits       */
7631/* which will also be removed).  Only dn->lsu and dn->digits change.  */
7632/* ------------------------------------------------------------------ */
7633static decNumber *decDecap(decNumber *dn, Int drop) {
7634  Unit *msu;                            // -> target cut point
7635  Int cut;                              // work
7636  if (drop>=dn->digits) {               // losing the whole thing
7637    #if DECCHECK
7638    if (drop>dn->digits)
7639      printf("decDecap called with drop>digits [%ld>%ld]\n",
7640             (LI)drop, (LI)dn->digits);
7641    #endif
7642    dn->lsu[0]=0;
7643    dn->digits=1;
7644    return dn;
7645    }
7646  msu=dn->lsu+D2U(dn->digits-drop)-1;   // -> likely msu
7647  cut=MSUDIGITS(dn->digits-drop);       // digits to be in use in msu
7648  if (cut!=DECDPUN) *msu%=powers[cut];  // clear left digits
7649  // that may have left leading zero digits, so do a proper count...
7650  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7651  return dn;
7652  } // decDecap
7653
7654/* ------------------------------------------------------------------ */
7655/* decBiStr -- compare string with pairwise options                   */
7656/*                                                                    */
7657/*   targ is the string to compare                                    */
7658/*   str1 is one of the strings to compare against (length may be 0)  */
7659/*   str2 is the other; it must be the same length as str1            */
7660/*                                                                    */
7661/*   returns 1 if strings compare equal, (that is, it is the same     */
7662/*   length as str1 and str2, and each character of targ is in either */
7663/*   str1 or str2 in the corresponding position), or 0 otherwise      */
7664/*                                                                    */
7665/* This is used for generic caseless compare, including the awkward   */
7666/* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7667/*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7668/* ------------------------------------------------------------------ */
7669static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7670  for (;;targ++, str1++, str2++) {
7671    if (*targ!=*str1 && *targ!=*str2) return 0;
7672    // *targ has a match in one (or both, if terminator)
7673    if (*targ=='\0') break;
7674    } // forever
7675  return 1;
7676  } // decBiStr
7677
7678/* ------------------------------------------------------------------ */
7679/* decNaNs -- handle NaN operand or operands                          */
7680/*                                                                    */
7681/*   res     is the result number                                     */
7682/*   lhs     is the first operand                                     */
7683/*   rhs     is the second operand, or NULL if none                   */
7684/*   context is used to limit payload length                          */
7685/*   status  contains the current status                              */
7686/*   returns res in case convenient                                   */
7687/*                                                                    */
7688/* Called when one or both operands is a NaN, and propagates the      */
7689/* appropriate result to res.  When an sNaN is found, it is changed   */
7690/* to a qNaN and Invalid operation is set.                            */
7691/* ------------------------------------------------------------------ */
7692static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7693                           const decNumber *rhs, decContext *set,
7694                           uInt *status) {
7695  // This decision tree ends up with LHS being the source pointer,
7696  // and status updated if need be
7697  if (lhs->bits & DECSNAN)
7698    *status|=DEC_Invalid_operation | DEC_sNaN;
7699   else if (rhs==NULL);
7700   else if (rhs->bits & DECSNAN) {
7701    lhs=rhs;
7702    *status|=DEC_Invalid_operation | DEC_sNaN;
7703    }
7704   else if (lhs->bits & DECNAN);
7705   else lhs=rhs;
7706
7707  // propagate the payload
7708  if (lhs->digits<=set->digits) decNumberCopy(res, lhs); // easy
7709   else { // too long
7710    const Unit *ul;
7711    Unit *ur, *uresp1;
7712    // copy safe number of units, then decapitate
7713    res->bits=lhs->bits;                // need sign etc.
7714    uresp1=res->lsu+D2U(set->digits);
7715    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7716    res->digits=D2U(set->digits)*DECDPUN;
7717    // maybe still too long
7718    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7719    }
7720
7721  res->bits&=~DECSNAN;        // convert any sNaN to NaN, while
7722  res->bits|=DECNAN;          // .. preserving sign
7723  res->exponent=0;            // clean exponent
7724                              // [coefficient was copied/decapitated]
7725  return res;
7726  } // decNaNs
7727
7728/* ------------------------------------------------------------------ */
7729/* decStatus -- apply non-zero status                                 */
7730/*                                                                    */
7731/*   dn     is the number to set if error                             */
7732/*   status contains the current status (not yet in context)          */
7733/*   set    is the context                                            */
7734/*                                                                    */
7735/* If the status is an error status, the number is set to a NaN,      */
7736/* unless the error was an overflow, divide-by-zero, or underflow,    */
7737/* in which case the number will have already been set.               */
7738/*                                                                    */
7739/* The context status is then updated with the new status.  Note that */
7740/* this may raise a signal, so control may never return from this     */
7741/* routine (hence resources must be recovered before it is called).   */
7742/* ------------------------------------------------------------------ */
7743static void decStatus(decNumber *dn, uInt status, decContext *set) {
7744  if (status & DEC_NaNs) {              // error status -> NaN
7745    // if cause was an sNaN, clear and propagate [NaN is already set up]
7746    if (status & DEC_sNaN) status&=~DEC_sNaN;
7747     else {
7748      decNumberZero(dn);                // other error: clean throughout
7749      dn->bits=DECNAN;                  // and make a quiet NaN
7750      }
7751    }
7752  decContextSetStatus(set, status);     // [may not return]
7753  return;
7754  } // decStatus
7755
7756/* ------------------------------------------------------------------ */
7757/* decGetDigits -- count digits in a Units array                      */
7758/*                                                                    */
7759/*   uar is the Unit array holding the number (this is often an       */
7760/*          accumulator of some sort)                                 */
7761/*   len is the length of the array in units [>=1]                    */
7762/*                                                                    */
7763/*   returns the number of (significant) digits in the array          */
7764/*                                                                    */
7765/* All leading zeros are excluded, except the last if the array has   */
7766/* only zero Units.                                                   */
7767/* ------------------------------------------------------------------ */
7768// This may be called twice during some operations.
7769static Int decGetDigits(Unit *uar, Int len) {
7770  Unit *up=uar+(len-1);            // -> msu
7771  Int  digits=(len-1)*DECDPUN+1;   // possible digits excluding msu
7772  #if DECDPUN>4
7773  uInt const *pow;                 // work
7774  #endif
7775                                   // (at least 1 in final msu)
7776  #if DECCHECK
7777  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7778  #endif
7779
7780  for (; up>=uar; up--) {
7781    if (*up==0) {                  // unit is all 0s
7782      if (digits==1) break;        // a zero has one digit
7783      digits-=DECDPUN;             // adjust for 0 unit
7784      continue;}
7785    // found the first (most significant) non-zero Unit
7786    #if DECDPUN>1                  // not done yet
7787    if (*up<10) break;             // is 1-9
7788    digits++;
7789    #if DECDPUN>2                  // not done yet
7790    if (*up<100) break;            // is 10-99
7791    digits++;
7792    #if DECDPUN>3                  // not done yet
7793    if (*up<1000) break;           // is 100-999
7794    digits++;
7795    #if DECDPUN>4                  // count the rest ...
7796    for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7797    #endif
7798    #endif
7799    #endif
7800    #endif
7801    break;
7802    } // up
7803  return digits;
7804  } // decGetDigits
7805
7806#if DECTRACE | DECCHECK
7807/* ------------------------------------------------------------------ */
7808/* decNumberShow -- display a number [debug aid]                      */
7809/*   dn is the number to show                                         */
7810/*                                                                    */
7811/* Shows: sign, exponent, coefficient (msu first), digits             */
7812/*    or: sign, special-value                                         */
7813/* ------------------------------------------------------------------ */
7814// this is public so other modules can use it
7815void decNumberShow(const decNumber *dn) {
7816  const Unit *up;                  // work
7817  uInt u, d;                       // ..
7818  Int cut;                         // ..
7819  char isign='+';                  // main sign
7820  if (dn==NULL) {
7821    printf("NULL\n");
7822    return;}
7823  if (decNumberIsNegative(dn)) isign='-';
7824  printf(" >> %c ", isign);
7825  if (dn->bits&DECSPECIAL) {       // Is a special value
7826    if (decNumberIsInfinite(dn)) printf("Infinity");
7827     else {                                  // a NaN
7828      if (dn->bits&DECSNAN) printf("sNaN");  // signalling NaN
7829       else printf("NaN");
7830      }
7831    // if coefficient and exponent are 0, no more to do
7832    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7833      printf("\n");
7834      return;}
7835    // drop through to report other information
7836    printf(" ");
7837    }
7838
7839  // now carefully display the coefficient
7840  up=dn->lsu+D2U(dn->digits)-1;         // msu
7841  printf("%ld", (LI)*up);
7842  for (up=up-1; up>=dn->lsu; up--) {
7843    u=*up;
7844    printf(":");
7845    for (cut=DECDPUN-1; cut>=0; cut--) {
7846      d=u/powers[cut];
7847      u-=d*powers[cut];
7848      printf("%ld", (LI)d);
7849      } // cut
7850    } // up
7851  if (dn->exponent!=0) {
7852    char esign='+';
7853    if (dn->exponent<0) esign='-';
7854    printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7855    }
7856  printf(" [%ld]\n", (LI)dn->digits);
7857  } // decNumberShow
7858#endif
7859
7860#if DECTRACE || DECCHECK
7861/* ------------------------------------------------------------------ */
7862/* decDumpAr -- display a unit array [debug/check aid]                */
7863/*   name is a single-character tag name                              */
7864/*   ar   is the array to display                                     */
7865/*   len  is the length of the array in Units                         */
7866/* ------------------------------------------------------------------ */
7867static void decDumpAr(char name, const Unit *ar, Int len) {
7868  Int i;
7869  const char *spec;
7870  #if DECDPUN==9
7871    spec="%09d ";
7872  #elif DECDPUN==8
7873    spec="%08d ";
7874  #elif DECDPUN==7
7875    spec="%07d ";
7876  #elif DECDPUN==6
7877    spec="%06d ";
7878  #elif DECDPUN==5
7879    spec="%05d ";
7880  #elif DECDPUN==4
7881    spec="%04d ";
7882  #elif DECDPUN==3
7883    spec="%03d ";
7884  #elif DECDPUN==2
7885    spec="%02d ";
7886  #else
7887    spec="%d ";
7888  #endif
7889  printf("  :%c: ", name);
7890  for (i=len-1; i>=0; i--) {
7891    if (i==len-1) printf("%ld ", (LI)ar[i]);
7892     else printf(spec, ar[i]);
7893    }
7894  printf("\n");
7895  return;}
7896#endif
7897
7898#if DECCHECK
7899/* ------------------------------------------------------------------ */
7900/* decCheckOperands -- check operand(s) to a routine                  */
7901/*   res is the result structure (not checked; it will be set to      */
7902/*          quiet NaN if error found (and it is not NULL))            */
7903/*   lhs is the first operand (may be DECUNRESU)                      */
7904/*   rhs is the second (may be DECUNUSED)                             */
7905/*   set is the context (may be DECUNCONT)                            */
7906/*   returns 0 if both operands, and the context are clean, or 1      */
7907/*     otherwise (in which case the context will show an error,       */
7908/*     unless NULL).  Note that res is not cleaned; caller should     */
7909/*     handle this so res=NULL case is safe.                          */
7910/* The caller is expected to abandon immediately if 1 is returned.    */
7911/* ------------------------------------------------------------------ */
7912static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7913                             const decNumber *rhs, decContext *set) {
7914  Flag bad=0;
7915  if (set==NULL) {                 // oops; hopeless
7916    #if DECTRACE || DECVERB
7917    printf("Reference to context is NULL.\n");
7918    #endif
7919    bad=1;
7920    return 1;}
7921   else if (set!=DECUNCONT
7922     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7923    bad=1;
7924    #if DECTRACE || DECVERB
7925    printf("Bad context [digits=%ld round=%ld].\n",
7926           (LI)set->digits, (LI)set->round);
7927    #endif
7928    }
7929   else {
7930    if (res==NULL) {
7931      bad=1;
7932      #if DECTRACE
7933      // this one not DECVERB as standard tests include NULL
7934      printf("Reference to result is NULL.\n");
7935      #endif
7936      }
7937    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7938    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7939    }
7940  if (bad) {
7941    if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7942    if (res!=DECUNRESU && res!=NULL) {
7943      decNumberZero(res);
7944      res->bits=DECNAN;       // qNaN
7945      }
7946    }
7947  return bad;
7948  } // decCheckOperands
7949
7950/* ------------------------------------------------------------------ */
7951/* decCheckNumber -- check a number                                   */
7952/*   dn is the number to check                                        */
7953/*   returns 0 if the number is clean, or 1 otherwise                 */
7954/*                                                                    */
7955/* The number is considered valid if it could be a result from some   */
7956/* operation in some valid context.                                   */
7957/* ------------------------------------------------------------------ */
7958static Flag decCheckNumber(const decNumber *dn) {
7959  const Unit *up;             // work
7960  uInt maxuint;               // ..
7961  Int ae, d, digits;          // ..
7962  Int emin, emax;             // ..
7963
7964  if (dn==NULL) {             // hopeless
7965    #if DECTRACE
7966    // this one not DECVERB as standard tests include NULL
7967    printf("Reference to decNumber is NULL.\n");
7968    #endif
7969    return 1;}
7970
7971  // check special values
7972  if (dn->bits & DECSPECIAL) {
7973    if (dn->exponent!=0) {
7974      #if DECTRACE || DECVERB
7975      printf("Exponent %ld (not 0) for a special value [%02x].\n",
7976             (LI)dn->exponent, dn->bits);
7977      #endif
7978      return 1;}
7979
7980    // 2003.09.08: NaNs may now have coefficients, so next tests Inf only
7981    if (decNumberIsInfinite(dn)) {
7982      if (dn->digits!=1) {
7983        #if DECTRACE || DECVERB
7984        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7985        #endif
7986        return 1;}
7987      if (*dn->lsu!=0) {
7988        #if DECTRACE || DECVERB
7989        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7990        #endif
7991        decDumpAr('I', dn->lsu, D2U(dn->digits));
7992        return 1;}
7993      } // Inf
7994    // 2002.12.26: negative NaNs can now appear through proposed IEEE
7995    //             concrete formats (decimal64, etc.).
7996    return 0;
7997    }
7998
7999  // check the coefficient
8000  if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8001    #if DECTRACE || DECVERB
8002    printf("Digits %ld in number.\n", (LI)dn->digits);
8003    #endif
8004    return 1;}
8005
8006  d=dn->digits;
8007
8008  for (up=dn->lsu; d>0; up++) {
8009    if (d>DECDPUN) maxuint=DECDPUNMAX;
8010     else {                   // reached the msu
8011      maxuint=powers[d]-1;
8012      if (dn->digits>1 && *up<powers[d-1]) {
8013        #if DECTRACE || DECVERB
8014        printf("Leading 0 in number.\n");
8015        decNumberShow(dn);
8016        #endif
8017        return 1;}
8018      }
8019    if (*up>maxuint) {
8020      #if DECTRACE || DECVERB
8021      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8022              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8023      #endif
8024      return 1;}
8025    d-=DECDPUN;
8026    }
8027
8028  // check the exponent.  Note that input operands can have exponents
8029  // which are out of the set->emin/set->emax and set->digits range
8030  // (just as they can have more digits than set->digits).
8031  ae=dn->exponent+dn->digits-1;    // adjusted exponent
8032  emax=DECNUMMAXE;
8033  emin=DECNUMMINE;
8034  digits=DECNUMMAXP;
8035  if (ae<emin-(digits-1)) {
8036    #if DECTRACE || DECVERB
8037    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8038    decNumberShow(dn);
8039    #endif
8040    return 1;}
8041  if (ae>+emax) {
8042    #if DECTRACE || DECVERB
8043    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8044    decNumberShow(dn);
8045    #endif
8046    return 1;}
8047
8048  return 0;              // it's OK
8049  } // decCheckNumber
8050
8051/* ------------------------------------------------------------------ */
8052/* decCheckInexact -- check a normal finite inexact result has digits */
8053/*   dn is the number to check                                        */
8054/*   set is the context (for status and precision)                    */
8055/*   sets Invalid operation, etc., if some digits are missing         */
8056/* [this check is not made for DECSUBSET compilation or when          */
8057/* subnormal is not set]                                              */
8058/* ------------------------------------------------------------------ */
8059static void decCheckInexact(const decNumber *dn, decContext *set) {
8060  #if !DECSUBSET && DECEXTFLAG
8061    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8062     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8063      #if DECTRACE || DECVERB
8064      printf("Insufficient digits [%ld] on normal Inexact result.\n",
8065             (LI)dn->digits);
8066      decNumberShow(dn);
8067      #endif
8068      decContextSetStatus(set, DEC_Invalid_operation);
8069      }
8070  #else
8071    // next is a noop for quiet compiler
8072    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8073  #endif
8074  return;
8075  } // decCheckInexact
8076#endif
8077
8078#if DECALLOC
8079#undef malloc
8080#undef free
8081/* ------------------------------------------------------------------ */
8082/* decMalloc -- accountable allocation routine                        */
8083/*   n is the number of bytes to allocate                             */
8084/*                                                                    */
8085/* Semantics is the same as the stdlib malloc routine, but bytes      */
8086/* allocated are accounted for globally, and corruption fences are    */
8087/* added before and after the 'actual' storage.                       */
8088/* ------------------------------------------------------------------ */
8089/* This routine allocates storage with an extra twelve bytes; 8 are   */
8090/* at the start and hold:                                             */
8091/*   0-3 the original length requested                                */
8092/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8093/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8094/* ------------------------------------------------------------------ */
8095static void *decMalloc(size_t n) {
8096  uInt  size=n+12;                 // true size
8097  void  *alloc;                    // -> allocated storage
8098  uByte *b, *b0;                   // work
8099  uInt  uiwork;                    // for macros
8100
8101  alloc=malloc(size);              // -> allocated storage
8102  if (alloc==NULL) return NULL;    // out of strorage
8103  b0=(uByte *)alloc;               // as bytes
8104  decAllocBytes+=n;                // account for storage
8105  UBFROMUI(alloc, n);              // save n
8106  // printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);
8107  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8108  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8109  return b0+8;                     // -> play area
8110  } // decMalloc
8111
8112/* ------------------------------------------------------------------ */
8113/* decFree -- accountable free routine                                */
8114/*   alloc is the storage to free                                     */
8115/*                                                                    */
8116/* Semantics is the same as the stdlib malloc routine, except that    */
8117/* the global storage accounting is updated and the fences are        */
8118/* checked to ensure that no routine has written 'out of bounds'.     */
8119/* ------------------------------------------------------------------ */
8120/* This routine first checks that the fences have not been corrupted. */
8121/* It then frees the storage using the 'truw' storage address (that   */
8122/* is, offset by 8).                                                  */
8123/* ------------------------------------------------------------------ */
8124static void decFree(void *alloc) {
8125  uInt  n;                         // original length
8126  uByte *b, *b0;                   // work
8127  uInt  uiwork;                    // for macros
8128
8129  if (alloc==NULL) return;         // allowed; it's a nop
8130  b0=(uByte *)alloc;               // as bytes
8131  b0-=8;                           // -> true start of storage
8132  n=UBTOUI(b0);                    // lift length
8133  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8134    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8135           b-b0-8, (LI)b0);
8136  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8137    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8138           b-b0-8, (LI)b0, (LI)n);
8139  free(b0);                        // drop the storage
8140  decAllocBytes-=n;                // account for storage
8141  // printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);
8142  } // decFree
8143#define malloc(a) decMalloc(a)
8144#define free(a) decFree(a)
8145#endif
8146