OSDN Git Service

Merge botch fixed.
[pf3gnuchains/gcc-fork.git] / libdecnumber / decNumber.c
1 /* Decimal number arithmetic module for the decNumber C Library.
2    Copyright (C) 2005, 2007 Free Software Foundation, Inc.
3    Contributed by IBM Corporation.  Author Mike Cowlishaw.
4
5    This file is part of GCC.
6
7    GCC is free software; you can redistribute it and/or modify it under
8    the terms of the GNU General Public License as published by the Free
9    Software Foundation; either version 2, or (at your option) any later
10    version.
11
12    In addition to the permissions in the GNU General Public License,
13    the Free Software Foundation gives you unlimited permission to link
14    the compiled version of this file into combinations with other
15    programs, and to distribute those combinations without any
16    restriction coming from the use of this file.  (The General Public
17    License restrictions do apply in other respects; for example, they
18    cover modification of the file, and distribution when not linked
19    into a combine executable.)
20
21    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
22    WARRANTY; without even the implied warranty of MERCHANTABILITY or
23    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
24    for more details.
25
26    You should have received a copy of the GNU General Public License
27    along with GCC; see the file COPYING.  If not, write to the Free
28    Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA
29    02110-1301, USA.  */
30
31 /* ------------------------------------------------------------------ */
32 /* Decimal Number arithmetic module                                   */
33 /* ------------------------------------------------------------------ */
34 /* This module comprises the routines for arbitrary-precision General */
35 /* Decimal Arithmetic as defined in the specification which may be    */
36 /* found on the General Decimal Arithmetic pages.  It implements both */
37 /* the full ('extended') arithmetic and the simpler ('subset')        */
38 /* arithmetic.                                                        */
39 /*                                                                    */
40 /* Usage notes:                                                       */
41 /*                                                                    */
42 /* 1. This code is ANSI C89 except:                                   */
43 /*                                                                    */
44 /*    a) C99 line comments (double forward slash) are used.  (Most C  */
45 /*       compilers accept these.  If yours does not, a simple script  */
46 /*       can be used to convert them to ANSI C comments.)             */
47 /*                                                                    */
48 /*    b) Types from C99 stdint.h are used.  If you do not have this   */
49 /*       header file, see the User's Guide section of the decNumber   */
50 /*       documentation; this lists the necessary definitions.         */
51 /*                                                                    */
52 /*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
53 /*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
54 /*       and DECDPUN<=4 (see documentation).                          */
55 /*                                                                    */
56 /*    The code also conforms to C99 restrictions; in particular,      */
57 /*    strict aliasing rules are observed.                             */
58 /*                                                                    */
59 /* 2. The decNumber format which this library uses is optimized for   */
60 /*    efficient processing of relatively short numbers; in particular */
61 /*    it allows the use of fixed sized structures and minimizes copy  */
62 /*    and move operations.  It does, however, support arbitrary       */
63 /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
64 /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
65 /*    range -999,999,999 through 0).  Mathematical functions (for     */
66 /*    example decNumberExp) as identified below are restricted more   */
67 /*    tightly: digits, emax, and -emin in the context must be <=      */
68 /*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
69 /*    these bounds.                                                   */
70 /*                                                                    */
71 /* 3. Logical functions are further restricted; their operands must   */
72 /*    be finite, positive, have an exponent of zero, and all digits   */
73 /*    must be either 0 or 1.  The result will only contain digits     */
74 /*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
75 /*                                                                    */
76 /* 4. Operands to operator functions are never modified unless they   */
77 /*    are also specified to be the result number (which is always     */
78 /*    permitted).  Other than that case, operands must not overlap.   */
79 /*                                                                    */
80 /* 5. Error handling: the type of the error is ORed into the status   */
81 /*    flags in the current context (decContext structure).  The       */
82 /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
83 /*    flag in the decContext is set (is 1).                           */
84 /*                                                                    */
85 /*    It is the responsibility of the caller to clear the status      */
86 /*    flags as required.                                              */
87 /*                                                                    */
88 /*    The result of any routine which returns a number will always    */
89 /*    be a valid number (which may be a special value, such as an     */
90 /*    Infinity or NaN).                                               */
91 /*                                                                    */
92 /* 6. The decNumber format is not an exchangeable concrete            */
93 /*    representation as it comprises fields which may be machine-     */
94 /*    dependent (packed or unpacked, or special length, for example). */
95 /*    Canonical conversions to and from strings are provided; other   */
96 /*    conversions are available in separate modules.                  */
97 /*                                                                    */
98 /* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
99 /*    to 1 for extended operand checking (including NULL operands).   */
100 /*    Results are undefined if a badly-formed structure (or a NULL    */
101 /*    pointer to a structure) is provided, though with DECCHECK       */
102 /*    enabled the operator routines are protected against exceptions. */
103 /*    (Except if the result pointer is NULL, which is unrecoverable.) */
104 /*                                                                    */
105 /*    However, the routines will never cause exceptions if they are   */
106 /*    given well-formed operands, even if the value of the operands   */
107 /*    is inappropriate for the operation and DECCHECK is not set.     */
108 /*    (Except for SIGFPE, as and where documented.)                   */
109 /*                                                                    */
110 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
111 /* ------------------------------------------------------------------ */
112 /* Implementation notes for maintenance of this module:               */
113 /*                                                                    */
114 /* 1. Storage leak protection:  Routines which use malloc are not     */
115 /*    permitted to use return for fastpath or error exits (i.e.,      */
116 /*    they follow strict structured programming conventions).         */
117 /*    Instead they have a do{}while(0); construct surrounding the     */
118 /*    code which is protected -- break may be used to exit this.      */
119 /*    Other routines can safely use the return statement inline.      */
120 /*                                                                    */
121 /*    Storage leak accounting can be enabled using DECALLOC.          */
122 /*                                                                    */
123 /* 2. All loops use the for(;;) construct.  Any do construct does     */
124 /*    not loop; it is for allocation protection as just described.    */
125 /*                                                                    */
126 /* 3. Setting status in the context must always be the very last      */
127 /*    action in a routine, as non-0 status may raise a trap and hence */
128 /*    the call to set status may not return (if the handler uses long */
129 /*    jump).  Therefore all cleanup must be done first.  In general,  */
130 /*    to achieve this status is accumulated and is only applied just  */
131 /*    before return by calling decContextSetStatus (via decStatus).   */
132 /*                                                                    */
133 /*    Routines which allocate storage cannot, in general, use the     */
134 /*    'top level' routines which could cause a non-returning          */
135 /*    transfer of control.  The decXxxxOp routines are safe (do not   */
136 /*    call decStatus even if traps are set in the context) and should */
137 /*    be used instead (they are also a little faster).                */
138 /*                                                                    */
139 /* 4. Exponent checking is minimized by allowing the exponent to      */
140 /*    grow outside its limits during calculations, provided that      */
141 /*    the decFinalize function is called later.  Multiplication and   */
142 /*    division, and intermediate calculations in exponentiation,      */
143 /*    require more careful checks because of the risk of 31-bit       */
144 /*    overflow (the most negative valid exponent is -1999999997, for  */
145 /*    a 999999999-digit number with adjusted exponent of -999999999). */
146 /*                                                                    */
147 /* 5. Rounding is deferred until finalization of results, with any    */
148 /*    'off to the right' data being represented as a single digit     */
149 /*    residue (in the range -1 through 9).  This avoids any double-   */
150 /*    rounding when more than one shortening takes place (for         */
151 /*    example, when a result is subnormal).                           */
152 /*                                                                    */
153 /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
154 /*    during many operations, so whole Units are handled and exact    */
155 /*    accounting of digits is not needed.  The correct digits value   */
156 /*    is found by decGetDigits, which accounts for leading zeros.     */
157 /*    This must be called before any rounding if the number of digits */
158 /*    is not known exactly.                                           */
159 /*                                                                    */
160 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
161 /*    numbers up to four digits, using appropriate constants.  This   */
162 /*    is not useful for longer numbers because overflow of 32 bits    */
163 /*    would lead to 4 multiplies, which is almost as expensive as     */
164 /*    a divide (unless a floating-point or 64-bit multiply is         */
165 /*    assumed to be available).                                       */
166 /*                                                                    */
167 /* 8. Unusual abbreviations that may be used in the commentary:       */
168 /*      lhs -- left hand side (operand, of an operation)              */
169 /*      lsd -- least significant digit (of coefficient)               */
170 /*      lsu -- least significant Unit (of coefficient)                */
171 /*      msd -- most significant digit (of coefficient)                */
172 /*      msi -- most significant item (in an array)                    */
173 /*      msu -- most significant Unit (of coefficient)                 */
174 /*      rhs -- right hand side (operand, of an operation)             */
175 /*      +ve -- positive                                               */
176 /*      -ve -- negative                                               */
177 /*      **  -- raise to the power                                     */
178 /* ------------------------------------------------------------------ */
179
180 #include <stdlib.h>                /* for malloc, free, etc. */
181 #include <stdio.h>                 /* for printf [if needed] */
182 #include <string.h>                /* for strcpy */
183 #include <ctype.h>                 /* for lower */
184 #include "dconfig.h"               /* for GCC definitions */
185 #include "decNumber.h"             /* base number library */
186 #include "decNumberLocal.h"        /* decNumber local types, etc. */
187
188 /* Constants */
189 /* Public lookup table used by the D2U macro */
190 const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
191
192 #define DECVERB     1              /* set to 1 for verbose DECCHECK */
193 #define powers      DECPOWERS      /* old internal name */
194
195 /* Local constants */
196 #define DIVIDE      0x80           /* Divide operators */
197 #define REMAINDER   0x40           /* .. */
198 #define DIVIDEINT   0x20           /* .. */
199 #define REMNEAR     0x10           /* .. */
200 #define COMPARE     0x01           /* Compare operators */
201 #define COMPMAX     0x02           /* .. */
202 #define COMPMIN     0x03           /* .. */
203 #define COMPTOTAL   0x04           /* .. */
204 #define COMPNAN     0x05           /* .. [NaN processing] */
205 #define COMPSIG     0x06           /* .. [signaling COMPARE] */
206 #define COMPMAXMAG  0x07           /* .. */
207 #define COMPMINMAG  0x08           /* .. */
208
209 #define DEC_sNaN     0x40000000    /* local status: sNaN signal */
210 #define BADINT  (Int)0x80000000    /* most-negative Int; error indicator */
211 /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
212 #define BIGEVEN (Int)0x80000002
213 #define BIGODD  (Int)0x80000003
214
215 static Unit uarrone[1]={1};   /* Unit array of 1, used for incrementing */
216
217 /* Granularity-dependent code */
218 #if DECDPUN<=4
219   #define eInt  Int           /* extended integer */
220   #define ueInt uInt          /* unsigned extended integer */
221   /* Constant multipliers for divide-by-power-of five using reciprocal */
222   /* multiply, after removing powers of 2 by shifting, and final shift */
223   /* of 17 [we only need up to **4] */
224   static const uInt multies[]={131073, 26215, 5243, 1049, 210};
225   /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
226   #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
227 #else
228   /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
229   #if !DECUSE64
230     #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
231   #endif
232   #define eInt  Long          /* extended integer */
233   #define ueInt uLong         /* unsigned extended integer */
234 #endif
235
236 /* Local routines */
237 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
238                               decContext *, uByte, uInt *);
239 static Flag        decBiStr(const char *, const char *, const char *);
240 static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
241 static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
242 static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
243 static decNumber * decCompareOp(decNumber *, const decNumber *,
244                               const decNumber *, decContext *,
245                               Flag, uInt *);
246 static void        decCopyFit(decNumber *, const decNumber *, decContext *,
247                               Int *, uInt *);
248 static decNumber * decDecap(decNumber *, Int);
249 static decNumber * decDivideOp(decNumber *, const decNumber *,
250                               const decNumber *, decContext *, Flag, uInt *);
251 static decNumber * decExpOp(decNumber *, const decNumber *,
252                               decContext *, uInt *);
253 static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
254 static Int         decGetDigits(Unit *, Int);
255 static Int         decGetInt(const decNumber *);
256 static decNumber * decLnOp(decNumber *, const decNumber *,
257                               decContext *, uInt *);
258 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
259                               const decNumber *, decContext *,
260                               uInt *);
261 static decNumber * decNaNs(decNumber *, const decNumber *,
262                               const decNumber *, decContext *, uInt *);
263 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
264                               const decNumber *, decContext *, Flag,
265                               uInt *);
266 static void        decReverse(Unit *, Unit *);
267 static void        decSetCoeff(decNumber *, decContext *, const Unit *,
268                               Int, Int *, uInt *);
269 static void        decSetMaxValue(decNumber *, decContext *);
270 static void        decSetOverflow(decNumber *, decContext *, uInt *);
271 static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
272 static Int         decShiftToLeast(Unit *, Int, Int);
273 static Int         decShiftToMost(Unit *, Int, Int);
274 static void        decStatus(decNumber *, uInt, decContext *);
275 static void        decToString(const decNumber *, char[], Flag);
276 static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
277 static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
278                               Unit *, Int);
279 static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
280
281 #if !DECSUBSET
282 /* decFinish == decFinalize when no subset arithmetic needed */
283 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
284 #else
285 static void        decFinish(decNumber *, decContext *, Int *, uInt *);
286 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
287 #endif
288
289 /* Local macros */
290 /* masked special-values bits */
291 #define SPECIALARG  (rhs->bits & DECSPECIAL)
292 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
293
294 /* Diagnostic macros, etc. */
295 #if DECALLOC
296 /* Handle malloc/free accounting.  If enabled, our accountable routines */
297 /* are used; otherwise the code just goes straight to the system malloc */
298 /* and free routines. */
299 #define malloc(a) decMalloc(a)
300 #define free(a) decFree(a)
301 #define DECFENCE 0x5a              /* corruption detector */
302 /* 'Our' malloc and free: */
303 static void *decMalloc(size_t);
304 static void  decFree(void *);
305 uInt decAllocBytes=0;              /* count of bytes allocated */
306 /* Note that DECALLOC code only checks for storage buffer overflow. */
307 /* To check for memory leaks, the decAllocBytes variable must be */
308 /* checked to be 0 at appropriate times (e.g., after the test */
309 /* harness completes a set of tests).  This checking may be unreliable */
310 /* if the testing is done in a multi-thread environment. */
311 #endif
312
313 #if DECCHECK
314 /* Optional checking routines.  Enabling these means that decNumber */
315 /* and decContext operands to operator routines are checked for */
316 /* correctness.  This roughly doubles the execution time of the */
317 /* fastest routines (and adds 600+ bytes), so should not normally be */
318 /* used in 'production'. */
319 /* decCheckInexact is used to check that inexact results have a full */
320 /* complement of digits (where appropriate -- this is not the case */
321 /* for Quantize, for example) */
322 #define DECUNRESU ((decNumber *)(void *)0xffffffff)
323 #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
324 #define DECUNCONT ((decContext *)(void *)(0xffffffff))
325 static Flag decCheckOperands(decNumber *, const decNumber *,
326                              const decNumber *, decContext *);
327 static Flag decCheckNumber(const decNumber *);
328 static void decCheckInexact(const decNumber *, decContext *);
329 #endif
330
331 #if DECTRACE || DECCHECK
332 /* Optional trace/debugging routines (may or may not be used) */
333 void decNumberShow(const decNumber *);  /* displays the components of a number */
334 static void decDumpAr(char, const Unit *, Int);
335 #endif
336
337 /* ================================================================== */
338 /* Conversions                                                        */
339 /* ================================================================== */
340
341 /* ------------------------------------------------------------------ */
342 /* from-int32 -- conversion from Int or uInt                          */
343 /*                                                                    */
344 /*  dn is the decNumber to receive the integer                        */
345 /*  in or uin is the integer to be converted                          */
346 /*  returns dn                                                        */
347 /*                                                                    */
348 /* No error is possible.                                              */
349 /* ------------------------------------------------------------------ */
350 decNumber * decNumberFromInt32(decNumber *dn, Int in) {
351   uInt unsig;
352   if (in>=0) unsig=in;
353    else {                               /* negative (possibly BADINT) */
354     if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
355      else unsig=-in;                    /* invert */
356     }
357   /* in is now positive */
358   decNumberFromUInt32(dn, unsig);
359   if (in<0) dn->bits=DECNEG;            /* sign needed */
360   return dn;
361   } /* decNumberFromInt32 */
362
363 decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
364   Unit *up;                             /* work pointer */
365   decNumberZero(dn);                    /* clean */
366   if (uin==0) return dn;                /* [or decGetDigits bad call] */
367   for (up=dn->lsu; uin>0; up++) {
368     *up=(Unit)(uin%(DECDPUNMAX+1));
369     uin=uin/(DECDPUNMAX+1);
370     }
371   dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
372   return dn;
373   } /* decNumberFromUInt32 */
374
375 /* ------------------------------------------------------------------ */
376 /* to-int32 -- conversion to Int or uInt                              */
377 /*                                                                    */
378 /*  dn is the decNumber to convert                                    */
379 /*  set is the context for reporting errors                           */
380 /*  returns the converted decNumber, or 0 if Invalid is set           */
381 /*                                                                    */
382 /* Invalid is set if the decNumber does not have exponent==0 or if    */
383 /* it is a NaN, Infinite, or out-of-range.                            */
384 /* ------------------------------------------------------------------ */
385 Int decNumberToInt32(const decNumber *dn, decContext *set) {
386   #if DECCHECK
387   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
388   #endif
389
390   /* special or too many digits, or bad exponent */
391   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
392    else { /* is a finite integer with 10 or fewer digits */
393     Int d;                         /* work */
394     const Unit *up;                /* .. */
395     uInt hi=0, lo;                 /* .. */
396     up=dn->lsu;                    /* -> lsu */
397     lo=*up;                        /* get 1 to 9 digits */
398     #if DECDPUN>1                  /* split to higher */
399       hi=lo/10;
400       lo=lo%10;
401     #endif
402     up++;
403     /* collect remaining Units, if any, into hi */
404     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
405     /* now low has the lsd, hi the remainder */
406     if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
407       /* most-negative is a reprieve */
408       if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
409       /* bad -- drop through */
410       }
411      else { /* in-range always */
412       Int i=X10(hi)+lo;
413       if (dn->bits&DECNEG) return -i;
414       return i;
415       }
416     } /* integer */
417   decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
418   return 0;
419   } /* decNumberToInt32 */
420
421 uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
422   #if DECCHECK
423   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
424   #endif
425   /* special or too many digits, or bad exponent, or negative (<0) */
426   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
427     || (dn->bits&DECNEG && !ISZERO(dn)));                   /* bad */
428    else { /* is a finite integer with 10 or fewer digits */
429     Int d;                         /* work */
430     const Unit *up;                /* .. */
431     uInt hi=0, lo;                 /* .. */
432     up=dn->lsu;                    /* -> lsu */
433     lo=*up;                        /* get 1 to 9 digits */
434     #if DECDPUN>1                  /* split to higher */
435       hi=lo/10;
436       lo=lo%10;
437     #endif
438     up++;
439     /* collect remaining Units, if any, into hi */
440     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
441
442     /* now low has the lsd, hi the remainder */
443     if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
444      else return X10(hi)+lo;
445     } /* integer */
446   decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
447   return 0;
448   } /* decNumberToUInt32 */
449
450 /* ------------------------------------------------------------------ */
451 /* to-scientific-string -- conversion to numeric string               */
452 /* to-engineering-string -- conversion to numeric string              */
453 /*                                                                    */
454 /*   decNumberToString(dn, string);                                   */
455 /*   decNumberToEngString(dn, string);                                */
456 /*                                                                    */
457 /*  dn is the decNumber to convert                                    */
458 /*  string is the string where the result will be laid out            */
459 /*                                                                    */
460 /*  string must be at least dn->digits+14 characters long             */
461 /*                                                                    */
462 /*  No error is possible, and no status can be set.                   */
463 /* ------------------------------------------------------------------ */
464 char * decNumberToString(const decNumber *dn, char *string){
465   decToString(dn, string, 0);
466   return string;
467   } /* DecNumberToString */
468
469 char * decNumberToEngString(const decNumber *dn, char *string){
470   decToString(dn, string, 1);
471   return string;
472   } /* DecNumberToEngString */
473
474 /* ------------------------------------------------------------------ */
475 /* to-number -- conversion from numeric string                        */
476 /*                                                                    */
477 /* decNumberFromString -- convert string to decNumber                 */
478 /*   dn        -- the number structure to fill                        */
479 /*   chars[]   -- the string to convert ('\0' terminated)             */
480 /*   set       -- the context used for processing any error,          */
481 /*                determining the maximum precision available         */
482 /*                (set.digits), determining the maximum and minimum   */
483 /*                exponent (set.emax and set.emin), determining if    */
484 /*                extended values are allowed, and checking the       */
485 /*                rounding mode if overflow occurs or rounding is     */
486 /*                needed.                                             */
487 /*                                                                    */
488 /* The length of the coefficient and the size of the exponent are     */
489 /* checked by this routine, so the correct error (Underflow or        */
490 /* Overflow) can be reported or rounding applied, as necessary.       */
491 /*                                                                    */
492 /* If bad syntax is detected, the result will be a quiet NaN.         */
493 /* ------------------------------------------------------------------ */
494 decNumber * decNumberFromString(decNumber *dn, const char chars[],
495                                 decContext *set) {
496   Int   exponent=0;                /* working exponent [assume 0] */
497   uByte bits=0;                    /* working flags [assume +ve] */
498   Unit  *res;                      /* where result will be built */
499   Unit  resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
500                                    /* [+9 allows for ln() constants] */
501   Unit  *allocres=NULL;            /* -> allocated result, iff allocated */
502   Int   d=0;                       /* count of digits found in decimal part */
503   const char *dotchar=NULL;        /* where dot was found */
504   const char *cfirst=chars;        /* -> first character of decimal part */
505   const char *last=NULL;           /* -> last digit of decimal part */
506   const char *c;                   /* work */
507   Unit  *up;                       /* .. */
508   #if DECDPUN>1
509   Int   cut, out;                  /* .. */
510   #endif
511   Int   residue;                   /* rounding residue */
512   uInt  status=0;                  /* error code */
513
514   #if DECCHECK
515   if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
516     return decNumberZero(dn);
517   #endif
518
519   do {                             /* status & malloc protection */
520     for (c=chars;; c++) {          /* -> input character */
521       if (*c>='0' && *c<='9') {    /* test for Arabic digit */
522         last=c;
523         d++;                       /* count of real digits */
524         continue;                  /* still in decimal part */
525         }
526       if (*c=='.' && dotchar==NULL) { /* first '.' */
527         dotchar=c;                 /* record offset into decimal part */
528         if (c==cfirst) cfirst++;   /* first digit must follow */
529         continue;}
530       if (c==chars) {              /* first in string... */
531         if (*c=='-') {             /* valid - sign */
532           cfirst++;
533           bits=DECNEG;
534           continue;}
535         if (*c=='+') {             /* valid + sign */
536           cfirst++;
537           continue;}
538         }
539       /* *c is not a digit, or a valid +, -, or '.' */
540       break;
541       } /* c */
542
543     if (last==NULL) {              /* no digits yet */
544       status=DEC_Conversion_syntax;/* assume the worst */
545       if (*c=='\0') break;         /* and no more to come... */
546       #if DECSUBSET
547       /* if subset then infinities and NaNs are not allowed */
548       if (!set->extended) break;   /* hopeless */
549       #endif
550       /* Infinities and NaNs are possible, here */
551       if (dotchar!=NULL) break;    /* .. unless had a dot */
552       decNumberZero(dn);           /* be optimistic */
553       if (decBiStr(c, "infinity", "INFINITY")
554        || decBiStr(c, "inf", "INF")) {
555         dn->bits=bits | DECINF;
556         status=0;                  /* is OK */
557         break; /* all done */
558         }
559       /* a NaN expected */
560       /* 2003.09.10 NaNs are now permitted to have a sign */
561       dn->bits=bits | DECNAN;      /* assume simple NaN */
562       if (*c=='s' || *c=='S') {    /* looks like an sNaN */
563         c++;
564         dn->bits=bits | DECSNAN;
565         }
566       if (*c!='n' && *c!='N') break;    /* check caseless "NaN" */
567       c++;
568       if (*c!='a' && *c!='A') break;    /* .. */
569       c++;
570       if (*c!='n' && *c!='N') break;    /* .. */
571       c++;
572       /* now either nothing, or nnnn payload, expected */
573       /* -> start of integer and skip leading 0s [including plain 0] */
574       for (cfirst=c; *cfirst=='0';) cfirst++;
575       if (*cfirst=='\0') {         /* "NaN" or "sNaN", maybe with all 0s */
576         status=0;                  /* it's good */
577         break;                     /* .. */
578         }
579       /* something other than 0s; setup last and d as usual [no dots] */
580       for (c=cfirst;; c++, d++) {
581         if (*c<'0' || *c>'9') break; /* test for Arabic digit */
582         last=c;
583         }
584       if (*c!='\0') break;         /* not all digits */
585       if (d>set->digits-1) {
586         /* [NB: payload in a decNumber can be full length unless */
587         /* clamped, in which case can only be digits-1] */
588         if (set->clamp) break;
589         if (d>set->digits) break;
590         } /* too many digits? */
591       /* good; drop through to convert the integer to coefficient */
592       status=0;                    /* syntax is OK */
593       bits=dn->bits;               /* for copy-back */
594       } /* last==NULL */
595
596      else if (*c!='\0') {          /* more to process... */
597       /* had some digits; exponent is only valid sequence now */
598       Flag nege;                   /* 1=negative exponent */
599       const char *firstexp;        /* -> first significant exponent digit */
600       status=DEC_Conversion_syntax;/* assume the worst */
601       if (*c!='e' && *c!='E') break;
602       /* Found 'e' or 'E' -- now process explicit exponent */
603       /* 1998.07.11: sign no longer required */
604       nege=0;
605       c++;                         /* to (possible) sign */
606       if (*c=='-') {nege=1; c++;}
607        else if (*c=='+') c++;
608       if (*c=='\0') break;
609
610       for (; *c=='0' && *(c+1)!='\0';) c++;  /* strip insignificant zeros */
611       firstexp=c;                            /* save exponent digit place */
612       for (; ;c++) {
613         if (*c<'0' || *c>'9') break;         /* not a digit */
614         exponent=X10(exponent)+(Int)*c-(Int)'0';
615         } /* c */
616       /* if not now on a '\0', *c must not be a digit */
617       if (*c!='\0') break;
618
619       /* (this next test must be after the syntax checks) */
620       /* if it was too long the exponent may have wrapped, so check */
621       /* carefully and set it to a certain overflow if wrap possible */
622       if (c>=firstexp+9+1) {
623         if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
624         /* [up to 1999999999 is OK, for example 1E-1000000998] */
625         }
626       if (nege) exponent=-exponent;     /* was negative */
627       status=0;                         /* is OK */
628       } /* stuff after digits */
629
630     /* Here when whole string has been inspected; syntax is good */
631     /* cfirst->first digit (never dot), last->last digit (ditto) */
632
633     /* strip leading zeros/dot [leave final 0 if all 0's] */
634     if (*cfirst=='0') {                 /* [cfirst has stepped over .] */
635       for (c=cfirst; c<last; c++, cfirst++) {
636         if (*c=='.') continue;          /* ignore dots */
637         if (*c!='0') break;             /* non-zero found */
638         d--;                            /* 0 stripped */
639         } /* c */
640       #if DECSUBSET
641       /* make a rapid exit for easy zeros if !extended */
642       if (*cfirst=='0' && !set->extended) {
643         decNumberZero(dn);              /* clean result */
644         break;                          /* [could be return] */
645         }
646       #endif
647       } /* at least one leading 0 */
648
649     /* Handle decimal point... */
650     if (dotchar!=NULL && dotchar<last)  /* non-trailing '.' found? */
651       exponent-=(last-dotchar);         /* adjust exponent */
652     /* [we can now ignore the .] */
653
654     /* OK, the digits string is good.  Assemble in the decNumber, or in */
655     /* a temporary units array if rounding is needed */
656     if (d<=set->digits) res=dn->lsu;    /* fits into supplied decNumber */
657      else {                             /* rounding needed */
658       Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
659       res=resbuff;                      /* assume use local buffer */
660       if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
661         allocres=(Unit *)malloc(needbytes);
662         if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
663         res=allocres;
664         }
665       }
666     /* res now -> number lsu, buffer, or allocated storage for Unit array */
667
668     /* Place the coefficient into the selected Unit array */
669     /* [this is often 70% of the cost of this function when DECDPUN>1] */
670     #if DECDPUN>1
671     out=0;                         /* accumulator */
672     up=res+D2U(d)-1;               /* -> msu */
673     cut=d-(up-res)*DECDPUN;        /* digits in top unit */
674     for (c=cfirst;; c++) {         /* along the digits */
675       if (*c=='.') continue;       /* ignore '.' [don't decrement cut] */
676       out=X10(out)+(Int)*c-(Int)'0';
677       if (c==last) break;          /* done [never get to trailing '.'] */
678       cut--;
679       if (cut>0) continue;         /* more for this unit */
680       *up=(Unit)out;               /* write unit */
681       up--;                        /* prepare for unit below.. */
682       cut=DECDPUN;                 /* .. */
683       out=0;                       /* .. */
684       } /* c */
685     *up=(Unit)out;                 /* write lsu */
686
687     #else
688     /* DECDPUN==1 */
689     up=res;                        /* -> lsu */
690     for (c=last; c>=cfirst; c--) { /* over each character, from least */
691       if (*c=='.') continue;       /* ignore . [don't step up] */
692       *up=(Unit)((Int)*c-(Int)'0');
693       up++;
694       } /* c */
695     #endif
696
697     dn->bits=bits;
698     dn->exponent=exponent;
699     dn->digits=d;
700
701     /* if not in number (too long) shorten into the number */
702     if (d>set->digits) {
703       residue=0;
704       decSetCoeff(dn, set, res, d, &residue, &status);
705       /* always check for overflow or subnormal and round as needed */
706       decFinalize(dn, set, &residue, &status);
707       }
708      else { /* no rounding, but may still have overflow or subnormal */
709       /* [these tests are just for performance; finalize repeats them] */
710       if ((dn->exponent-1<set->emin-dn->digits)
711        || (dn->exponent-1>set->emax-set->digits)) {
712         residue=0;
713         decFinalize(dn, set, &residue, &status);
714         }
715       }
716     /* decNumberShow(dn); */
717     } while(0);                         /* [for break] */
718
719   if (allocres!=NULL) free(allocres);   /* drop any storage used */
720   if (status!=0) decStatus(dn, status, set);
721   return dn;
722   } /* decNumberFromString */
723
724 /* ================================================================== */
725 /* Operators                                                          */
726 /* ================================================================== */
727
728 /* ------------------------------------------------------------------ */
729 /* decNumberAbs -- absolute value operator                            */
730 /*                                                                    */
731 /*   This computes C = abs(A)                                         */
732 /*                                                                    */
733 /*   res is C, the result.  C may be A                                */
734 /*   rhs is A                                                         */
735 /*   set is the context                                               */
736 /*                                                                    */
737 /* See also decNumberCopyAbs for a quiet bitwise version of this.     */
738 /* C must have space for set->digits digits.                          */
739 /* ------------------------------------------------------------------ */
740 /* This has the same effect as decNumberPlus unless A is negative,    */
741 /* in which case it has the same effect as decNumberMinus.            */
742 /* ------------------------------------------------------------------ */
743 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
744                          decContext *set) {
745   decNumber dzero;                      /* for 0 */
746   uInt status=0;                        /* accumulator */
747
748   #if DECCHECK
749   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
750   #endif
751
752   decNumberZero(&dzero);                /* set 0 */
753   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
754   decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
755   if (status!=0) decStatus(res, status, set);
756   #if DECCHECK
757   decCheckInexact(res, set);
758   #endif
759   return res;
760   } /* decNumberAbs */
761
762 /* ------------------------------------------------------------------ */
763 /* decNumberAdd -- add two Numbers                                    */
764 /*                                                                    */
765 /*   This computes C = A + B                                          */
766 /*                                                                    */
767 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
768 /*   lhs is A                                                         */
769 /*   rhs is B                                                         */
770 /*   set is the context                                               */
771 /*                                                                    */
772 /* C must have space for set->digits digits.                          */
773 /* ------------------------------------------------------------------ */
774 /* This just calls the routine shared with Subtract                   */
775 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
776                          const decNumber *rhs, decContext *set) {
777   uInt status=0;                        /* accumulator */
778   decAddOp(res, lhs, rhs, set, 0, &status);
779   if (status!=0) decStatus(res, status, set);
780   #if DECCHECK
781   decCheckInexact(res, set);
782   #endif
783   return res;
784   } /* decNumberAdd */
785
786 /* ------------------------------------------------------------------ */
787 /* decNumberAnd -- AND two Numbers, digitwise                         */
788 /*                                                                    */
789 /*   This computes C = A & B                                          */
790 /*                                                                    */
791 /*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
792 /*   lhs is A                                                         */
793 /*   rhs is B                                                         */
794 /*   set is the context (used for result length and error report)     */
795 /*                                                                    */
796 /* C must have space for set->digits digits.                          */
797 /*                                                                    */
798 /* Logical function restrictions apply (see above); a NaN is          */
799 /* returned with Invalid_operation if a restriction is violated.      */
800 /* ------------------------------------------------------------------ */
801 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
802                          const decNumber *rhs, decContext *set) {
803   const Unit *ua, *ub;                  /* -> operands */
804   const Unit *msua, *msub;              /* -> operand msus */
805   Unit *uc,  *msuc;                     /* -> result and its msu */
806   Int   msudigs;                        /* digits in res msu */
807   #if DECCHECK
808   if (decCheckOperands(res, lhs, rhs, set)) return res;
809   #endif
810
811   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
812    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
813     decStatus(res, DEC_Invalid_operation, set);
814     return res;
815     }
816
817   /* operands are valid */
818   ua=lhs->lsu;                          /* bottom-up */
819   ub=rhs->lsu;                          /* .. */
820   uc=res->lsu;                          /* .. */
821   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
822   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
823   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
824   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
825   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
826     Unit a, b;                          /* extract units */
827     if (ua>msua) a=0;
828      else a=*ua;
829     if (ub>msub) b=0;
830      else b=*ub;
831     *uc=0;                              /* can now write back */
832     if (a|b) {                          /* maybe 1 bits to examine */
833       Int i, j;
834       *uc=0;                            /* can now write back */
835       /* This loop could be unrolled and/or use BIN2BCD tables */
836       for (i=0; i<DECDPUN; i++) {
837         if (a&b&1) *uc=*uc+(Unit)powers[i];  /* effect AND */
838         j=a%10;
839         a=a/10;
840         j|=b%10;
841         b=b/10;
842         if (j>1) {
843           decStatus(res, DEC_Invalid_operation, set);
844           return res;
845           }
846         if (uc==msuc && i==msudigs-1) break; /* just did final digit */
847         } /* each digit */
848       } /* both OK */
849     } /* each unit */
850   /* [here uc-1 is the msu of the result] */
851   res->digits=decGetDigits(res->lsu, uc-res->lsu);
852   res->exponent=0;                      /* integer */
853   res->bits=0;                          /* sign=0 */
854   return res;  /* [no status to set] */
855   } /* decNumberAnd */
856
857 /* ------------------------------------------------------------------ */
858 /* decNumberCompare -- compare two Numbers                            */
859 /*                                                                    */
860 /*   This computes C = A ? B                                          */
861 /*                                                                    */
862 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
863 /*   lhs is A                                                         */
864 /*   rhs is B                                                         */
865 /*   set is the context                                               */
866 /*                                                                    */
867 /* C must have space for one digit (or NaN).                          */
868 /* ------------------------------------------------------------------ */
869 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
870                              const decNumber *rhs, decContext *set) {
871   uInt status=0;                        /* accumulator */
872   decCompareOp(res, lhs, rhs, set, COMPARE, &status);
873   if (status!=0) decStatus(res, status, set);
874   return res;
875   } /* decNumberCompare */
876
877 /* ------------------------------------------------------------------ */
878 /* decNumberCompareSignal -- compare, signalling on all NaNs          */
879 /*                                                                    */
880 /*   This computes C = A ? B                                          */
881 /*                                                                    */
882 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
883 /*   lhs is A                                                         */
884 /*   rhs is B                                                         */
885 /*   set is the context                                               */
886 /*                                                                    */
887 /* C must have space for one digit (or NaN).                          */
888 /* ------------------------------------------------------------------ */
889 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
890                                    const decNumber *rhs, decContext *set) {
891   uInt status=0;                        /* accumulator */
892   decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
893   if (status!=0) decStatus(res, status, set);
894   return res;
895   } /* decNumberCompareSignal */
896
897 /* ------------------------------------------------------------------ */
898 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
899 /*                                                                    */
900 /*   This computes C = A ? B, under total ordering                    */
901 /*                                                                    */
902 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
903 /*   lhs is A                                                         */
904 /*   rhs is B                                                         */
905 /*   set is the context                                               */
906 /*                                                                    */
907 /* C must have space for one digit; the result will always be one of  */
908 /* -1, 0, or 1.                                                       */
909 /* ------------------------------------------------------------------ */
910 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
911                                   const decNumber *rhs, decContext *set) {
912   uInt status=0;                        /* accumulator */
913   decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
914   if (status!=0) decStatus(res, status, set);
915   return res;
916   } /* decNumberCompareTotal */
917
918 /* ------------------------------------------------------------------ */
919 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
920 /*                                                                    */
921 /*   This computes C = |A| ? |B|, under total ordering                */
922 /*                                                                    */
923 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
924 /*   lhs is A                                                         */
925 /*   rhs is B                                                         */
926 /*   set is the context                                               */
927 /*                                                                    */
928 /* C must have space for one digit; the result will always be one of  */
929 /* -1, 0, or 1.                                                       */
930 /* ------------------------------------------------------------------ */
931 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
932                                      const decNumber *rhs, decContext *set) {
933   uInt status=0;                   /* accumulator */
934   uInt needbytes;                  /* for space calculations */
935   decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
936   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
937   decNumber bufb[D2N(DECBUFFER+1)];
938   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
939   decNumber *a, *b;                /* temporary pointers */
940
941   #if DECCHECK
942   if (decCheckOperands(res, lhs, rhs, set)) return res;
943   #endif
944
945   do {                                  /* protect allocated storage */
946     /* if either is negative, take a copy and absolute */
947     if (decNumberIsNegative(lhs)) {     /* lhs<0 */
948       a=bufa;
949       needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
950       if (needbytes>sizeof(bufa)) {     /* need malloc space */
951         allocbufa=(decNumber *)malloc(needbytes);
952         if (allocbufa==NULL) {          /* hopeless -- abandon */
953           status|=DEC_Insufficient_storage;
954           break;}
955         a=allocbufa;                    /* use the allocated space */
956         }
957       decNumberCopy(a, lhs);            /* copy content */
958       a->bits&=~DECNEG;                 /* .. and clear the sign */
959       lhs=a;                            /* use copy from here on */
960       }
961     if (decNumberIsNegative(rhs)) {     /* rhs<0 */
962       b=bufb;
963       needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
964       if (needbytes>sizeof(bufb)) {     /* need malloc space */
965         allocbufb=(decNumber *)malloc(needbytes);
966         if (allocbufb==NULL) {          /* hopeless -- abandon */
967           status|=DEC_Insufficient_storage;
968           break;}
969         b=allocbufb;                    /* use the allocated space */
970         }
971       decNumberCopy(b, rhs);            /* copy content */
972       b->bits&=~DECNEG;                 /* .. and clear the sign */
973       rhs=b;                            /* use copy from here on */
974       }
975     decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
976     } while(0);                         /* end protected */
977
978   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
979   if (allocbufb!=NULL) free(allocbufb); /* .. */
980   if (status!=0) decStatus(res, status, set);
981   return res;
982   } /* decNumberCompareTotalMag */
983
984 /* ------------------------------------------------------------------ */
985 /* decNumberDivide -- divide one number by another                    */
986 /*                                                                    */
987 /*   This computes C = A / B                                          */
988 /*                                                                    */
989 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
990 /*   lhs is A                                                         */
991 /*   rhs is B                                                         */
992 /*   set is the context                                               */
993 /*                                                                    */
994 /* C must have space for set->digits digits.                          */
995 /* ------------------------------------------------------------------ */
996 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
997                             const decNumber *rhs, decContext *set) {
998   uInt status=0;                        /* accumulator */
999   decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1000   if (status!=0) decStatus(res, status, set);
1001   #if DECCHECK
1002   decCheckInexact(res, set);
1003   #endif
1004   return res;
1005   } /* decNumberDivide */
1006
1007 /* ------------------------------------------------------------------ */
1008 /* decNumberDivideInteger -- divide and return integer quotient       */
1009 /*                                                                    */
1010 /*   This computes C = A # B, where # is the integer divide operator  */
1011 /*                                                                    */
1012 /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1013 /*   lhs is A                                                         */
1014 /*   rhs is B                                                         */
1015 /*   set is the context                                               */
1016 /*                                                                    */
1017 /* C must have space for set->digits digits.                          */
1018 /* ------------------------------------------------------------------ */
1019 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1020                                    const decNumber *rhs, decContext *set) {
1021   uInt status=0;                        /* accumulator */
1022   decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1023   if (status!=0) decStatus(res, status, set);
1024   return res;
1025   } /* decNumberDivideInteger */
1026
1027 /* ------------------------------------------------------------------ */
1028 /* decNumberExp -- exponentiation                                     */
1029 /*                                                                    */
1030 /*   This computes C = exp(A)                                         */
1031 /*                                                                    */
1032 /*   res is C, the result.  C may be A                                */
1033 /*   rhs is A                                                         */
1034 /*   set is the context; note that rounding mode has no effect        */
1035 /*                                                                    */
1036 /* C must have space for set->digits digits.                          */
1037 /*                                                                    */
1038 /* Mathematical function restrictions apply (see above); a NaN is     */
1039 /* returned with Invalid_operation if a restriction is violated.      */
1040 /*                                                                    */
1041 /* Finite results will always be full precision and Inexact, except   */
1042 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1043 /*                                                                    */
1044 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1045 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1046 /* error in rare cases.                                               */
1047 /* ------------------------------------------------------------------ */
1048 /* This is a wrapper for decExpOp which can handle the slightly wider */
1049 /* (double) range needed by Ln (which has to be able to calculate     */
1050 /* exp(-a) where a can be the tiniest number (Ntiny).                 */
1051 /* ------------------------------------------------------------------ */
1052 decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1053                          decContext *set) {
1054   uInt status=0;                        /* accumulator */
1055   #if DECSUBSET
1056   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1057   #endif
1058
1059   #if DECCHECK
1060   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1061   #endif
1062
1063   /* Check restrictions; these restrictions ensure that if h=8 (see */
1064   /* decExpOp) then the result will either overflow or underflow to 0. */
1065   /* Other math functions restrict the input range, too, for inverses. */
1066   /* If not violated then carry out the operation. */
1067   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1068     #if DECSUBSET
1069     if (!set->extended) {
1070       /* reduce operand and set lostDigits status, as needed */
1071       if (rhs->digits>set->digits) {
1072         allocrhs=decRoundOperand(rhs, set, &status);
1073         if (allocrhs==NULL) break;
1074         rhs=allocrhs;
1075         }
1076       }
1077     #endif
1078     decExpOp(res, rhs, set, &status);
1079     } while(0);                         /* end protected */
1080
1081   #if DECSUBSET
1082   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
1083   #endif
1084   /* apply significant status */
1085   if (status!=0) decStatus(res, status, set);
1086   #if DECCHECK
1087   decCheckInexact(res, set);
1088   #endif
1089   return res;
1090   } /* decNumberExp */
1091
1092 /* ------------------------------------------------------------------ */
1093 /* decNumberFMA -- fused multiply add                                 */
1094 /*                                                                    */
1095 /*   This computes D = (A * B) + C with only one rounding             */
1096 /*                                                                    */
1097 /*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1098 /*   lhs is A                                                         */
1099 /*   rhs is B                                                         */
1100 /*   fhs is C [far hand side]                                         */
1101 /*   set is the context                                               */
1102 /*                                                                    */
1103 /* Mathematical function restrictions apply (see above); a NaN is     */
1104 /* returned with Invalid_operation if a restriction is violated.      */
1105 /*                                                                    */
1106 /* C must have space for set->digits digits.                          */
1107 /* ------------------------------------------------------------------ */
1108 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1109                          const decNumber *rhs, const decNumber *fhs,
1110                          decContext *set) {
1111   uInt status=0;                   /* accumulator */
1112   decContext dcmul;                /* context for the multiplication */
1113   uInt needbytes;                  /* for space calculations */
1114   decNumber bufa[D2N(DECBUFFER*2+1)];
1115   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
1116   decNumber *acc;                  /* accumulator pointer */
1117   decNumber dzero;                 /* work */
1118
1119   #if DECCHECK
1120   if (decCheckOperands(res, lhs, rhs, set)) return res;
1121   if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1122   #endif
1123
1124   do {                                  /* protect allocated storage */
1125     #if DECSUBSET
1126     if (!set->extended) {               /* [undefined if subset] */
1127       status|=DEC_Invalid_operation;
1128       break;}
1129     #endif
1130     /* Check math restrictions [these ensure no overflow or underflow] */
1131     if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1132      || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1133      || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1134     /* set up context for multiply */
1135     dcmul=*set;
1136     dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1137     /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1138     dcmul.emax=DEC_MAX_EMAX;            /* effectively unbounded .. */
1139     dcmul.emin=DEC_MIN_EMIN;            /* [thanks to Math restrictions] */
1140     /* set up decNumber space to receive the result of the multiply */
1141     acc=bufa;                           /* may fit */
1142     needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1143     if (needbytes>sizeof(bufa)) {       /* need malloc space */
1144       allocbufa=(decNumber *)malloc(needbytes);
1145       if (allocbufa==NULL) {            /* hopeless -- abandon */
1146         status|=DEC_Insufficient_storage;
1147         break;}
1148       acc=allocbufa;                    /* use the allocated space */
1149       }
1150     /* multiply with extended range and necessary precision */
1151     /*printf("emin=%ld\n", dcmul.emin); */
1152     decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1153     /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1154     /* status; if either is seen than ignore fhs (in case it is */
1155     /* another sNaN) and set acc to NaN unless we had an sNaN */
1156     /* [decMultiplyOp leaves that to caller] */
1157     /* Note sNaN has to go through addOp to shorten payload if */
1158     /* necessary */
1159     if ((status&DEC_Invalid_operation)!=0) {
1160       if (!(status&DEC_sNaN)) {         /* but be true invalid */
1161         decNumberZero(res);             /* acc not yet set */
1162         res->bits=DECNAN;
1163         break;
1164         }
1165       decNumberZero(&dzero);            /* make 0 (any non-NaN would do) */
1166       fhs=&dzero;                       /* use that */
1167       }
1168     #if DECCHECK
1169      else { /* multiply was OK */
1170       if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1171       }
1172     #endif
1173     /* add the third operand and result -> res, and all is done */
1174     decAddOp(res, acc, fhs, set, 0, &status);
1175     } while(0);                         /* end protected */
1176
1177   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1178   if (status!=0) decStatus(res, status, set);
1179   #if DECCHECK
1180   decCheckInexact(res, set);
1181   #endif
1182   return res;
1183   } /* decNumberFMA */
1184
1185 /* ------------------------------------------------------------------ */
1186 /* decNumberInvert -- invert a Number, digitwise                      */
1187 /*                                                                    */
1188 /*   This computes C = ~A                                             */
1189 /*                                                                    */
1190 /*   res is C, the result.  C may be A (e.g., X=~X)                   */
1191 /*   rhs is A                                                         */
1192 /*   set is the context (used for result length and error report)     */
1193 /*                                                                    */
1194 /* C must have space for set->digits digits.                          */
1195 /*                                                                    */
1196 /* Logical function restrictions apply (see above); a NaN is          */
1197 /* returned with Invalid_operation if a restriction is violated.      */
1198 /* ------------------------------------------------------------------ */
1199 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1200                             decContext *set) {
1201   const Unit *ua, *msua;                /* -> operand and its msu */
1202   Unit  *uc, *msuc;                     /* -> result and its msu */
1203   Int   msudigs;                        /* digits in res msu */
1204   #if DECCHECK
1205   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1206   #endif
1207
1208   if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1209     decStatus(res, DEC_Invalid_operation, set);
1210     return res;
1211     }
1212   /* operand is valid */
1213   ua=rhs->lsu;                          /* bottom-up */
1214   uc=res->lsu;                          /* .. */
1215   msua=ua+D2U(rhs->digits)-1;           /* -> msu of rhs */
1216   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
1217   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
1218   for (; uc<=msuc; ua++, uc++) {        /* Unit loop */
1219     Unit a;                             /* extract unit */
1220     Int  i, j;                          /* work */
1221     if (ua>msua) a=0;
1222      else a=*ua;
1223     *uc=0;                              /* can now write back */
1224     /* always need to examine all bits in rhs */
1225     /* This loop could be unrolled and/or use BIN2BCD tables */
1226     for (i=0; i<DECDPUN; i++) {
1227       if ((~a)&1) *uc=*uc+(Unit)powers[i];   /* effect INVERT */
1228       j=a%10;
1229       a=a/10;
1230       if (j>1) {
1231         decStatus(res, DEC_Invalid_operation, set);
1232         return res;
1233         }
1234       if (uc==msuc && i==msudigs-1) break;   /* just did final digit */
1235       } /* each digit */
1236     } /* each unit */
1237   /* [here uc-1 is the msu of the result] */
1238   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1239   res->exponent=0;                      /* integer */
1240   res->bits=0;                          /* sign=0 */
1241   return res;  /* [no status to set] */
1242   } /* decNumberInvert */
1243
1244 /* ------------------------------------------------------------------ */
1245 /* decNumberLn -- natural logarithm                                   */
1246 /*                                                                    */
1247 /*   This computes C = ln(A)                                          */
1248 /*                                                                    */
1249 /*   res is C, the result.  C may be A                                */
1250 /*   rhs is A                                                         */
1251 /*   set is the context; note that rounding mode has no effect        */
1252 /*                                                                    */
1253 /* C must have space for set->digits digits.                          */
1254 /*                                                                    */
1255 /* Notable cases:                                                     */
1256 /*   A<0 -> Invalid                                                   */
1257 /*   A=0 -> -Infinity (Exact)                                         */
1258 /*   A=+Infinity -> +Infinity (Exact)                                 */
1259 /*   A=1 exactly -> 0 (Exact)                                         */
1260 /*                                                                    */
1261 /* Mathematical function restrictions apply (see above); a NaN is     */
1262 /* returned with Invalid_operation if a restriction is violated.      */
1263 /*                                                                    */
1264 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1265 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1266 /* error in rare cases.                                               */
1267 /* ------------------------------------------------------------------ */
1268 /* This is a wrapper for decLnOp which can handle the slightly wider  */
1269 /* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1270 /* to calculate at p+e+2).                                            */
1271 /* ------------------------------------------------------------------ */
1272 decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1273                         decContext *set) {
1274   uInt status=0;                   /* accumulator */
1275   #if DECSUBSET
1276   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1277   #endif
1278
1279   #if DECCHECK
1280   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1281   #endif
1282
1283   /* Check restrictions; this is a math function; if not violated */
1284   /* then carry out the operation. */
1285   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1286     #if DECSUBSET
1287     if (!set->extended) {
1288       /* reduce operand and set lostDigits status, as needed */
1289       if (rhs->digits>set->digits) {
1290         allocrhs=decRoundOperand(rhs, set, &status);
1291         if (allocrhs==NULL) break;
1292         rhs=allocrhs;
1293         }
1294       /* special check in subset for rhs=0 */
1295       if (ISZERO(rhs)) {                /* +/- zeros -> error */
1296         status|=DEC_Invalid_operation;
1297         break;}
1298       } /* extended=0 */
1299     #endif
1300     decLnOp(res, rhs, set, &status);
1301     } while(0);                         /* end protected */
1302
1303   #if DECSUBSET
1304   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
1305   #endif
1306   /* apply significant status */
1307   if (status!=0) decStatus(res, status, set);
1308   #if DECCHECK
1309   decCheckInexact(res, set);
1310   #endif
1311   return res;
1312   } /* decNumberLn */
1313
1314 /* ------------------------------------------------------------------ */
1315 /* decNumberLogB - get adjusted exponent, by 754 rules                */
1316 /*                                                                    */
1317 /*   This computes C = adjustedexponent(A)                            */
1318 /*                                                                    */
1319 /*   res is C, the result.  C may be A                                */
1320 /*   rhs is A                                                         */
1321 /*   set is the context, used only for digits and status              */
1322 /*                                                                    */
1323 /* C must have space for 10 digits (A might have 10**9 digits and     */
1324 /* an exponent of +999999999, or one digit and an exponent of         */
1325 /* -1999999999).                                                      */
1326 /*                                                                    */
1327 /* This returns the adjusted exponent of A after (in theory) padding  */
1328 /* with zeros on the right to set->digits digits while keeping the    */
1329 /* same value.  The exponent is not limited by emin/emax.             */
1330 /*                                                                    */
1331 /* Notable cases:                                                     */
1332 /*   A<0 -> Use |A|                                                   */
1333 /*   A=0 -> -Infinity (Division by zero)                              */
1334 /*   A=Infinite -> +Infinity (Exact)                                  */
1335 /*   A=1 exactly -> 0 (Exact)                                         */
1336 /*   NaNs are propagated as usual                                     */
1337 /* ------------------------------------------------------------------ */
1338 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1339                           decContext *set) {
1340   uInt status=0;                   /* accumulator */
1341
1342   #if DECCHECK
1343   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1344   #endif
1345
1346   /* NaNs as usual; Infinities return +Infinity; 0->oops */
1347   if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1348    else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1349    else if (decNumberIsZero(rhs)) {
1350     decNumberZero(res);                 /* prepare for Infinity */
1351     res->bits=DECNEG|DECINF;            /* -Infinity */
1352     status|=DEC_Division_by_zero;       /* as per 754 */
1353     }
1354    else { /* finite non-zero */
1355     Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1356     decNumberFromInt32(res, ae);        /* lay it out */
1357     }
1358
1359   if (status!=0) decStatus(res, status, set);
1360   return res;
1361   } /* decNumberLogB */
1362
1363 /* ------------------------------------------------------------------ */
1364 /* decNumberLog10 -- logarithm in base 10                             */
1365 /*                                                                    */
1366 /*   This computes C = log10(A)                                       */
1367 /*                                                                    */
1368 /*   res is C, the result.  C may be A                                */
1369 /*   rhs is A                                                         */
1370 /*   set is the context; note that rounding mode has no effect        */
1371 /*                                                                    */
1372 /* C must have space for set->digits digits.                          */
1373 /*                                                                    */
1374 /* Notable cases:                                                     */
1375 /*   A<0 -> Invalid                                                   */
1376 /*   A=0 -> -Infinity (Exact)                                         */
1377 /*   A=+Infinity -> +Infinity (Exact)                                 */
1378 /*   A=10**n (if n is an integer) -> n (Exact)                        */
1379 /*                                                                    */
1380 /* Mathematical function restrictions apply (see above); a NaN is     */
1381 /* returned with Invalid_operation if a restriction is violated.      */
1382 /*                                                                    */
1383 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1384 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1385 /* error in rare cases.                                               */
1386 /* ------------------------------------------------------------------ */
1387 /* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1388 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1389 /* requested digits and t is the number of digits in the exponent     */
1390 /* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1391 /* fastpath in decLnOp.  The final division is done to the requested  */
1392 /* precision.                                                         */
1393 /* ------------------------------------------------------------------ */
1394 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1395                           decContext *set) {
1396   uInt status=0, ignore=0;         /* status accumulators */
1397   uInt needbytes;                  /* for space calculations */
1398   Int p;                           /* working precision */
1399   Int t;                           /* digits in exponent of A */
1400
1401   /* buffers for a and b working decimals */
1402   /* (adjustment calculator, same size) */
1403   decNumber bufa[D2N(DECBUFFER+2)];
1404   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
1405   decNumber *a=bufa;               /* temporary a */
1406   decNumber bufb[D2N(DECBUFFER+2)];
1407   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
1408   decNumber *b=bufb;               /* temporary b */
1409   decNumber bufw[D2N(10)];         /* working 2-10 digit number */
1410   decNumber *w=bufw;               /* .. */
1411   #if DECSUBSET
1412   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1413   #endif
1414
1415   decContext aset;                 /* working context */
1416
1417   #if DECCHECK
1418   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1419   #endif
1420
1421   /* Check restrictions; this is a math function; if not violated */
1422   /* then carry out the operation. */
1423   if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1424     #if DECSUBSET
1425     if (!set->extended) {
1426       /* reduce operand and set lostDigits status, as needed */
1427       if (rhs->digits>set->digits) {
1428         allocrhs=decRoundOperand(rhs, set, &status);
1429         if (allocrhs==NULL) break;
1430         rhs=allocrhs;
1431         }
1432       /* special check in subset for rhs=0 */
1433       if (ISZERO(rhs)) {                /* +/- zeros -> error */
1434         status|=DEC_Invalid_operation;
1435         break;}
1436       } /* extended=0 */
1437     #endif
1438
1439     decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1440
1441     /* handle exact powers of 10; only check if +ve finite */
1442     if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1443       Int residue=0;               /* (no residue) */
1444       uInt copystat=0;             /* clean status */
1445
1446       /* round to a single digit... */
1447       aset.digits=1;
1448       decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1449       /* if exact and the digit is 1, rhs is a power of 10 */
1450       if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1451         /* the exponent, conveniently, is the power of 10; making */
1452         /* this the result needs a little care as it might not fit, */
1453         /* so first convert it into the working number, and then move */
1454         /* to res */
1455         decNumberFromInt32(w, w->exponent);
1456         residue=0;
1457         decCopyFit(res, w, set, &residue, &status); /* copy & round */
1458         decFinish(res, set, &residue, &status);     /* cleanup/set flags */
1459         break;
1460         } /* not a power of 10 */
1461       } /* not a candidate for exact */
1462
1463     /* simplify the information-content calculation to use 'total */
1464     /* number of digits in a, including exponent' as compared to the */
1465     /* requested digits, as increasing this will only rarely cost an */
1466     /* iteration in ln(a) anyway */
1467     t=6;                                /* it can never be >6 */
1468
1469     /* allocate space when needed... */
1470     p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1471     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1472     if (needbytes>sizeof(bufa)) {       /* need malloc space */
1473       allocbufa=(decNumber *)malloc(needbytes);
1474       if (allocbufa==NULL) {            /* hopeless -- abandon */
1475         status|=DEC_Insufficient_storage;
1476         break;}
1477       a=allocbufa;                      /* use the allocated space */
1478       }
1479     aset.digits=p;                      /* as calculated */
1480     aset.emax=DEC_MAX_MATH;             /* usual bounds */
1481     aset.emin=-DEC_MAX_MATH;            /* .. */
1482     aset.clamp=0;                       /* and no concrete format */
1483     decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs) */
1484
1485     /* skip the division if the result so far is infinite, NaN, or */
1486     /* zero, or there was an error; note NaN from sNaN needs copy */
1487     if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1488     if (a->bits&DECSPECIAL || ISZERO(a)) {
1489       decNumberCopy(res, a);            /* [will fit] */
1490       break;}
1491
1492     /* for ln(10) an extra 3 digits of precision are needed */
1493     p=set->digits+3;
1494     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1495     if (needbytes>sizeof(bufb)) {       /* need malloc space */
1496       allocbufb=(decNumber *)malloc(needbytes);
1497       if (allocbufb==NULL) {            /* hopeless -- abandon */
1498         status|=DEC_Insufficient_storage;
1499         break;}
1500       b=allocbufb;                      /* use the allocated space */
1501       }
1502     decNumberZero(w);                   /* set up 10... */
1503     #if DECDPUN==1
1504     w->lsu[1]=1; w->lsu[0]=0;           /* .. */
1505     #else
1506     w->lsu[0]=10;                       /* .. */
1507     #endif
1508     w->digits=2;                        /* .. */
1509
1510     aset.digits=p;
1511     decLnOp(b, w, &aset, &ignore);      /* b=ln(10) */
1512
1513     aset.digits=set->digits;            /* for final divide */
1514     decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1515     } while(0);                         /* [for break] */
1516
1517   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1518   if (allocbufb!=NULL) free(allocbufb); /* .. */
1519   #if DECSUBSET
1520   if (allocrhs !=NULL) free(allocrhs);  /* .. */
1521   #endif
1522   /* apply significant status */
1523   if (status!=0) decStatus(res, status, set);
1524   #if DECCHECK
1525   decCheckInexact(res, set);
1526   #endif
1527   return res;
1528   } /* decNumberLog10 */
1529
1530 /* ------------------------------------------------------------------ */
1531 /* decNumberMax -- compare two Numbers and return the maximum         */
1532 /*                                                                    */
1533 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1534 /*                                                                    */
1535 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1536 /*   lhs is A                                                         */
1537 /*   rhs is B                                                         */
1538 /*   set is the context                                               */
1539 /*                                                                    */
1540 /* C must have space for set->digits digits.                          */
1541 /* ------------------------------------------------------------------ */
1542 decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1543                          const decNumber *rhs, decContext *set) {
1544   uInt status=0;                        /* accumulator */
1545   decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1546   if (status!=0) decStatus(res, status, set);
1547   #if DECCHECK
1548   decCheckInexact(res, set);
1549   #endif
1550   return res;
1551   } /* decNumberMax */
1552
1553 /* ------------------------------------------------------------------ */
1554 /* decNumberMaxMag -- compare and return the maximum by magnitude     */
1555 /*                                                                    */
1556 /*   This computes C = A ? B, returning the maximum by 754 rules      */
1557 /*                                                                    */
1558 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1559 /*   lhs is A                                                         */
1560 /*   rhs is B                                                         */
1561 /*   set is the context                                               */
1562 /*                                                                    */
1563 /* C must have space for set->digits digits.                          */
1564 /* ------------------------------------------------------------------ */
1565 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1566                          const decNumber *rhs, decContext *set) {
1567   uInt status=0;                        /* accumulator */
1568   decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1569   if (status!=0) decStatus(res, status, set);
1570   #if DECCHECK
1571   decCheckInexact(res, set);
1572   #endif
1573   return res;
1574   } /* decNumberMaxMag */
1575
1576 /* ------------------------------------------------------------------ */
1577 /* decNumberMin -- compare two Numbers and return the minimum         */
1578 /*                                                                    */
1579 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1580 /*                                                                    */
1581 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1582 /*   lhs is A                                                         */
1583 /*   rhs is B                                                         */
1584 /*   set is the context                                               */
1585 /*                                                                    */
1586 /* C must have space for set->digits digits.                          */
1587 /* ------------------------------------------------------------------ */
1588 decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1589                          const decNumber *rhs, decContext *set) {
1590   uInt status=0;                        /* accumulator */
1591   decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1592   if (status!=0) decStatus(res, status, set);
1593   #if DECCHECK
1594   decCheckInexact(res, set);
1595   #endif
1596   return res;
1597   } /* decNumberMin */
1598
1599 /* ------------------------------------------------------------------ */
1600 /* decNumberMinMag -- compare and return the minimum by magnitude     */
1601 /*                                                                    */
1602 /*   This computes C = A ? B, returning the minimum by 754 rules      */
1603 /*                                                                    */
1604 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1605 /*   lhs is A                                                         */
1606 /*   rhs is B                                                         */
1607 /*   set is the context                                               */
1608 /*                                                                    */
1609 /* C must have space for set->digits digits.                          */
1610 /* ------------------------------------------------------------------ */
1611 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1612                          const decNumber *rhs, decContext *set) {
1613   uInt status=0;                        /* accumulator */
1614   decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1615   if (status!=0) decStatus(res, status, set);
1616   #if DECCHECK
1617   decCheckInexact(res, set);
1618   #endif
1619   return res;
1620   } /* decNumberMinMag */
1621
1622 /* ------------------------------------------------------------------ */
1623 /* decNumberMinus -- prefix minus operator                            */
1624 /*                                                                    */
1625 /*   This computes C = 0 - A                                          */
1626 /*                                                                    */
1627 /*   res is C, the result.  C may be A                                */
1628 /*   rhs is A                                                         */
1629 /*   set is the context                                               */
1630 /*                                                                    */
1631 /* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1632 /* C must have space for set->digits digits.                          */
1633 /* ------------------------------------------------------------------ */
1634 /* Simply use AddOp for the subtract, which will do the necessary.    */
1635 /* ------------------------------------------------------------------ */
1636 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1637                            decContext *set) {
1638   decNumber dzero;
1639   uInt status=0;                        /* accumulator */
1640
1641   #if DECCHECK
1642   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1643   #endif
1644
1645   decNumberZero(&dzero);                /* make 0 */
1646   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
1647   decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1648   if (status!=0) decStatus(res, status, set);
1649   #if DECCHECK
1650   decCheckInexact(res, set);
1651   #endif
1652   return res;
1653   } /* decNumberMinus */
1654
1655 /* ------------------------------------------------------------------ */
1656 /* decNumberNextMinus -- next towards -Infinity                       */
1657 /*                                                                    */
1658 /*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1659 /*                                                                    */
1660 /*   res is C, the result.  C may be A                                */
1661 /*   rhs is A                                                         */
1662 /*   set is the context                                               */
1663 /*                                                                    */
1664 /* This is a generalization of 754 NextDown.                          */
1665 /* ------------------------------------------------------------------ */
1666 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1667                                decContext *set) {
1668   decNumber dtiny;                           /* constant */
1669   decContext workset=*set;                   /* work */
1670   uInt status=0;                             /* accumulator */
1671   #if DECCHECK
1672   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1673   #endif
1674
1675   /* +Infinity is the special case */
1676   if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1677     decSetMaxValue(res, set);                /* is +ve */
1678     /* there is no status to set */
1679     return res;
1680     }
1681   decNumberZero(&dtiny);                     /* start with 0 */
1682   dtiny.lsu[0]=1;                            /* make number that is .. */
1683   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest */
1684   workset.round=DEC_ROUND_FLOOR;
1685   decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1686   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please */
1687   if (status!=0) decStatus(res, status, set);
1688   return res;
1689   } /* decNumberNextMinus */
1690
1691 /* ------------------------------------------------------------------ */
1692 /* decNumberNextPlus -- next towards +Infinity                        */
1693 /*                                                                    */
1694 /*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1695 /*                                                                    */
1696 /*   res is C, the result.  C may be A                                */
1697 /*   rhs is A                                                         */
1698 /*   set is the context                                               */
1699 /*                                                                    */
1700 /* This is a generalization of 754 NextUp.                            */
1701 /* ------------------------------------------------------------------ */
1702 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1703                               decContext *set) {
1704   decNumber dtiny;                           /* constant */
1705   decContext workset=*set;                   /* work */
1706   uInt status=0;                             /* accumulator */
1707   #if DECCHECK
1708   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1709   #endif
1710
1711   /* -Infinity is the special case */
1712   if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1713     decSetMaxValue(res, set);
1714     res->bits=DECNEG;                        /* negative */
1715     /* there is no status to set */
1716     return res;
1717     }
1718   decNumberZero(&dtiny);                     /* start with 0 */
1719   dtiny.lsu[0]=1;                            /* make number that is .. */
1720   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest */
1721   workset.round=DEC_ROUND_CEILING;
1722   decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1723   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please */
1724   if (status!=0) decStatus(res, status, set);
1725   return res;
1726   } /* decNumberNextPlus */
1727
1728 /* ------------------------------------------------------------------ */
1729 /* decNumberNextToward -- next towards rhs                            */
1730 /*                                                                    */
1731 /*   This computes C = A +/- infinitesimal, rounded towards           */
1732 /*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1733 /*   modified during revision but dropped from 754-2008.              */
1734 /*                                                                    */
1735 /*   res is C, the result.  C may be A or B.                          */
1736 /*   lhs is A                                                         */
1737 /*   rhs is B                                                         */
1738 /*   set is the context                                               */
1739 /*                                                                    */
1740 /* This is a generalization of 754-1985 NextAfter.                    */
1741 /* ------------------------------------------------------------------ */
1742 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1743                                 const decNumber *rhs, decContext *set) {
1744   decNumber dtiny;                           /* constant */
1745   decContext workset=*set;                   /* work */
1746   Int result;                                /* .. */
1747   uInt status=0;                             /* accumulator */
1748   #if DECCHECK
1749   if (decCheckOperands(res, lhs, rhs, set)) return res;
1750   #endif
1751
1752   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1753     decNaNs(res, lhs, rhs, set, &status);
1754     }
1755    else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1756     result=decCompare(lhs, rhs, 0);     /* sign matters */
1757     if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1758      else { /* valid compare */
1759       if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */
1760        else { /* differ: need NextPlus or NextMinus */
1761         uByte sub;                      /* add or subtract */
1762         if (result<0) {                 /* lhs<rhs, do nextplus */
1763           /* -Infinity is the special case */
1764           if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1765             decSetMaxValue(res, set);
1766             res->bits=DECNEG;           /* negative */
1767             return res;                 /* there is no status to set */
1768             }
1769           workset.round=DEC_ROUND_CEILING;
1770           sub=0;                        /* add, please */
1771           } /* plus */
1772          else {                         /* lhs>rhs, do nextminus */
1773           /* +Infinity is the special case */
1774           if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1775             decSetMaxValue(res, set);
1776             return res;                 /* there is no status to set */
1777             }
1778           workset.round=DEC_ROUND_FLOOR;
1779           sub=DECNEG;                   /* subtract, please */
1780           } /* minus */
1781         decNumberZero(&dtiny);          /* start with 0 */
1782         dtiny.lsu[0]=1;                 /* make number that is .. */
1783         dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest */
1784         decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1785         /* turn off exceptions if the result is a normal number */
1786         /* (including Nmin), otherwise let all status through */
1787         if (decNumberIsNormal(res, set)) status=0;
1788         } /* unequal */
1789       } /* compare OK */
1790     } /* numeric */
1791   if (status!=0) decStatus(res, status, set);
1792   return res;
1793   } /* decNumberNextToward */
1794
1795 /* ------------------------------------------------------------------ */
1796 /* decNumberOr -- OR two Numbers, digitwise                           */
1797 /*                                                                    */
1798 /*   This computes C = A | B                                          */
1799 /*                                                                    */
1800 /*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1801 /*   lhs is A                                                         */
1802 /*   rhs is B                                                         */
1803 /*   set is the context (used for result length and error report)     */
1804 /*                                                                    */
1805 /* C must have space for set->digits digits.                          */
1806 /*                                                                    */
1807 /* Logical function restrictions apply (see above); a NaN is          */
1808 /* returned with Invalid_operation if a restriction is violated.      */
1809 /* ------------------------------------------------------------------ */
1810 decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1811                         const decNumber *rhs, decContext *set) {
1812   const Unit *ua, *ub;                  /* -> operands */
1813   const Unit *msua, *msub;              /* -> operand msus */
1814   Unit  *uc, *msuc;                     /* -> result and its msu */
1815   Int   msudigs;                        /* digits in res msu */
1816   #if DECCHECK
1817   if (decCheckOperands(res, lhs, rhs, set)) return res;
1818   #endif
1819
1820   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1821    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1822     decStatus(res, DEC_Invalid_operation, set);
1823     return res;
1824     }
1825   /* operands are valid */
1826   ua=lhs->lsu;                          /* bottom-up */
1827   ub=rhs->lsu;                          /* .. */
1828   uc=res->lsu;                          /* .. */
1829   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
1830   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
1831   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
1832   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
1833   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
1834     Unit a, b;                          /* extract units */
1835     if (ua>msua) a=0;
1836      else a=*ua;
1837     if (ub>msub) b=0;
1838      else b=*ub;
1839     *uc=0;                              /* can now write back */
1840     if (a|b) {                          /* maybe 1 bits to examine */
1841       Int i, j;
1842       /* This loop could be unrolled and/or use BIN2BCD tables */
1843       for (i=0; i<DECDPUN; i++) {
1844         if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR */
1845         j=a%10;
1846         a=a/10;
1847         j|=b%10;
1848         b=b/10;
1849         if (j>1) {
1850           decStatus(res, DEC_Invalid_operation, set);
1851           return res;
1852           }
1853         if (uc==msuc && i==msudigs-1) break;      /* just did final digit */
1854         } /* each digit */
1855       } /* non-zero */
1856     } /* each unit */
1857   /* [here uc-1 is the msu of the result] */
1858   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1859   res->exponent=0;                      /* integer */
1860   res->bits=0;                          /* sign=0 */
1861   return res;  /* [no status to set] */
1862   } /* decNumberOr */
1863
1864 /* ------------------------------------------------------------------ */
1865 /* decNumberPlus -- prefix plus operator                              */
1866 /*                                                                    */
1867 /*   This computes C = 0 + A                                          */
1868 /*                                                                    */
1869 /*   res is C, the result.  C may be A                                */
1870 /*   rhs is A                                                         */
1871 /*   set is the context                                               */
1872 /*                                                                    */
1873 /* See also decNumberCopy for a quiet bitwise version of this.        */
1874 /* C must have space for set->digits digits.                          */
1875 /* ------------------------------------------------------------------ */
1876 /* This simply uses AddOp; Add will take fast path after preparing A. */
1877 /* Performance is a concern here, as this routine is often used to    */
1878 /* check operands and apply rounding and overflow/underflow testing.  */
1879 /* ------------------------------------------------------------------ */
1880 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1881                           decContext *set) {
1882   decNumber dzero;
1883   uInt status=0;                        /* accumulator */
1884   #if DECCHECK
1885   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1886   #endif
1887
1888   decNumberZero(&dzero);                /* make 0 */
1889   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
1890   decAddOp(res, &dzero, rhs, set, 0, &status);
1891   if (status!=0) decStatus(res, status, set);
1892   #if DECCHECK
1893   decCheckInexact(res, set);
1894   #endif
1895   return res;
1896   } /* decNumberPlus */
1897
1898 /* ------------------------------------------------------------------ */
1899 /* decNumberMultiply -- multiply two Numbers                          */
1900 /*                                                                    */
1901 /*   This computes C = A x B                                          */
1902 /*                                                                    */
1903 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1904 /*   lhs is A                                                         */
1905 /*   rhs is B                                                         */
1906 /*   set is the context                                               */
1907 /*                                                                    */
1908 /* C must have space for set->digits digits.                          */
1909 /* ------------------------------------------------------------------ */
1910 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1911                               const decNumber *rhs, decContext *set) {
1912   uInt status=0;                   /* accumulator */
1913   decMultiplyOp(res, lhs, rhs, set, &status);
1914   if (status!=0) decStatus(res, status, set);
1915   #if DECCHECK
1916   decCheckInexact(res, set);
1917   #endif
1918   return res;
1919   } /* decNumberMultiply */
1920
1921 /* ------------------------------------------------------------------ */
1922 /* decNumberPower -- raise a number to a power                        */
1923 /*                                                                    */
1924 /*   This computes C = A ** B                                         */
1925 /*                                                                    */
1926 /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1927 /*   lhs is A                                                         */
1928 /*   rhs is B                                                         */
1929 /*   set is the context                                               */
1930 /*                                                                    */
1931 /* C must have space for set->digits digits.                          */
1932 /*                                                                    */
1933 /* Mathematical function restrictions apply (see above); a NaN is     */
1934 /* returned with Invalid_operation if a restriction is violated.      */
1935 /*                                                                    */
1936 /* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1937 /* restrictions on A and the context are relaxed to the usual bounds, */
1938 /* for compatibility with the earlier (integer power only) version    */
1939 /* of this function.                                                  */
1940 /*                                                                    */
1941 /* When B is an integer, the result may be exact, even if rounded.    */
1942 /*                                                                    */
1943 /* The final result is rounded according to the context; it will      */
1944 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1945 /* error in rare cases.                                               */
1946 /* ------------------------------------------------------------------ */
1947 decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1948                            const decNumber *rhs, decContext *set) {
1949   #if DECSUBSET
1950   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
1951   decNumber *allocrhs=NULL;        /* .., rhs */
1952   #endif
1953   decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used */
1954   decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used */
1955   Int   reqdigits=set->digits;     /* requested DIGITS */
1956   Int   n;                         /* rhs in binary */
1957   Flag  rhsint=0;                  /* 1 if rhs is an integer */
1958   Flag  useint=0;                  /* 1 if can use integer calculation */
1959   Flag  isoddint=0;                /* 1 if rhs is an integer and odd */
1960   Int   i;                         /* work */
1961   #if DECSUBSET
1962   Int   dropped;                   /* .. */
1963   #endif
1964   uInt  needbytes;                 /* buffer size needed */
1965   Flag  seenbit;                   /* seen a bit while powering */
1966   Int   residue=0;                 /* rounding residue */
1967   uInt  status=0;                  /* accumulators */
1968   uByte bits=0;                    /* result sign if errors */
1969   decContext aset;                 /* working context */
1970   decNumber dnOne;                 /* work value 1... */
1971   /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1972   decNumber dacbuff[D2N(DECBUFFER+9)];
1973   decNumber *dac=dacbuff;          /* -> result accumulator */
1974   /* same again for possible 1/lhs calculation */
1975   decNumber invbuff[D2N(DECBUFFER+9)];
1976
1977   #if DECCHECK
1978   if (decCheckOperands(res, lhs, rhs, set)) return res;
1979   #endif
1980
1981   do {                             /* protect allocated storage */
1982     #if DECSUBSET
1983     if (!set->extended) { /* reduce operands and set status, as needed */
1984       if (lhs->digits>reqdigits) {
1985         alloclhs=decRoundOperand(lhs, set, &status);
1986         if (alloclhs==NULL) break;
1987         lhs=alloclhs;
1988         }
1989       if (rhs->digits>reqdigits) {
1990         allocrhs=decRoundOperand(rhs, set, &status);
1991         if (allocrhs==NULL) break;
1992         rhs=allocrhs;
1993         }
1994       }
1995     #endif
1996     /* [following code does not require input rounding] */
1997
1998     /* handle NaNs and rhs Infinity (lhs infinity is harder) */
1999     if (SPECIALARGS) {
2000       if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
2001         decNaNs(res, lhs, rhs, set, &status);
2002         break;}
2003       if (decNumberIsInfinite(rhs)) {   /* rhs Infinity */
2004         Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign */
2005         if (decNumberIsNegative(lhs)    /* lhs<0 */
2006          && !decNumberIsZero(lhs))      /* .. */
2007           status|=DEC_Invalid_operation;
2008          else {                         /* lhs >=0 */
2009           decNumberZero(&dnOne);        /* set up 1 */
2010           dnOne.lsu[0]=1;
2011           decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
2012           decNumberZero(res);           /* prepare for 0/1/Infinity */
2013           if (decNumberIsNegative(dac)) {    /* lhs<1 */
2014             if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0] */
2015             }
2016            else if (dac->lsu[0]==0) {        /* lhs=1 */
2017             /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2018             Int shift=set->digits-1;
2019             *res->lsu=1;                     /* was 0, make int 1 */
2020             res->digits=decShiftToMost(res->lsu, 1, shift);
2021             res->exponent=-shift;            /* make 1.0000... */
2022             status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2023             }
2024            else {                            /* lhs>1 */
2025             if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0] */
2026             }
2027           } /* lhs>=0 */
2028         break;}
2029       /* [lhs infinity drops through] */
2030       } /* specials */
2031
2032     /* Original rhs may be an integer that fits and is in range */
2033     n=decGetInt(rhs);
2034     if (n!=BADINT) {                    /* it is an integer */
2035       rhsint=1;                         /* record the fact for 1**n */
2036       isoddint=(Flag)n&1;               /* [works even if big] */
2037       if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path? */
2038         useint=1;                       /* looks good */
2039       }
2040
2041     if (decNumberIsNegative(lhs)        /* -x .. */
2042       && isoddint) bits=DECNEG;         /* .. to an odd power */
2043
2044     /* handle LHS infinity */
2045     if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled] */
2046       uByte rbits=rhs->bits;            /* save */
2047       decNumberZero(res);               /* prepare */
2048       if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1 */
2049        else {
2050         /* -Inf**nonint -> error */
2051         if (!rhsint && decNumberIsNegative(lhs)) {
2052           status|=DEC_Invalid_operation;     /* -Inf**nonint is error */
2053           break;}
2054         if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2055         /* [otherwise will be 0 or -0] */
2056         res->bits=bits;
2057         }
2058       break;}
2059
2060     /* similarly handle LHS zero */
2061     if (decNumberIsZero(lhs)) {
2062       if (n==0) {                            /* 0**0 => Error */
2063         #if DECSUBSET
2064         if (!set->extended) {                /* [unless subset] */
2065           decNumberZero(res);
2066           *res->lsu=1;                       /* return 1 */
2067           break;}
2068         #endif
2069         status|=DEC_Invalid_operation;
2070         }
2071        else {                                /* 0**x */
2072         uByte rbits=rhs->bits;               /* save */
2073         if (rbits & DECNEG) {                /* was a 0**(-n) */
2074           #if DECSUBSET
2075           if (!set->extended) {              /* [bad if subset] */
2076             status|=DEC_Invalid_operation;
2077             break;}
2078           #endif
2079           bits|=DECINF;
2080           }
2081         decNumberZero(res);                  /* prepare */
2082         /* [otherwise will be 0 or -0] */
2083         res->bits=bits;
2084         }
2085       break;}
2086
2087     /* here both lhs and rhs are finite; rhs==0 is handled in the */
2088     /* integer path.  Next handle the non-integer cases */
2089     if (!useint) {                      /* non-integral rhs */
2090       /* any -ve lhs is bad, as is either operand or context out of */
2091       /* bounds */
2092       if (decNumberIsNegative(lhs)) {
2093         status|=DEC_Invalid_operation;
2094         break;}
2095       if (decCheckMath(lhs, set, &status)
2096        || decCheckMath(rhs, set, &status)) break; /* variable status */
2097
2098       decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2099       aset.emax=DEC_MAX_MATH;           /* usual bounds */
2100       aset.emin=-DEC_MAX_MATH;          /* .. */
2101       aset.clamp=0;                     /* and no concrete format */
2102
2103       /* calculate the result using exp(ln(lhs)*rhs), which can */
2104       /* all be done into the accumulator, dac.  The precision needed */
2105       /* is enough to contain the full information in the lhs (which */
2106       /* is the total digits, including exponent), or the requested */
2107       /* precision, if larger, + 4; 6 is used for the exponent */
2108       /* maximum length, and this is also used when it is shorter */
2109       /* than the requested digits as it greatly reduces the >0.5 ulp */
2110       /* cases at little cost (because Ln doubles digits each */
2111       /* iteration so a few extra digits rarely causes an extra */
2112       /* iteration) */
2113       aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2114       } /* non-integer rhs */
2115
2116      else { /* rhs is in-range integer */
2117       if (n==0) {                       /* x**0 = 1 */
2118         /* (0**0 was handled above) */
2119         decNumberZero(res);             /* result=1 */
2120         *res->lsu=1;                    /* .. */
2121         break;}
2122       /* rhs is a non-zero integer */
2123       if (n<0) n=-n;                    /* use abs(n) */
2124
2125       aset=*set;                        /* clone the context */
2126       aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced */
2127       /* calculate the working DIGITS */
2128       aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2129       #if DECSUBSET
2130       if (!set->extended) aset.digits--;     /* use classic precision */
2131       #endif
2132       /* it's an error if this is more than can be handled */
2133       if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2134       } /* integer path */
2135
2136     /* aset.digits is the count of digits for the accumulator needed */
2137     /* if accumulator is too long for local storage, then allocate */
2138     needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2139     /* [needbytes also used below if 1/lhs needed] */
2140     if (needbytes>sizeof(dacbuff)) {
2141       allocdac=(decNumber *)malloc(needbytes);
2142       if (allocdac==NULL) {   /* hopeless -- abandon */
2143         status|=DEC_Insufficient_storage;
2144         break;}
2145       dac=allocdac;           /* use the allocated space */
2146       }
2147     /* here, aset is set up and accumulator is ready for use */
2148
2149     if (!useint) {                           /* non-integral rhs */
2150       /* x ** y; special-case x=1 here as it will otherwise always */
2151       /* reduce to integer 1; decLnOp has a fastpath which detects */
2152       /* the case of x=1 */
2153       decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs) */
2154       /* [no error possible, as lhs 0 already handled] */
2155       if (ISZERO(dac)) {                     /* x==1, 1.0, etc. */
2156         /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2157         *dac->lsu=1;                         /* was 0, make int 1 */
2158         if (!rhsint) {                       /* add padding */
2159           Int shift=set->digits-1;
2160           dac->digits=decShiftToMost(dac->lsu, 1, shift);
2161           dac->exponent=-shift;              /* make 1.0000... */
2162           status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact */
2163           }
2164         }
2165        else {
2166         decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs */
2167         decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac) */
2168         }
2169       /* and drop through for final rounding */
2170       } /* non-integer rhs */
2171
2172      else {                             /* carry on with integer */
2173       decNumberZero(dac);               /* acc=1 */
2174       *dac->lsu=1;                      /* .. */
2175
2176       /* if a negative power the constant 1 is needed, and if not subset */
2177       /* invert the lhs now rather than inverting the result later */
2178       if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0] */
2179         decNumber *inv=invbuff;         /* asssume use fixed buffer */
2180         decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later] */
2181         #if DECSUBSET
2182         if (set->extended) {            /* need to calculate 1/lhs */
2183         #endif
2184           /* divide lhs into 1, putting result in dac [dac=1/dac] */
2185           decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2186           /* now locate or allocate space for the inverted lhs */
2187           if (needbytes>sizeof(invbuff)) {
2188             allocinv=(decNumber *)malloc(needbytes);
2189             if (allocinv==NULL) {       /* hopeless -- abandon */
2190               status|=DEC_Insufficient_storage;
2191               break;}
2192             inv=allocinv;               /* use the allocated space */
2193             }
2194           /* [inv now points to big-enough buffer or allocated storage] */
2195           decNumberCopy(inv, dac);      /* copy the 1/lhs */
2196           decNumberCopy(dac, &dnOne);   /* restore acc=1 */
2197           lhs=inv;                      /* .. and go forward with new lhs */
2198         #if DECSUBSET
2199           }
2200         #endif
2201         }
2202
2203       /* Raise-to-the-power loop... */
2204       seenbit=0;                   /* set once a 1-bit is encountered */
2205       for (i=1;;i++){              /* for each bit [top bit ignored] */
2206         /* abandon if had overflow or terminal underflow */
2207         if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2208           if (status&DEC_Overflow || ISZERO(dac)) break;
2209           }
2210         /* [the following two lines revealed an optimizer bug in a C++ */
2211         /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2212         n=n<<1;                    /* move next bit to testable position */
2213         if (n<0) {                 /* top bit is set */
2214           seenbit=1;               /* OK, significant bit seen */
2215           decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2216           }
2217         if (i==31) break;          /* that was the last bit */
2218         if (!seenbit) continue;    /* no need to square 1 */
2219         decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2220         } /*i*/ /* 32 bits */
2221
2222       /* complete internal overflow or underflow processing */
2223       if (status & (DEC_Overflow|DEC_Underflow)) {
2224         #if DECSUBSET
2225         /* If subset, and power was negative, reverse the kind of -erflow */
2226         /* [1/x not yet done] */
2227         if (!set->extended && decNumberIsNegative(rhs)) {
2228           if (status & DEC_Overflow)
2229             status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2230            else { /* trickier -- Underflow may or may not be set */
2231             status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2232             status|=DEC_Overflow;
2233             }
2234           }
2235         #endif
2236         dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2237         /* round subnormals [to set.digits rather than aset.digits] */
2238         /* or set overflow result similarly as required */
2239         decFinalize(dac, set, &residue, &status);
2240         decNumberCopy(res, dac);   /* copy to result (is now OK length) */
2241         break;
2242         }
2243
2244       #if DECSUBSET
2245       if (!set->extended &&                  /* subset math */
2246           decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0] */
2247         /* so divide result into 1 [dac=1/dac] */
2248         decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2249         }
2250       #endif
2251       } /* rhs integer path */
2252
2253     /* reduce result to the requested length and copy to result */
2254     decCopyFit(res, dac, set, &residue, &status);
2255     decFinish(res, set, &residue, &status);  /* final cleanup */
2256     #if DECSUBSET
2257     if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros */
2258     #endif
2259     } while(0);                         /* end protected */
2260
2261   if (allocdac!=NULL) free(allocdac);   /* drop any storage used */
2262   if (allocinv!=NULL) free(allocinv);   /* .. */
2263   #if DECSUBSET
2264   if (alloclhs!=NULL) free(alloclhs);   /* .. */
2265   if (allocrhs!=NULL) free(allocrhs);   /* .. */
2266   #endif
2267   if (status!=0) decStatus(res, status, set);
2268   #if DECCHECK
2269   decCheckInexact(res, set);
2270   #endif
2271   return res;
2272   } /* decNumberPower */
2273
2274 /* ------------------------------------------------------------------ */
2275 /* decNumberQuantize -- force exponent to requested value             */
2276 /*                                                                    */
2277 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2278 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2279 /*   of C has exponent of B.  The numerical value of C will equal A,  */
2280 /*   except for the effects of any rounding that occurred.            */
2281 /*                                                                    */
2282 /*   res is C, the result.  C may be A or B                           */
2283 /*   lhs is A, the number to adjust                                   */
2284 /*   rhs is B, the number with exponent to match                      */
2285 /*   set is the context                                               */
2286 /*                                                                    */
2287 /* C must have space for set->digits digits.                          */
2288 /*                                                                    */
2289 /* Unless there is an error or the result is infinite, the exponent   */
2290 /* after the operation is guaranteed to be equal to that of B.        */
2291 /* ------------------------------------------------------------------ */
2292 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2293                               const decNumber *rhs, decContext *set) {
2294   uInt status=0;                        /* accumulator */
2295   decQuantizeOp(res, lhs, rhs, set, 1, &status);
2296   if (status!=0) decStatus(res, status, set);
2297   return res;
2298   } /* decNumberQuantize */
2299
2300 /* ------------------------------------------------------------------ */
2301 /* decNumberReduce -- remove trailing zeros                           */
2302 /*                                                                    */
2303 /*   This computes C = 0 + A, and normalizes the result               */
2304 /*                                                                    */
2305 /*   res is C, the result.  C may be A                                */
2306 /*   rhs is A                                                         */
2307 /*   set is the context                                               */
2308 /*                                                                    */
2309 /* C must have space for set->digits digits.                          */
2310 /* ------------------------------------------------------------------ */
2311 /* Previously known as Normalize */
2312 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2313                                decContext *set) {
2314   return decNumberReduce(res, rhs, set);
2315   } /* decNumberNormalize */
2316
2317 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2318                             decContext *set) {
2319   #if DECSUBSET
2320   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
2321   #endif
2322   uInt status=0;                   /* as usual */
2323   Int  residue=0;                  /* as usual */
2324   Int  dropped;                    /* work */
2325
2326   #if DECCHECK
2327   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2328   #endif
2329
2330   do {                             /* protect allocated storage */
2331     #if DECSUBSET
2332     if (!set->extended) {
2333       /* reduce operand and set lostDigits status, as needed */
2334       if (rhs->digits>set->digits) {
2335         allocrhs=decRoundOperand(rhs, set, &status);
2336         if (allocrhs==NULL) break;
2337         rhs=allocrhs;
2338         }
2339       }
2340     #endif
2341     /* [following code does not require input rounding] */
2342
2343     /* Infinities copy through; NaNs need usual treatment */
2344     if (decNumberIsNaN(rhs)) {
2345       decNaNs(res, rhs, NULL, set, &status);
2346       break;
2347       }
2348
2349     /* reduce result to the requested length and copy to result */
2350     decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2351     decFinish(res, set, &residue, &status);       /* cleanup/set flags */
2352     decTrim(res, set, 1, 0, &dropped);            /* normalize in place */
2353                                                   /* [may clamp] */
2354     } while(0);                              /* end protected */
2355
2356   #if DECSUBSET
2357   if (allocrhs !=NULL) free(allocrhs);       /* .. */
2358   #endif
2359   if (status!=0) decStatus(res, status, set);/* then report status */
2360   return res;
2361   } /* decNumberReduce */
2362
2363 /* ------------------------------------------------------------------ */
2364 /* decNumberRescale -- force exponent to requested value              */
2365 /*                                                                    */
2366 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2367 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2368 /*   of C has the value B.  The numerical value of C will equal A,    */
2369 /*   except for the effects of any rounding that occurred.            */
2370 /*                                                                    */
2371 /*   res is C, the result.  C may be A or B                           */
2372 /*   lhs is A, the number to adjust                                   */
2373 /*   rhs is B, the requested exponent                                 */
2374 /*   set is the context                                               */
2375 /*                                                                    */
2376 /* C must have space for set->digits digits.                          */
2377 /*                                                                    */
2378 /* Unless there is an error or the result is infinite, the exponent   */
2379 /* after the operation is guaranteed to be equal to B.                */
2380 /* ------------------------------------------------------------------ */
2381 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2382                              const decNumber *rhs, decContext *set) {
2383   uInt status=0;                        /* accumulator */
2384   decQuantizeOp(res, lhs, rhs, set, 0, &status);
2385   if (status!=0) decStatus(res, status, set);
2386   return res;
2387   } /* decNumberRescale */
2388
2389 /* ------------------------------------------------------------------ */
2390 /* decNumberRemainder -- divide and return remainder                  */
2391 /*                                                                    */
2392 /*   This computes C = A % B                                          */
2393 /*                                                                    */
2394 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2395 /*   lhs is A                                                         */
2396 /*   rhs is B                                                         */
2397 /*   set is the context                                               */
2398 /*                                                                    */
2399 /* C must have space for set->digits digits.                          */
2400 /* ------------------------------------------------------------------ */
2401 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2402                                const decNumber *rhs, decContext *set) {
2403   uInt status=0;                        /* accumulator */
2404   decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2405   if (status!=0) decStatus(res, status, set);
2406   #if DECCHECK
2407   decCheckInexact(res, set);
2408   #endif
2409   return res;
2410   } /* decNumberRemainder */
2411
2412 /* ------------------------------------------------------------------ */
2413 /* decNumberRemainderNear -- divide and return remainder from nearest */
2414 /*                                                                    */
2415 /*   This computes C = A % B, where % is the IEEE remainder operator  */
2416 /*                                                                    */
2417 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2418 /*   lhs is A                                                         */
2419 /*   rhs is B                                                         */
2420 /*   set is the context                                               */
2421 /*                                                                    */
2422 /* C must have space for set->digits digits.                          */
2423 /* ------------------------------------------------------------------ */
2424 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2425                                    const decNumber *rhs, decContext *set) {
2426   uInt status=0;                        /* accumulator */
2427   decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2428   if (status!=0) decStatus(res, status, set);
2429   #if DECCHECK
2430   decCheckInexact(res, set);
2431   #endif
2432   return res;
2433   } /* decNumberRemainderNear */
2434
2435 /* ------------------------------------------------------------------ */
2436 /* decNumberRotate -- rotate the coefficient of a Number left/right   */
2437 /*                                                                    */
2438 /*   This computes C = A rot B  (in base ten and rotating set->digits */
2439 /*   digits).                                                         */
2440 /*                                                                    */
2441 /*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2442 /*   lhs is A                                                         */
2443 /*   rhs is B, the number of digits to rotate (-ve to right)          */
2444 /*   set is the context                                               */
2445 /*                                                                    */
2446 /* The digits of the coefficient of A are rotated to the left (if B   */
2447 /* is positive) or to the right (if B is negative) without adjusting  */
2448 /* the exponent or the sign of A.  If lhs->digits is less than        */
2449 /* set->digits the coefficient is padded with zeros on the left       */
2450 /* before the rotate.  Any leading zeros in the result are removed    */
2451 /* as usual.                                                          */
2452 /*                                                                    */
2453 /* B must be an integer (q=0) and in the range -set->digits through   */
2454 /* +set->digits.                                                      */
2455 /* C must have space for set->digits digits.                          */
2456 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2457 /* B must be valid).  No status is set unless B is invalid or an      */
2458 /* operand is an sNaN.                                                */
2459 /* ------------------------------------------------------------------ */
2460 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2461                            const decNumber *rhs, decContext *set) {
2462   uInt status=0;              /* accumulator */
2463   Int  rotate;                /* rhs as an Int */
2464
2465   #if DECCHECK
2466   if (decCheckOperands(res, lhs, rhs, set)) return res;
2467   #endif
2468
2469   /* NaNs propagate as normal */
2470   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2471     decNaNs(res, lhs, rhs, set, &status);
2472    /* rhs must be an integer */
2473    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2474     status=DEC_Invalid_operation;
2475    else { /* both numeric, rhs is an integer */
2476     rotate=decGetInt(rhs);                   /* [cannot fail] */
2477     if (rotate==BADINT                       /* something bad .. */
2478      || rotate==BIGODD || rotate==BIGEVEN    /* .. very big .. */
2479      || abs(rotate)>set->digits)             /* .. or out of range */
2480       status=DEC_Invalid_operation;
2481      else {                                  /* rhs is OK */
2482       decNumberCopy(res, lhs);
2483       /* convert -ve rotate to equivalent positive rotation */
2484       if (rotate<0) rotate=set->digits+rotate;
2485       if (rotate!=0 && rotate!=set->digits   /* zero or full rotation */
2486        && !decNumberIsInfinite(res)) {       /* lhs was infinite */
2487         /* left-rotate to do; 0 < rotate < set->digits */
2488         uInt units, shift;                   /* work */
2489         uInt msudigits;                      /* digits in result msu */
2490         Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu */
2491         Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2492         for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0 */
2493         res->digits=set->digits;                  /* now full-length */
2494         msudigits=MSUDIGITS(res->digits);         /* actual digits in msu */
2495
2496         /* rotation here is done in-place, in three steps */
2497         /* 1. shift all to least up to one unit to unit-align final */
2498         /*    lsd [any digits shifted out are rotated to the left, */
2499         /*    abutted to the original msd (which may require split)] */
2500         /* */
2501         /*    [if there are no whole units left to rotate, the */
2502         /*    rotation is now complete] */
2503         /* */
2504         /* 2. shift to least, from below the split point only, so that */
2505         /*    the final msd is in the right place in its Unit [any */
2506         /*    digits shifted out will fit exactly in the current msu, */
2507         /*    left aligned, no split required] */
2508         /* */
2509         /* 3. rotate all the units by reversing left part, right */
2510         /*    part, and then whole */
2511         /* */
2512         /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2513         /* */
2514         /*   start: 00a bcd efg hij klm npq */
2515         /* */
2516         /*      1a  000 0ab cde fgh|ijk lmn [pq saved] */
2517         /*      1b  00p qab cde fgh|ijk lmn */
2518         /* */
2519         /*      2a  00p qab cde fgh|00i jkl [mn saved] */
2520         /*      2b  mnp qab cde fgh|00i jkl */
2521         /* */
2522         /*      3a  fgh cde qab mnp|00i jkl */
2523         /*      3b  fgh cde qab mnp|jkl 00i */
2524         /*      3c  00i jkl mnp qab cde fgh */
2525
2526         /* Step 1: amount to shift is the partial right-rotate count */
2527         rotate=set->digits-rotate;      /* make it right-rotate */
2528         units=rotate/DECDPUN;           /* whole units to rotate */
2529         shift=rotate%DECDPUN;           /* left-over digits count */
2530         if (shift>0) {                  /* not an exact number of units */
2531           uInt save=res->lsu[0]%powers[shift];    /* save low digit(s) */
2532           decShiftToLeast(res->lsu, D2U(res->digits), shift);
2533           if (shift>msudigits) {        /* msumax-1 needs >0 digits */
2534             uInt rem=save%powers[shift-msudigits];/* split save */
2535             *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2536             *(msumax-1)=*(msumax-1)
2537                        +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2538             }
2539            else { /* all fits in msumax */
2540             *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2541             }
2542           } /* digits shift needed */
2543
2544         /* If whole units to rotate... */
2545         if (units>0) {                  /* some to do */
2546           /* Step 2: the units to touch are the whole ones in rotate, */
2547           /*   if any, and the shift is DECDPUN-msudigits (which may be */
2548           /*   0, again) */
2549           shift=DECDPUN-msudigits;
2550           if (shift>0) {                /* not an exact number of units */
2551             uInt save=res->lsu[0]%powers[shift];  /* save low digit(s) */
2552             decShiftToLeast(res->lsu, units, shift);
2553             *msumax=*msumax+(Unit)(save*powers[msudigits]);
2554             } /* partial shift needed */
2555
2556           /* Step 3: rotate the units array using triple reverse */
2557           /* (reversing is easy and fast) */
2558           decReverse(res->lsu+units, msumax);     /* left part */
2559           decReverse(res->lsu, res->lsu+units-1); /* right part */
2560           decReverse(res->lsu, msumax);           /* whole */
2561           } /* whole units to rotate */
2562         /* the rotation may have left an undetermined number of zeros */
2563         /* on the left, so true length needs to be calculated */
2564         res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2565         } /* rotate needed */
2566       } /* rhs OK */
2567     } /* numerics */
2568   if (status!=0) decStatus(res, status, set);
2569   return res;
2570   } /* decNumberRotate */
2571
2572 /* ------------------------------------------------------------------ */
2573 /* decNumberSameQuantum -- test for equal exponents                   */
2574 /*                                                                    */
2575 /*   res is the result number, which will contain either 0 or 1       */
2576 /*   lhs is a number to test                                          */
2577 /*   rhs is the second (usually a pattern)                            */
2578 /*                                                                    */
2579 /* No errors are possible and no context is needed.                   */
2580 /* ------------------------------------------------------------------ */
2581 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2582                                  const decNumber *rhs) {
2583   Unit ret=0;                      /* return value */
2584
2585   #if DECCHECK
2586   if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2587   #endif
2588
2589   if (SPECIALARGS) {
2590     if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2591      else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2592      /* [anything else with a special gives 0] */
2593     }
2594    else if (lhs->exponent==rhs->exponent) ret=1;
2595
2596   decNumberZero(res);              /* OK to overwrite an operand now */
2597   *res->lsu=ret;
2598   return res;
2599   } /* decNumberSameQuantum */
2600
2601 /* ------------------------------------------------------------------ */
2602 /* decNumberScaleB -- multiply by a power of 10                       */
2603 /*                                                                    */
2604 /* This computes C = A x 10**B where B is an integer (q=0) with       */
2605 /* maximum magnitude 2*(emax+digits)                                  */
2606 /*                                                                    */
2607 /*   res is C, the result.  C may be A or B                           */
2608 /*   lhs is A, the number to adjust                                   */
2609 /*   rhs is B, the requested power of ten to use                      */
2610 /*   set is the context                                               */
2611 /*                                                                    */
2612 /* C must have space for set->digits digits.                          */
2613 /*                                                                    */
2614 /* The result may underflow or overflow.                              */
2615 /* ------------------------------------------------------------------ */
2616 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2617                             const decNumber *rhs, decContext *set) {
2618   Int  reqexp;                /* requested exponent change [B] */
2619   uInt status=0;              /* accumulator */
2620   Int  residue;               /* work */
2621
2622   #if DECCHECK
2623   if (decCheckOperands(res, lhs, rhs, set)) return res;
2624   #endif
2625
2626   /* Handle special values except lhs infinite */
2627   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2628     decNaNs(res, lhs, rhs, set, &status);
2629     /* rhs must be an integer */
2630    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2631     status=DEC_Invalid_operation;
2632    else {
2633     /* lhs is a number; rhs is a finite with q==0 */
2634     reqexp=decGetInt(rhs);                   /* [cannot fail] */
2635     if (reqexp==BADINT                       /* something bad .. */
2636      || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big .. */
2637      || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2638       status=DEC_Invalid_operation;
2639      else {                                  /* rhs is OK */
2640       decNumberCopy(res, lhs);               /* all done if infinite lhs */
2641       if (!decNumberIsInfinite(res)) {       /* prepare to scale */
2642         res->exponent+=reqexp;               /* adjust the exponent */
2643         residue=0;
2644         decFinalize(res, set, &residue, &status); /* .. and check */
2645         } /* finite LHS */
2646       } /* rhs OK */
2647     } /* rhs finite */
2648   if (status!=0) decStatus(res, status, set);
2649   return res;
2650   } /* decNumberScaleB */
2651
2652 /* ------------------------------------------------------------------ */
2653 /* decNumberShift -- shift the coefficient of a Number left or right  */
2654 /*                                                                    */
2655 /*   This computes C = A << B or C = A >> -B  (in base ten).          */
2656 /*                                                                    */
2657 /*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2658 /*   lhs is A                                                         */
2659 /*   rhs is B, the number of digits to shift (-ve to right)           */
2660 /*   set is the context                                               */
2661 /*                                                                    */
2662 /* The digits of the coefficient of A are shifted to the left (if B   */
2663 /* is positive) or to the right (if B is negative) without adjusting  */
2664 /* the exponent or the sign of A.                                     */
2665 /*                                                                    */
2666 /* B must be an integer (q=0) and in the range -set->digits through   */
2667 /* +set->digits.                                                      */
2668 /* C must have space for set->digits digits.                          */
2669 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2670 /* B must be valid).  No status is set unless B is invalid or an      */
2671 /* operand is an sNaN.                                                */
2672 /* ------------------------------------------------------------------ */
2673 decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2674                            const decNumber *rhs, decContext *set) {
2675   uInt status=0;              /* accumulator */
2676   Int  shift;                 /* rhs as an Int */
2677
2678   #if DECCHECK
2679   if (decCheckOperands(res, lhs, rhs, set)) return res;
2680   #endif
2681
2682   /* NaNs propagate as normal */
2683   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2684     decNaNs(res, lhs, rhs, set, &status);
2685    /* rhs must be an integer */
2686    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2687     status=DEC_Invalid_operation;
2688    else { /* both numeric, rhs is an integer */
2689     shift=decGetInt(rhs);                    /* [cannot fail] */
2690     if (shift==BADINT                        /* something bad .. */
2691      || shift==BIGODD || shift==BIGEVEN      /* .. very big .. */
2692      || abs(shift)>set->digits)              /* .. or out of range */
2693       status=DEC_Invalid_operation;
2694      else {                                  /* rhs is OK */
2695       decNumberCopy(res, lhs);
2696       if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2697         if (shift>0) {                       /* to left */
2698           if (shift==set->digits) {          /* removing all */
2699             *res->lsu=0;                     /* so place 0 */
2700             res->digits=1;                   /* .. */
2701             }
2702            else {                            /* */
2703             /* first remove leading digits if necessary */
2704             if (res->digits+shift>set->digits) {
2705               decDecap(res, res->digits+shift-set->digits);
2706               /* that updated res->digits; may have gone to 1 (for a */
2707               /* single digit or for zero */
2708               }
2709             if (res->digits>1 || *res->lsu)  /* if non-zero.. */
2710               res->digits=decShiftToMost(res->lsu, res->digits, shift);
2711             } /* partial left */
2712           } /* left */
2713          else { /* to right */
2714           if (-shift>=res->digits) {         /* discarding all */
2715             *res->lsu=0;                     /* so place 0 */
2716             res->digits=1;                   /* .. */
2717             }
2718            else {
2719             decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2720             res->digits-=(-shift);
2721             }
2722           } /* to right */
2723         } /* non-0 non-Inf shift */
2724       } /* rhs OK */
2725     } /* numerics */
2726   if (status!=0) decStatus(res, status, set);
2727   return res;
2728   } /* decNumberShift */
2729
2730 /* ------------------------------------------------------------------ */
2731 /* decNumberSquareRoot -- square root operator                        */
2732 /*                                                                    */
2733 /*   This computes C = squareroot(A)                                  */
2734 /*                                                                    */
2735 /*   res is C, the result.  C may be A                                */
2736 /*   rhs is A                                                         */
2737 /*   set is the context; note that rounding mode has no effect        */
2738 /*                                                                    */
2739 /* C must have space for set->digits digits.                          */
2740 /* ------------------------------------------------------------------ */
2741 /* This uses the following varying-precision algorithm in:            */
2742 /*                                                                    */
2743 /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2744 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2745 /*   pp229-237, ACM, September 1985.                                  */
2746 /*                                                                    */
2747 /* The square-root is calculated using Newton's method, after which   */
2748 /* a check is made to ensure the result is correctly rounded.         */
2749 /*                                                                    */
2750 /* % [Reformatted original Numerical Turing source code follows.]     */
2751 /* function sqrt(x : real) : real                                     */
2752 /* % sqrt(x) returns the properly rounded approximation to the square */
2753 /* % root of x, in the precision of the calling environment, or it    */
2754 /* % fails if x < 0.                                                  */
2755 /* % t e hull and a abrham, august, 1984                              */
2756 /* if x <= 0 then                                                     */
2757 /*   if x < 0 then                                                    */
2758 /*     assert false                                                   */
2759 /*   else                                                             */
2760 /*     result 0                                                       */
2761 /*   end if                                                           */
2762 /* end if                                                             */
2763 /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2764 /* var e := getexp(x)     % exponent part of x                        */
2765 /* var approx : real                                                  */
2766 /* if e mod 2 = 0  then                                               */
2767 /*   approx := .259 + .819 * f   % approx to root of f                */
2768 /* else                                                               */
2769 /*   f := f/l0                   % adjustments                        */
2770 /*   e := e + 1                  %   for odd                          */
2771 /*   approx := .0819 + 2.59 * f  %   exponent                         */
2772 /* end if                                                             */
2773 /*                                                                    */
2774 /* var p:= 3                                                          */
2775 /* const maxp := currentprecision + 2                                 */
2776 /* loop                                                               */
2777 /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2778 /*   precision p                                                      */
2779 /*   approx := .5 * (approx + f/approx)                               */
2780 /*   exit when p = maxp                                               */
2781 /* end loop                                                           */
2782 /*                                                                    */
2783 /* % approx is now within 1 ulp of the properly rounded square root   */
2784 /* % of f; to ensure proper rounding, compare squares of (approx -    */
2785 /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2786 /* p := currentprecision                                              */
2787 /* begin                                                              */
2788 /*   precision p + 2                                                  */
2789 /*   const approxsubhalf := approx - setexp(.5, -p)                   */
2790 /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2791 /*     approx := approx - setexp(.l, -p + 1)                          */
2792 /*   else                                                             */
2793 /*     const approxaddhalf := approx + setexp(.5, -p)                 */
2794 /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2795 /*       approx := approx + setexp(.l, -p + 1)                        */
2796 /*     end if                                                         */
2797 /*   end if                                                           */
2798 /* end                                                                */
2799 /* result setexp(approx, e div 2)  % fix exponent                     */
2800 /* end sqrt                                                           */
2801 /* ------------------------------------------------------------------ */
2802 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2803                                 decContext *set) {
2804   decContext workset, approxset;   /* work contexts */
2805   decNumber dzero;                 /* used for constant zero */
2806   Int  maxp;                       /* largest working precision */
2807   Int  workp;                      /* working precision */
2808   Int  residue=0;                  /* rounding residue */
2809   uInt status=0, ignore=0;         /* status accumulators */
2810   uInt rstatus;                    /* .. */
2811   Int  exp;                        /* working exponent */
2812   Int  ideal;                      /* ideal (preferred) exponent */
2813   Int  needbytes;                  /* work */
2814   Int  dropped;                    /* .. */
2815
2816   #if DECSUBSET
2817   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
2818   #endif
2819   /* buffer for f [needs +1 in case DECBUFFER 0] */
2820   decNumber buff[D2N(DECBUFFER+1)];
2821   /* buffer for a [needs +2 to match likely maxp] */
2822   decNumber bufa[D2N(DECBUFFER+2)];
2823   /* buffer for temporary, b [must be same size as a] */
2824   decNumber bufb[D2N(DECBUFFER+2)];
2825   decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated */
2826   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
2827   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
2828   decNumber *f=buff;               /* reduced fraction */
2829   decNumber *a=bufa;               /* approximation to result */
2830   decNumber *b=bufb;               /* intermediate result */
2831   /* buffer for temporary variable, up to 3 digits */
2832   decNumber buft[D2N(3)];
2833   decNumber *t=buft;               /* up-to-3-digit constant or work */
2834
2835   #if DECCHECK
2836   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2837   #endif
2838
2839   do {                             /* protect allocated storage */
2840     #if DECSUBSET
2841     if (!set->extended) {
2842       /* reduce operand and set lostDigits status, as needed */
2843       if (rhs->digits>set->digits) {
2844         allocrhs=decRoundOperand(rhs, set, &status);
2845         if (allocrhs==NULL) break;
2846         /* [Note: 'f' allocation below could reuse this buffer if */
2847         /* used, but as this is rare they are kept separate for clarity.] */
2848         rhs=allocrhs;
2849         }
2850       }
2851     #endif
2852     /* [following code does not require input rounding] */
2853
2854     /* handle infinities and NaNs */
2855     if (SPECIALARG) {
2856       if (decNumberIsInfinite(rhs)) {         /* an infinity */
2857         if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2858          else decNumberCopy(res, rhs);        /* +Infinity */
2859         }
2860        else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2861       break;
2862       }
2863
2864     /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2865     /* [It would be nicer to write: ideal=rhs->exponent>>1, but this */
2866     /* generates a compiler warning.  Generated code is the same.] */
2867     ideal=(rhs->exponent&~1)/2;         /* target */
2868
2869     /* handle zeros */
2870     if (ISZERO(rhs)) {
2871       decNumberCopy(res, rhs);          /* could be 0 or -0 */
2872       res->exponent=ideal;              /* use the ideal [safe] */
2873       /* use decFinish to clamp any out-of-range exponent, etc. */
2874       decFinish(res, set, &residue, &status);
2875       break;
2876       }
2877
2878     /* any other -x is an oops */
2879     if (decNumberIsNegative(rhs)) {
2880       status|=DEC_Invalid_operation;
2881       break;
2882       }
2883
2884     /* space is needed for three working variables */
2885     /*   f -- the same precision as the RHS, reduced to 0.01->0.99... */
2886     /*   a -- Hull's approximation -- precision, when assigned, is */
2887     /*        currentprecision+1 or the input argument precision, */
2888     /*        whichever is larger (+2 for use as temporary) */
2889     /*   b -- intermediate temporary result (same size as a) */
2890     /* if any is too long for local storage, then allocate */
2891     workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision */
2892     workp=MAXI(workp, 7);                    /* at least 7 for low cases */
2893     maxp=workp+2;                            /* largest working precision */
2894
2895     needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2896     if (needbytes>(Int)sizeof(buff)) {
2897       allocbuff=(decNumber *)malloc(needbytes);
2898       if (allocbuff==NULL) {  /* hopeless -- abandon */
2899         status|=DEC_Insufficient_storage;
2900         break;}
2901       f=allocbuff;            /* use the allocated space */
2902       }
2903     /* a and b both need to be able to hold a maxp-length number */
2904     needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2905     if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b] */
2906       allocbufa=(decNumber *)malloc(needbytes);
2907       allocbufb=(decNumber *)malloc(needbytes);
2908       if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless */
2909         status|=DEC_Insufficient_storage;
2910         break;}
2911       a=allocbufa;            /* use the allocated spaces */
2912       b=allocbufb;            /* .. */
2913       }
2914
2915     /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2916     decNumberCopy(f, rhs);
2917     exp=f->exponent+f->digits;               /* adjusted to Hull rules */
2918     f->exponent=-(f->digits);                /* to range */
2919
2920     /* set up working context */
2921     decContextDefault(&workset, DEC_INIT_DECIMAL64);
2922     workset.emax=DEC_MAX_EMAX;
2923     workset.emin=DEC_MIN_EMIN;
2924
2925     /* [Until further notice, no error is possible and status bits */
2926     /* (Rounded, etc.) should be ignored, not accumulated.] */
2927
2928     /* Calculate initial approximation, and allow for odd exponent */
2929     workset.digits=workp;                    /* p for initial calculation */
2930     t->bits=0; t->digits=3;
2931     a->bits=0; a->digits=3;
2932     if ((exp & 1)==0) {                      /* even exponent */
2933       /* Set t=0.259, a=0.819 */
2934       t->exponent=-3;
2935       a->exponent=-3;
2936       #if DECDPUN>=3
2937         t->lsu[0]=259;
2938         a->lsu[0]=819;
2939       #elif DECDPUN==2
2940         t->lsu[0]=59; t->lsu[1]=2;
2941         a->lsu[0]=19; a->lsu[1]=8;
2942       #else
2943         t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2944         a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2945       #endif
2946       }
2947      else {                                  /* odd exponent */
2948       /* Set t=0.0819, a=2.59 */
2949       f->exponent--;                         /* f=f/10 */
2950       exp++;                                 /* e=e+1 */
2951       t->exponent=-4;
2952       a->exponent=-2;
2953       #if DECDPUN>=3
2954         t->lsu[0]=819;
2955         a->lsu[0]=259;
2956       #elif DECDPUN==2
2957         t->lsu[0]=19; t->lsu[1]=8;
2958         a->lsu[0]=59; a->lsu[1]=2;
2959       #else
2960         t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2961         a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2962       #endif
2963       }
2964
2965     decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f */
2966     decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t */
2967     /* [a is now the initial approximation for sqrt(f), calculated with */
2968     /* currentprecision, which is also a's precision.] */
2969
2970     /* the main calculation loop */
2971     decNumberZero(&dzero);                   /* make 0 */
2972     decNumberZero(t);                        /* set t = 0.5 */
2973     t->lsu[0]=5;                             /* .. */
2974     t->exponent=-1;                          /* .. */
2975     workset.digits=3;                        /* initial p */
2976     for (; workset.digits<maxp;) {
2977       /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp] */
2978       workset.digits=MINI(workset.digits*2-2, maxp);
2979       /* a = 0.5 * (a + f/a) */
2980       /* [calculated at p then rounded to currentprecision] */
2981       decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
2982       decAddOp(b, b, a, &workset, 0, &ignore);         /* b=b+a */
2983       decMultiplyOp(a, b, t, &workset, &ignore);       /* a=b*0.5 */
2984       } /* loop */
2985
2986     /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
2987     /* now reduce to length, etc.; this needs to be done with a */
2988     /* having the correct exponent so as to handle subnormals */
2989     /* correctly */
2990     approxset=*set;                          /* get emin, emax, etc. */
2991     approxset.round=DEC_ROUND_HALF_EVEN;
2992     a->exponent+=exp/2;                      /* set correct exponent */
2993     rstatus=0;                               /* clear status */
2994     residue=0;                               /* .. and accumulator */
2995     decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed) */
2996     decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize */
2997
2998     /* Overflow was possible if the input exponent was out-of-range, */
2999     /* in which case quit */
3000     if (rstatus&DEC_Overflow) {
3001       status=rstatus;                        /* use the status as-is */
3002       decNumberCopy(res, a);                 /* copy to result */
3003       break;
3004       }
3005
3006     /* Preserve status except Inexact/Rounded */
3007     status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3008
3009     /* Carry out the Hull correction */
3010     a->exponent-=exp/2;                      /* back to 0.1->1 */
3011
3012     /* a is now at final precision and within 1 ulp of the properly */
3013     /* rounded square root of f; to ensure proper rounding, compare */
3014     /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
3015     /* Here workset.digits=maxp and t=0.5, and a->digits determines */
3016     /* the ulp */
3017     workset.digits--;                             /* maxp-1 is OK now */
3018     t->exponent=-a->digits-1;                     /* make 0.5 ulp */
3019     decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3020     workset.round=DEC_ROUND_UP;
3021     decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b) */
3022     decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3023     if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f] */
3024       /* this is the more common adjustment, though both are rare */
3025       t->exponent++;                              /* make 1.0 ulp */
3026       t->lsu[0]=1;                                /* .. */
3027       decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3028       /* assign to approx [round to length] */
3029       approxset.emin-=exp/2;                      /* adjust to match a */
3030       approxset.emax-=exp/2;
3031       decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3032       }
3033      else {
3034       decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp */
3035       workset.round=DEC_ROUND_DOWN;
3036       decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b) */
3037       decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f */
3038       if (decNumberIsNegative(b)) {               /* b < f */
3039         t->exponent++;                            /* make 1.0 ulp */
3040         t->lsu[0]=1;                              /* .. */
3041         decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp */
3042         /* assign to approx [round to length] */
3043         approxset.emin-=exp/2;                    /* adjust to match a */
3044         approxset.emax-=exp/2;
3045         decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3046         }
3047       }
3048     /* [no errors are possible in the above, and rounding/inexact during */
3049     /* estimation are irrelevant, so status was not accumulated] */
3050
3051     /* Here, 0.1 <= a < 1  (still), so adjust back */
3052     a->exponent+=exp/2;                      /* set correct exponent */
3053
3054     /* count droppable zeros [after any subnormal rounding] by */
3055     /* trimming a copy */
3056     decNumberCopy(b, a);
3057     decTrim(b, set, 1, 1, &dropped);         /* [drops trailing zeros] */
3058
3059     /* Set Inexact and Rounded.  The answer can only be exact if */
3060     /* it is short enough so that squaring it could fit in workp */
3061     /* digits, so this is the only (relatively rare) condition that */
3062     /* a careful check is needed */
3063     if (b->digits*2-1 > workp) {             /* cannot fit */
3064       status|=DEC_Inexact|DEC_Rounded;
3065       }
3066      else {                                  /* could be exact/unrounded */
3067       uInt mstatus=0;                        /* local status */
3068       decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3069       if (mstatus&DEC_Overflow) {            /* result just won't fit */
3070         status|=DEC_Inexact|DEC_Rounded;
3071         }
3072        else {                                /* plausible */
3073         decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3074         if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3075          else {                              /* is Exact */
3076           /* here, dropped is the count of trailing zeros in 'a' */
3077           /* use closest exponent to ideal... */
3078           Int todrop=ideal-a->exponent;      /* most that can be dropped */
3079           if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3080            else {                            /* unrounded */
3081             /* there are some to drop, but emax may not allow all */
3082             Int maxexp=set->emax-set->digits+1;
3083             Int maxdrop=maxexp-a->exponent;
3084             if (todrop>maxdrop && set->clamp) { /* apply clamping */
3085               todrop=maxdrop;
3086               status|=DEC_Clamped;
3087               }
3088             if (dropped<todrop) {            /* clamp to those available */
3089               todrop=dropped;
3090               status|=DEC_Clamped;
3091               }
3092             if (todrop>0) {                  /* have some to drop */
3093               decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3094               a->exponent+=todrop;           /* maintain numerical value */
3095               a->digits-=todrop;             /* new length */
3096               }
3097             }
3098           }
3099         }
3100       }
3101
3102     /* double-check Underflow, as perhaps the result could not have */
3103     /* been subnormal (initial argument too big), or it is now Exact */
3104     if (status&DEC_Underflow) {
3105       Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent */
3106       /* check if truly subnormal */
3107       #if DECEXTFLAG                         /* DEC_Subnormal too */
3108         if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3109       #else
3110         if (ae>=set->emin*2) status&=~DEC_Underflow;
3111       #endif
3112       /* check if truly inexact */
3113       if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3114       }
3115
3116     decNumberCopy(res, a);                   /* a is now the result */
3117     } while(0);                              /* end protected */
3118
3119   if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used */
3120   if (allocbufa!=NULL) free(allocbufa);      /* .. */
3121   if (allocbufb!=NULL) free(allocbufb);      /* .. */
3122   #if DECSUBSET
3123   if (allocrhs !=NULL) free(allocrhs);       /* .. */
3124   #endif
3125   if (status!=0) decStatus(res, status, set);/* then report status */
3126   #if DECCHECK
3127   decCheckInexact(res, set);
3128   #endif
3129   return res;
3130   } /* decNumberSquareRoot */
3131
3132 /* ------------------------------------------------------------------ */
3133 /* decNumberSubtract -- subtract two Numbers                          */
3134 /*                                                                    */
3135 /*   This computes C = A - B                                          */
3136 /*                                                                    */
3137 /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3138 /*   lhs is A                                                         */
3139 /*   rhs is B                                                         */
3140 /*   set is the context                                               */
3141 /*                                                                    */
3142 /* C must have space for set->digits digits.                          */
3143 /* ------------------------------------------------------------------ */
3144 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3145                               const decNumber *rhs, decContext *set) {
3146   uInt status=0;                        /* accumulator */
3147
3148   decAddOp(res, lhs, rhs, set, DECNEG, &status);
3149   if (status!=0) decStatus(res, status, set);
3150   #if DECCHECK
3151   decCheckInexact(res, set);
3152   #endif
3153   return res;
3154   } /* decNumberSubtract */
3155
3156 /* ------------------------------------------------------------------ */
3157 /* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3158 /* decNumberToIntegralValue -- round-to-integral-value                */
3159 /*                                                                    */
3160 /*   res is the result                                                */
3161 /*   rhs is input number                                              */
3162 /*   set is the context                                               */
3163 /*                                                                    */
3164 /* res must have space for any value of rhs.                          */
3165 /*                                                                    */
3166 /* This implements the IEEE special operators and therefore treats    */
3167 /* special values as valid.  For finite numbers it returns            */
3168 /* rescale(rhs, 0) if rhs->exponent is <0.                            */
3169 /* Otherwise the result is rhs (so no error is possible, except for   */
3170 /* sNaN).                                                             */
3171 /*                                                                    */
3172 /* The context is used for rounding mode and status after sNaN, but   */
3173 /* the digits setting is ignored.  The Exact version will signal      */
3174 /* Inexact if the result differs numerically from rhs; the other      */
3175 /* never signals Inexact.                                             */
3176 /* ------------------------------------------------------------------ */
3177 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3178                                      decContext *set) {
3179   decNumber dn;
3180   decContext workset;              /* working context */
3181   uInt status=0;                   /* accumulator */
3182
3183   #if DECCHECK
3184   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3185   #endif
3186
3187   /* handle infinities and NaNs */
3188   if (SPECIALARG) {
3189     if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */
3190      else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3191     }
3192    else { /* finite */
3193     /* have a finite number; no error possible (res must be big enough) */
3194     if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3195     /* that was easy, but if negative exponent there is work to do... */
3196     workset=*set;                  /* clone rounding, etc. */
3197     workset.digits=rhs->digits;    /* no length rounding */
3198     workset.traps=0;               /* no traps */
3199     decNumberZero(&dn);            /* make a number with exponent 0 */
3200     decNumberQuantize(res, rhs, &dn, &workset);
3201     status|=workset.status;
3202     }
3203   if (status!=0) decStatus(res, status, set);
3204   return res;
3205   } /* decNumberToIntegralExact */
3206
3207 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3208                                      decContext *set) {
3209   decContext workset=*set;         /* working context */
3210   workset.traps=0;                 /* no traps */
3211   decNumberToIntegralExact(res, rhs, &workset);
3212   /* this never affects set, except for sNaNs; NaN will have been set */
3213   /* or propagated already, so no need to call decStatus */
3214   set->status|=workset.status&DEC_Invalid_operation;
3215   return res;
3216   } /* decNumberToIntegralValue */
3217
3218 /* ------------------------------------------------------------------ */
3219 /* decNumberXor -- XOR two Numbers, digitwise                         */
3220 /*                                                                    */
3221 /*   This computes C = A ^ B                                          */
3222 /*                                                                    */
3223 /*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3224 /*   lhs is A                                                         */
3225 /*   rhs is B                                                         */
3226 /*   set is the context (used for result length and error report)     */
3227 /*                                                                    */
3228 /* C must have space for set->digits digits.                          */
3229 /*                                                                    */
3230 /* Logical function restrictions apply (see above); a NaN is          */
3231 /* returned with Invalid_operation if a restriction is violated.      */
3232 /* ------------------------------------------------------------------ */
3233 decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3234                          const decNumber *rhs, decContext *set) {
3235   const Unit *ua, *ub;                  /* -> operands */
3236   const Unit *msua, *msub;              /* -> operand msus */
3237   Unit  *uc, *msuc;                     /* -> result and its msu */
3238   Int   msudigs;                        /* digits in res msu */
3239   #if DECCHECK
3240   if (decCheckOperands(res, lhs, rhs, set)) return res;
3241   #endif
3242
3243   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3244    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3245     decStatus(res, DEC_Invalid_operation, set);
3246     return res;
3247     }
3248   /* operands are valid */
3249   ua=lhs->lsu;                          /* bottom-up */
3250   ub=rhs->lsu;                          /* .. */
3251   uc=res->lsu;                          /* .. */
3252   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
3253   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
3254   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
3255   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
3256   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
3257     Unit a, b;                          /* extract units */
3258     if (ua>msua) a=0;
3259      else a=*ua;
3260     if (ub>msub) b=0;
3261      else b=*ub;
3262     *uc=0;                              /* can now write back */
3263     if (a|b) {                          /* maybe 1 bits to examine */
3264       Int i, j;
3265       /* This loop could be unrolled and/or use BIN2BCD tables */
3266       for (i=0; i<DECDPUN; i++) {
3267         if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR */
3268         j=a%10;
3269         a=a/10;
3270         j|=b%10;
3271         b=b/10;
3272         if (j>1) {
3273           decStatus(res, DEC_Invalid_operation, set);
3274           return res;
3275           }
3276         if (uc==msuc && i==msudigs-1) break;      /* just did final digit */
3277         } /* each digit */
3278       } /* non-zero */
3279     } /* each unit */
3280   /* [here uc-1 is the msu of the result] */
3281   res->digits=decGetDigits(res->lsu, uc-res->lsu);
3282   res->exponent=0;                      /* integer */
3283   res->bits=0;                          /* sign=0 */
3284   return res;  /* [no status to set] */
3285   } /* decNumberXor */
3286
3287
3288 /* ================================================================== */
3289 /* Utility routines                                                   */
3290 /* ================================================================== */
3291
3292 /* ------------------------------------------------------------------ */
3293 /* decNumberClass -- return the decClass of a decNumber               */
3294 /*   dn -- the decNumber to test                                      */
3295 /*   set -- the context to use for Emin                               */
3296 /*   returns the decClass enum                                        */
3297 /* ------------------------------------------------------------------ */
3298 enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3299   if (decNumberIsSpecial(dn)) {
3300     if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3301     if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3302     /* must be an infinity */
3303     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3304     return DEC_CLASS_POS_INF;
3305     }
3306   /* is finite */
3307   if (decNumberIsNormal(dn, set)) { /* most common */
3308     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3309     return DEC_CLASS_POS_NORMAL;
3310     }
3311   /* is subnormal or zero */
3312   if (decNumberIsZero(dn)) {    /* most common */
3313     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3314     return DEC_CLASS_POS_ZERO;
3315     }
3316   if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3317   return DEC_CLASS_POS_SUBNORMAL;
3318   } /* decNumberClass */
3319
3320 /* ------------------------------------------------------------------ */
3321 /* decNumberClassToString -- convert decClass to a string             */
3322 /*                                                                    */
3323 /*  eclass is a valid decClass                                        */
3324 /*  returns a constant string describing the class (max 13+1 chars)   */
3325 /* ------------------------------------------------------------------ */
3326 const char *decNumberClassToString(enum decClass eclass) {
3327   if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3328   if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3329   if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3330   if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3331   if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3332   if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3333   if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3334   if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3335   if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3336   if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3337   return DEC_ClassString_UN;           /* Unknown */
3338   } /* decNumberClassToString */
3339
3340 /* ------------------------------------------------------------------ */
3341 /* decNumberCopy -- copy a number                                     */
3342 /*                                                                    */
3343 /*   dest is the target decNumber                                     */
3344 /*   src  is the source decNumber                                     */
3345 /*   returns dest                                                     */
3346 /*                                                                    */
3347 /* (dest==src is allowed and is a no-op)                              */
3348 /* All fields are updated as required.  This is a utility operation,  */
3349 /* so special values are unchanged and no error is possible.          */
3350 /* ------------------------------------------------------------------ */
3351 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3352
3353   #if DECCHECK
3354   if (src==NULL) return decNumberZero(dest);
3355   #endif
3356
3357   if (dest==src) return dest;                /* no copy required */
3358
3359   /* Use explicit assignments here as structure assignment could copy */
3360   /* more than just the lsu (for small DECDPUN).  This would not affect */
3361   /* the value of the results, but could disturb test harness spill */
3362   /* checking. */
3363   dest->bits=src->bits;
3364   dest->exponent=src->exponent;
3365   dest->digits=src->digits;
3366   dest->lsu[0]=src->lsu[0];
3367   if (src->digits>DECDPUN) {                 /* more Units to come */
3368     const Unit *smsup, *s;                   /* work */
3369     Unit  *d;                                /* .. */
3370     /* memcpy for the remaining Units would be safe as they cannot */
3371     /* overlap.  However, this explicit loop is faster in short cases. */
3372     d=dest->lsu+1;                           /* -> first destination */
3373     smsup=src->lsu+D2U(src->digits);         /* -> source msu+1 */
3374     for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3375     }
3376   return dest;
3377   } /* decNumberCopy */
3378
3379 /* ------------------------------------------------------------------ */
3380 /* decNumberCopyAbs -- quiet absolute value operator                  */
3381 /*                                                                    */
3382 /*   This sets C = abs(A)                                             */
3383 /*                                                                    */
3384 /*   res is C, the result.  C may be A                                */
3385 /*   rhs is A                                                         */
3386 /*                                                                    */
3387 /* C must have space for set->digits digits.                          */
3388 /* No exception or error can occur; this is a quiet bitwise operation.*/
3389 /* See also decNumberAbs for a checking version of this.              */
3390 /* ------------------------------------------------------------------ */
3391 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3392   #if DECCHECK
3393   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3394   #endif
3395   decNumberCopy(res, rhs);
3396   res->bits&=~DECNEG;                   /* turn off sign */
3397   return res;
3398   } /* decNumberCopyAbs */
3399
3400 /* ------------------------------------------------------------------ */
3401 /* decNumberCopyNegate -- quiet negate value operator                 */
3402 /*                                                                    */
3403 /*   This sets C = negate(A)                                          */
3404 /*                                                                    */
3405 /*   res is C, the result.  C may be A                                */
3406 /*   rhs is A                                                         */
3407 /*                                                                    */
3408 /* C must have space for set->digits digits.                          */
3409 /* No exception or error can occur; this is a quiet bitwise operation.*/
3410 /* See also decNumberMinus for a checking version of this.            */
3411 /* ------------------------------------------------------------------ */
3412 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3413   #if DECCHECK
3414   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3415   #endif
3416   decNumberCopy(res, rhs);
3417   res->bits^=DECNEG;                    /* invert the sign */
3418   return res;
3419   } /* decNumberCopyNegate */
3420
3421 /* ------------------------------------------------------------------ */
3422 /* decNumberCopySign -- quiet copy and set sign operator              */
3423 /*                                                                    */
3424 /*   This sets C = A with the sign of B                               */
3425 /*                                                                    */
3426 /*   res is C, the result.  C may be A                                */
3427 /*   lhs is A                                                         */
3428 /*   rhs is B                                                         */
3429 /*                                                                    */
3430 /* C must have space for set->digits digits.                          */
3431 /* No exception or error can occur; this is a quiet bitwise operation.*/
3432 /* ------------------------------------------------------------------ */
3433 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3434                               const decNumber *rhs) {
3435   uByte sign;                           /* rhs sign */
3436   #if DECCHECK
3437   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3438   #endif
3439   sign=rhs->bits & DECNEG;              /* save sign bit */
3440   decNumberCopy(res, lhs);
3441   res->bits&=~DECNEG;                   /* clear the sign */
3442   res->bits|=sign;                      /* set from rhs */
3443   return res;
3444   } /* decNumberCopySign */
3445
3446 /* ------------------------------------------------------------------ */
3447 /* decNumberGetBCD -- get the coefficient in BCD8                     */
3448 /*   dn is the source decNumber                                       */
3449 /*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3450 /*     most-significant at offset 0                                   */
3451 /*   returns bcd                                                      */
3452 /*                                                                    */
3453 /* bcd must have at least dn->digits bytes.  No error is possible; if */
3454 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3455 /* ------------------------------------------------------------------ */
3456 uByte * decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3457   uByte *ub=bcd+dn->digits-1;      /* -> lsd */
3458   const Unit *up=dn->lsu;          /* Unit pointer, -> lsu */
3459
3460   #if DECDPUN==1                   /* trivial simple copy */
3461     for (; ub>=bcd; ub--, up++) *ub=*up;
3462   #else                            /* chopping needed */
3463     uInt u=*up;                    /* work */
3464     uInt cut=DECDPUN;              /* downcounter through unit */
3465     for (; ub>=bcd; ub--) {
3466       *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here] */
3467       u=u/10;
3468       cut--;
3469       if (cut>0) continue;         /* more in this unit */
3470       up++;
3471       u=*up;
3472       cut=DECDPUN;
3473       }
3474   #endif
3475   return bcd;
3476   } /* decNumberGetBCD */
3477
3478 /* ------------------------------------------------------------------ */
3479 /* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3480 /*   dn is the target decNumber                                       */
3481 /*   bcd is the uInt array that will source n BCD bytes, most-        */
3482 /*     significant at offset 0                                        */
3483 /*   n is the number of digits in the source BCD array (bcd)          */
3484 /*   returns dn                                                       */
3485 /*                                                                    */
3486 /* dn must have space for at least n digits.  No error is possible;   */
3487 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3488 /* and bcd[0] zero.                                                   */
3489 /* ------------------------------------------------------------------ */
3490 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3491   Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer] */
3492   const uByte *ub=bcd;                  /* -> source msd */
3493
3494   #if DECDPUN==1                        /* trivial simple copy */
3495     for (; ub<bcd+n; ub++, up--) *up=*ub;
3496   #else                                 /* some assembly needed */
3497     /* calculate how many digits in msu, and hence first cut */
3498     Int cut=MSUDIGITS(n);               /* [faster than remainder] */
3499     for (;up>=dn->lsu; up--) {          /* each Unit from msu */
3500       *up=0;                            /* will take <=DECDPUN digits */
3501       for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3502       cut=DECDPUN;                      /* next Unit has all digits */
3503       }
3504   #endif
3505   dn->digits=n;                         /* set digit count */
3506   return dn;
3507   } /* decNumberSetBCD */
3508
3509 /* ------------------------------------------------------------------ */
3510 /* decNumberIsNormal -- test normality of a decNumber                 */
3511 /*   dn is the decNumber to test                                      */
3512 /*   set is the context to use for Emin                               */
3513 /*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3514 /* ------------------------------------------------------------------ */
3515 Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3516   Int ae;                               /* adjusted exponent */
3517   #if DECCHECK
3518   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3519   #endif
3520
3521   if (decNumberIsSpecial(dn)) return 0; /* not finite */
3522   if (decNumberIsZero(dn)) return 0;    /* not non-zero */
3523
3524   ae=dn->exponent+dn->digits-1;         /* adjusted exponent */
3525   if (ae<set->emin) return 0;           /* is subnormal */
3526   return 1;
3527   } /* decNumberIsNormal */
3528
3529 /* ------------------------------------------------------------------ */
3530 /* decNumberIsSubnormal -- test subnormality of a decNumber           */
3531 /*   dn is the decNumber to test                                      */
3532 /*   set is the context to use for Emin                               */
3533 /*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3534 /* ------------------------------------------------------------------ */
3535 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3536   Int ae;                               /* adjusted exponent */
3537   #if DECCHECK
3538   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3539   #endif
3540
3541   if (decNumberIsSpecial(dn)) return 0; /* not finite */
3542   if (decNumberIsZero(dn)) return 0;    /* not non-zero */
3543
3544   ae=dn->exponent+dn->digits-1;         /* adjusted exponent */
3545   if (ae<set->emin) return 1;           /* is subnormal */
3546   return 0;
3547   } /* decNumberIsSubnormal */
3548
3549 /* ------------------------------------------------------------------ */
3550 /* decNumberTrim -- remove insignificant zeros                        */
3551 /*                                                                    */
3552 /*   dn is the number to trim                                         */
3553 /*   returns dn                                                       */
3554 /*                                                                    */
3555 /* All fields are updated as required.  This is a utility operation,  */
3556 /* so special values are unchanged and no error is possible.  The     */
3557 /* zeros are removed unconditionally.                                 */
3558 /* ------------------------------------------------------------------ */
3559 decNumber * decNumberTrim(decNumber *dn) {
3560   Int  dropped;                    /* work */
3561   decContext set;                  /* .. */
3562   #if DECCHECK
3563   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3564   #endif
3565   decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0 */
3566   return decTrim(dn, &set, 0, 1, &dropped);
3567   } /* decNumberTrim */
3568
3569 /* ------------------------------------------------------------------ */
3570 /* decNumberVersion -- return the name and version of this module     */
3571 /*                                                                    */
3572 /* No error is possible.                                              */
3573 /* ------------------------------------------------------------------ */
3574 const char * decNumberVersion(void) {
3575   return DECVERSION;
3576   } /* decNumberVersion */
3577
3578 /* ------------------------------------------------------------------ */
3579 /* decNumberZero -- set a number to 0                                 */
3580 /*                                                                    */
3581 /*   dn is the number to set, with space for one digit                */
3582 /*   returns dn                                                       */
3583 /*                                                                    */
3584 /* No error is possible.                                              */
3585 /* ------------------------------------------------------------------ */
3586 /* Memset is not used as it is much slower in some environments. */
3587 decNumber * decNumberZero(decNumber *dn) {
3588
3589   #if DECCHECK
3590   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3591   #endif
3592
3593   dn->bits=0;
3594   dn->exponent=0;
3595   dn->digits=1;
3596   dn->lsu[0]=0;
3597   return dn;
3598   } /* decNumberZero */
3599
3600 /* ================================================================== */
3601 /* Local routines                                                     */
3602 /* ================================================================== */
3603
3604 /* ------------------------------------------------------------------ */
3605 /* decToString -- lay out a number into a string                      */
3606 /*                                                                    */
3607 /*   dn     is the number to lay out                                  */
3608 /*   string is where to lay out the number                            */
3609 /*   eng    is 1 if Engineering, 0 if Scientific                      */
3610 /*                                                                    */
3611 /* string must be at least dn->digits+14 characters long              */
3612 /* No error is possible.                                              */
3613 /*                                                                    */
3614 /* Note that this routine can generate a -0 or 0.000.  These are      */
3615 /* never generated in subset to-number or arithmetic, but can occur   */
3616 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3617 /* ------------------------------------------------------------------ */
3618 /* If DECCHECK is enabled the string "?" is returned if a number is */
3619 /* invalid. */
3620 static void decToString(const decNumber *dn, char *string, Flag eng) {
3621   Int exp=dn->exponent;       /* local copy */
3622   Int e;                      /* E-part value */
3623   Int pre;                    /* digits before the '.' */
3624   Int cut;                    /* for counting digits in a Unit */
3625   char *c=string;             /* work [output pointer] */
3626   const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3627   uInt u, pow;                /* work */
3628
3629   #if DECCHECK
3630   if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3631     strcpy(string, "?");
3632     return;}
3633   #endif
3634
3635   if (decNumberIsNegative(dn)) {   /* Negatives get a minus */
3636     *c='-';
3637     c++;
3638     }
3639   if (dn->bits&DECSPECIAL) {       /* Is a special value */
3640     if (decNumberIsInfinite(dn)) {
3641       strcpy(c,   "Inf");
3642       strcpy(c+3, "inity");
3643       return;}
3644     /* a NaN */
3645     if (dn->bits&DECSNAN) {        /* signalling NaN */
3646       *c='s';
3647       c++;
3648       }
3649     strcpy(c, "NaN");
3650     c+=3;                          /* step past */
3651     /* if not a clean non-zero coefficient, that's all there is in a */
3652     /* NaN string */
3653     if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3654     /* [drop through to add integer] */
3655     }
3656
3657   /* calculate how many digits in msu, and hence first cut */
3658   cut=MSUDIGITS(dn->digits);       /* [faster than remainder] */
3659   cut--;                           /* power of ten for digit */
3660
3661   if (exp==0) {                    /* simple integer [common fastpath] */
3662     for (;up>=dn->lsu; up--) {     /* each Unit from msu */
3663       u=*up;                       /* contains DECDPUN digits to lay out */
3664       for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3665       cut=DECDPUN-1;               /* next Unit has all digits */
3666       }
3667     *c='\0';                       /* terminate the string */
3668     return;}
3669
3670   /* non-0 exponent -- assume plain form */
3671   pre=dn->digits+exp;              /* digits before '.' */
3672   e=0;                             /* no E */
3673   if ((exp>0) || (pre<-5)) {       /* need exponential form */
3674     e=exp+dn->digits-1;            /* calculate E value */
3675     pre=1;                         /* assume one digit before '.' */
3676     if (eng && (e!=0)) {           /* engineering: may need to adjust */
3677       Int adj;                     /* adjustment */
3678       /* The C remainder operator is undefined for negative numbers, so */
3679       /* a positive remainder calculation must be used here */
3680       if (e<0) {
3681         adj=(-e)%3;
3682         if (adj!=0) adj=3-adj;
3683         }
3684        else { /* e>0 */
3685         adj=e%3;
3686         }
3687       e=e-adj;
3688       /* if dealing with zero still produce an exponent which is a */
3689       /* multiple of three, as expected, but there will only be the */
3690       /* one zero before the E, still.  Otherwise note the padding. */
3691       if (!ISZERO(dn)) pre+=adj;
3692        else {  /* is zero */
3693         if (adj!=0) {              /* 0.00Esnn needed */
3694           e=e+3;
3695           pre=-(2-adj);
3696           }
3697         } /* zero */
3698       } /* eng */
3699     } /* need exponent */
3700
3701   /* lay out the digits of the coefficient, adding 0s and . as needed */
3702   u=*up;
3703   if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form */
3704     Int n=pre;
3705     for (; pre>0; pre--, c++, cut--) {
3706       if (cut<0) {                 /* need new Unit */
3707         if (up==dn->lsu) break;    /* out of input digits (pre>digits) */
3708         up--;
3709         cut=DECDPUN-1;
3710         u=*up;
3711         }
3712       TODIGIT(u, cut, c, pow);
3713       }
3714     if (n<dn->digits) {            /* more to come, after '.' */
3715       *c='.'; c++;
3716       for (;; c++, cut--) {
3717         if (cut<0) {               /* need new Unit */
3718           if (up==dn->lsu) break;  /* out of input digits */
3719           up--;
3720           cut=DECDPUN-1;
3721           u=*up;
3722           }
3723         TODIGIT(u, cut, c, pow);
3724         }
3725       }
3726      else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3727     }
3728    else {                          /* 0.xxx or 0.000xxx form */
3729     *c='0'; c++;
3730     *c='.'; c++;
3731     for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.' */
3732     for (; ; c++, cut--) {
3733       if (cut<0) {                 /* need new Unit */
3734         if (up==dn->lsu) break;    /* out of input digits */
3735         up--;
3736         cut=DECDPUN-1;
3737         u=*up;
3738         }
3739       TODIGIT(u, cut, c, pow);
3740       }
3741     }
3742
3743   /* Finally add the E-part, if needed.  It will never be 0, has a
3744      base maximum and minimum of +999999999 through -999999999, but
3745      could range down to -1999999998 for anormal numbers */
3746   if (e!=0) {
3747     Flag had=0;               /* 1=had non-zero */
3748     *c='E'; c++;
3749     *c='+'; c++;              /* assume positive */
3750     u=e;                      /* .. */
3751     if (e<0) {
3752       *(c-1)='-';             /* oops, need - */
3753       u=-e;                   /* uInt, please */
3754       }
3755     /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3756     for (cut=9; cut>=0; cut--) {
3757       TODIGIT(u, cut, c, pow);
3758       if (*c=='0' && !had) continue;    /* skip leading zeros */
3759       had=1;                            /* had non-0 */
3760       c++;                              /* step for next */
3761       } /* cut */
3762     }
3763   *c='\0';          /* terminate the string (all paths) */
3764   return;
3765   } /* decToString */
3766
3767 /* ------------------------------------------------------------------ */
3768 /* decAddOp -- add/subtract operation                                 */
3769 /*                                                                    */
3770 /*   This computes C = A + B                                          */
3771 /*                                                                    */
3772 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3773 /*   lhs is A                                                         */
3774 /*   rhs is B                                                         */
3775 /*   set is the context                                               */
3776 /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3777 /*   status accumulates status for the caller                         */
3778 /*                                                                    */
3779 /* C must have space for set->digits digits.                          */
3780 /* Inexact in status must be 0 for correct Exact zero sign in result  */
3781 /* ------------------------------------------------------------------ */
3782 /* If possible, the coefficient is calculated directly into C.        */
3783 /* However, if:                                                       */
3784 /*   -- a digits+1 calculation is needed because the numbers are      */
3785 /*      unaligned and span more than set->digits digits               */
3786 /*   -- a carry to digits+1 digits looks possible                     */
3787 /*   -- C is the same as A or B, and the result would destructively   */
3788 /*      overlap the A or B coefficient                                */
3789 /* then the result must be calculated into a temporary buffer.  In    */
3790 /* this case a local (stack) buffer is used if possible, and only if  */
3791 /* too long for that does malloc become the final resort.             */
3792 /*                                                                    */
3793 /* Misalignment is handled as follows:                                */
3794 /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3795 /*   BPad: Apply the padding by a combination of shifting (whole      */
3796 /*         units) and multiplication (part units).                    */
3797 /*                                                                    */
3798 /* Addition, especially x=x+1, is speed-critical.                     */
3799 /* The static buffer is larger than might be expected to allow for    */
3800 /* calls from higher-level funtions (notable exp).                    */
3801 /* ------------------------------------------------------------------ */
3802 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3803                             const decNumber *rhs, decContext *set,
3804                             uByte negate, uInt *status) {
3805   #if DECSUBSET
3806   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
3807   decNumber *allocrhs=NULL;        /* .., rhs */
3808   #endif
3809   Int   rhsshift;                  /* working shift (in Units) */
3810   Int   maxdigits;                 /* longest logical length */
3811   Int   mult;                      /* multiplier */
3812   Int   residue;                   /* rounding accumulator */
3813   uByte bits;                      /* result bits */
3814   Flag  diffsign;                  /* non-0 if arguments have different sign */
3815   Unit  *acc;                      /* accumulator for result */
3816   Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3817                                    /* allocations when called from */
3818                                    /* other operations, notable exp] */
3819   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated */
3820   Int   reqdigits=set->digits;     /* local copy; requested DIGITS */
3821   Int   padding;                   /* work */
3822
3823   #if DECCHECK
3824   if (decCheckOperands(res, lhs, rhs, set)) return res;
3825   #endif
3826
3827   do {                             /* protect allocated storage */
3828     #if DECSUBSET
3829     if (!set->extended) {
3830       /* reduce operands and set lostDigits status, as needed */
3831       if (lhs->digits>reqdigits) {
3832         alloclhs=decRoundOperand(lhs, set, status);
3833         if (alloclhs==NULL) break;
3834         lhs=alloclhs;
3835         }
3836       if (rhs->digits>reqdigits) {
3837         allocrhs=decRoundOperand(rhs, set, status);
3838         if (allocrhs==NULL) break;
3839         rhs=allocrhs;
3840         }
3841       }
3842     #endif
3843     /* [following code does not require input rounding] */
3844
3845     /* note whether signs differ [used all paths] */
3846     diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3847
3848     /* handle infinities and NaNs */
3849     if (SPECIALARGS) {                  /* a special bit set */
3850       if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN */
3851         decNaNs(res, lhs, rhs, set, status);
3852        else { /* one or two infinities */
3853         if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3854           /* two infinities with different signs is invalid */
3855           if (decNumberIsInfinite(rhs) && diffsign) {
3856             *status|=DEC_Invalid_operation;
3857             break;
3858             }
3859           bits=lhs->bits & DECNEG;      /* get sign from LHS */
3860           }
3861          else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3862         bits|=DECINF;
3863         decNumberZero(res);
3864         res->bits=bits;                 /* set +/- infinity */
3865         } /* an infinity */
3866       break;
3867       }
3868
3869     /* Quick exit for add 0s; return the non-0, modified as need be */
3870     if (ISZERO(lhs)) {
3871       Int adjust;                       /* work */
3872       Int lexp=lhs->exponent;           /* save in case LHS==RES */
3873       bits=lhs->bits;                   /* .. */
3874       residue=0;                        /* clear accumulator */
3875       decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3876       res->bits^=negate;                /* flip if rhs was negated */
3877       #if DECSUBSET
3878       if (set->extended) {              /* exponents on zeros count */
3879       #endif
3880         /* exponent will be the lower of the two */
3881         adjust=lexp-res->exponent;      /* adjustment needed [if -ve] */
3882         if (ISZERO(res)) {              /* both 0: special IEEE 754 rules */
3883           if (adjust<0) res->exponent=lexp;  /* set exponent */
3884           /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3885           if (diffsign) {
3886             if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3887              else res->bits=DECNEG;     /* preserve 0 sign */
3888             }
3889           }
3890          else { /* non-0 res */
3891           if (adjust<0) {     /* 0-padding needed */
3892             if ((res->digits-adjust)>set->digits) {
3893               adjust=res->digits-set->digits;     /* to fit exactly */
3894               *status|=DEC_Rounded;               /* [but exact] */
3895               }
3896             res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3897             res->exponent+=adjust;                /* set the exponent. */
3898             }
3899           } /* non-0 res */
3900       #if DECSUBSET
3901         } /* extended */
3902       #endif
3903       decFinish(res, set, &residue, status);      /* clean and finalize */
3904       break;}
3905
3906     if (ISZERO(rhs)) {                  /* [lhs is non-zero] */
3907       Int adjust;                       /* work */
3908       Int rexp=rhs->exponent;           /* save in case RHS==RES */
3909       bits=rhs->bits;                   /* be clean */
3910       residue=0;                        /* clear accumulator */
3911       decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3912       #if DECSUBSET
3913       if (set->extended) {              /* exponents on zeros count */
3914       #endif
3915         /* exponent will be the lower of the two */
3916         /* [0-0 case handled above] */
3917         adjust=rexp-res->exponent;      /* adjustment needed [if -ve] */
3918         if (adjust<0) {     /* 0-padding needed */
3919           if ((res->digits-adjust)>set->digits) {
3920             adjust=res->digits-set->digits;     /* to fit exactly */
3921             *status|=DEC_Rounded;               /* [but exact] */
3922             }
3923           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3924           res->exponent+=adjust;                /* set the exponent. */
3925           }
3926       #if DECSUBSET
3927         } /* extended */
3928       #endif
3929       decFinish(res, set, &residue, status);      /* clean and finalize */
3930       break;}
3931
3932     /* [NB: both fastpath and mainpath code below assume these cases */
3933     /* (notably 0-0) have already been handled] */
3934
3935     /* calculate the padding needed to align the operands */
3936     padding=rhs->exponent-lhs->exponent;
3937
3938     /* Fastpath cases where the numbers are aligned and normal, the RHS */
3939     /* is all in one unit, no operand rounding is needed, and no carry, */
3940     /* lengthening, or borrow is needed */
3941     if (padding==0
3942         && rhs->digits<=DECDPUN
3943         && rhs->exponent>=set->emin     /* [some normals drop through] */
3944         && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3945         && rhs->digits<=reqdigits
3946         && lhs->digits<=reqdigits) {
3947       Int partial=*lhs->lsu;
3948       if (!diffsign) {                  /* adding */
3949         partial+=*rhs->lsu;
3950         if ((partial<=DECDPUNMAX)       /* result fits in unit */
3951          && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change */
3952              partial<(Int)powers[lhs->digits])) { /* .. */
3953           if (res!=lhs) decNumberCopy(res, lhs);  /* not in place */
3954           *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS] */
3955           break;
3956           }
3957         /* else drop out for careful add */
3958         }
3959        else {                           /* signs differ */
3960         partial-=*rhs->lsu;
3961         if (partial>0) { /* no borrow needed, and non-0 result */
3962           if (res!=lhs) decNumberCopy(res, lhs);  /* not in place */
3963           *res->lsu=(Unit)partial;
3964           /* this could have reduced digits [but result>0] */
3965           res->digits=decGetDigits(res->lsu, D2U(res->digits));
3966           break;
3967           }
3968         /* else drop out for careful subtract */
3969         }
3970       }
3971
3972     /* Now align (pad) the lhs or rhs so they can be added or */
3973     /* subtracted, as necessary.  If one number is much larger than */
3974     /* the other (that is, if in plain form there is a least one */
3975     /* digit between the lowest digit of one and the highest of the */
3976     /* other) padding with up to DIGITS-1 trailing zeros may be */
3977     /* needed; then apply rounding (as exotic rounding modes may be */
3978     /* affected by the residue). */
3979     rhsshift=0;               /* rhs shift to left (padding) in Units */
3980     bits=lhs->bits;           /* assume sign is that of LHS */
3981     mult=1;                   /* likely multiplier */
3982
3983     /* [if padding==0 the operands are aligned; no padding is needed] */
3984     if (padding!=0) {
3985       /* some padding needed; always pad the RHS, as any required */
3986       /* padding can then be effected by a simple combination of */
3987       /* shifts and a multiply */
3988       Flag swapped=0;
3989       if (padding<0) {                  /* LHS needs the padding */
3990         const decNumber *t;
3991         padding=-padding;               /* will be +ve */
3992         bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
3993         t=lhs; lhs=rhs; rhs=t;
3994         swapped=1;
3995         }
3996
3997       /* If, after pad, rhs would be longer than lhs by digits+1 or */
3998       /* more then lhs cannot affect the answer, except as a residue, */
3999       /* so only need to pad up to a length of DIGITS+1. */
4000       if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4001         /* The RHS is sufficient */
4002         /* for residue use the relative sign indication... */
4003         Int shift=reqdigits-rhs->digits;     /* left shift needed */
4004         residue=1;                           /* residue for rounding */
4005         if (diffsign) residue=-residue;      /* signs differ */
4006         /* copy, shortening if necessary */
4007         decCopyFit(res, rhs, set, &residue, status);
4008         /* if it was already shorter, then need to pad with zeros */
4009         if (shift>0) {
4010           res->digits=decShiftToMost(res->lsu, res->digits, shift);
4011           res->exponent-=shift;              /* adjust the exponent. */
4012           }
4013         /* flip the result sign if unswapped and rhs was negated */
4014         if (!swapped) res->bits^=negate;
4015         decFinish(res, set, &residue, status);    /* done */
4016         break;}
4017
4018       /* LHS digits may affect result */
4019       rhsshift=D2U(padding+1)-1;        /* this much by Unit shift .. */
4020       mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
4021       } /* padding needed */
4022
4023     if (diffsign) mult=-mult;           /* signs differ */
4024
4025     /* determine the longer operand */
4026     maxdigits=rhs->digits+padding;      /* virtual length of RHS */
4027     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4028
4029     /* Decide on the result buffer to use; if possible place directly */
4030     /* into result. */
4031     acc=res->lsu;                       /* assume add direct to result */
4032     /* If destructive overlap, or the number is too long, or a carry or */
4033     /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4034     /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4035     if ((maxdigits>=reqdigits)          /* is, or could be, too large */
4036      || (res==rhs && rhsshift>0)) {     /* destructive overlap */
4037       /* buffer needed, choose it; units for maxdigits digits will be */
4038       /* needed, +1 Unit for carry or borrow */
4039       Int need=D2U(maxdigits)+1;
4040       acc=accbuff;                      /* assume use local buffer */
4041       if (need*sizeof(Unit)>sizeof(accbuff)) {
4042         /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4043         allocacc=(Unit *)malloc(need*sizeof(Unit));
4044         if (allocacc==NULL) {           /* hopeless -- abandon */
4045           *status|=DEC_Insufficient_storage;
4046           break;}
4047         acc=allocacc;
4048         }
4049       }
4050
4051     res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite.. */
4052     res->exponent=lhs->exponent;        /* .. operands (even if aliased) */
4053
4054     #if DECTRACE
4055       decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4056       decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4057       printf("  :h: %ld %ld\n", rhsshift, mult);
4058     #endif
4059
4060     /* add [A+B*m] or subtract [A+B*(-m)] */
4061     res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4062                               rhs->lsu, D2U(rhs->digits),
4063                               rhsshift, acc, mult)
4064                *DECDPUN;           /* [units -> digits] */
4065     if (res->digits<0) {           /* borrowed... */
4066       res->digits=-res->digits;
4067       res->bits^=DECNEG;           /* flip the sign */
4068       }
4069     #if DECTRACE
4070       decDumpAr('+', acc, D2U(res->digits));
4071     #endif
4072
4073     /* If a buffer was used the result must be copied back, possibly */
4074     /* shortening.  (If no buffer was used then the result must have */
4075     /* fit, so can't need rounding and residue must be 0.) */
4076     residue=0;                     /* clear accumulator */
4077     if (acc!=res->lsu) {
4078       #if DECSUBSET
4079       if (set->extended) {         /* round from first significant digit */
4080       #endif
4081         /* remove leading zeros that were added due to rounding up to */
4082         /* integral Units -- before the test for rounding. */
4083         if (res->digits>reqdigits)
4084           res->digits=decGetDigits(acc, D2U(res->digits));
4085         decSetCoeff(res, set, acc, res->digits, &residue, status);
4086       #if DECSUBSET
4087         }
4088        else { /* subset arithmetic rounds from original significant digit */
4089         /* May have an underestimate.  This only occurs when both */
4090         /* numbers fit in DECDPUN digits and are padding with a */
4091         /* negative multiple (-10, -100...) and the top digit(s) become */
4092         /* 0.  (This only matters when using X3.274 rules where the */
4093         /* leading zero could be included in the rounding.) */
4094         if (res->digits<maxdigits) {
4095           *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4096           res->digits=maxdigits;
4097           }
4098          else {
4099           /* remove leading zeros that added due to rounding up to */
4100           /* integral Units (but only those in excess of the original */
4101           /* maxdigits length, unless extended) before test for rounding. */
4102           if (res->digits>reqdigits) {
4103             res->digits=decGetDigits(acc, D2U(res->digits));
4104             if (res->digits<maxdigits) res->digits=maxdigits;
4105             }
4106           }
4107         decSetCoeff(res, set, acc, res->digits, &residue, status);
4108         /* Now apply rounding if needed before removing leading zeros. */
4109         /* This is safe because subnormals are not a possibility */
4110         if (residue!=0) {
4111           decApplyRound(res, set, residue, status);
4112           residue=0;                 /* did what needed to be done */
4113           }
4114         } /* subset */
4115       #endif
4116       } /* used buffer */
4117
4118     /* strip leading zeros [these were left on in case of subset subtract] */
4119     res->digits=decGetDigits(res->lsu, D2U(res->digits));
4120
4121     /* apply checks and rounding */
4122     decFinish(res, set, &residue, status);
4123
4124     /* "When the sum of two operands with opposite signs is exactly */
4125     /* zero, the sign of that sum shall be '+' in all rounding modes */
4126     /* except round toward -Infinity, in which mode that sign shall be */
4127     /* '-'."  [Subset zeros also never have '-', set by decFinish.] */
4128     if (ISZERO(res) && diffsign
4129      #if DECSUBSET
4130      && set->extended
4131      #endif
4132      && (*status&DEC_Inexact)==0) {
4133       if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign - */
4134                                   else res->bits&=~DECNEG;  /* sign + */
4135       }
4136     } while(0);                              /* end protected */
4137
4138   if (allocacc!=NULL) free(allocacc);        /* drop any storage used */
4139   #if DECSUBSET
4140   if (allocrhs!=NULL) free(allocrhs);        /* .. */
4141   if (alloclhs!=NULL) free(alloclhs);        /* .. */
4142   #endif
4143   return res;
4144   } /* decAddOp */
4145
4146 /* ------------------------------------------------------------------ */
4147 /* decDivideOp -- division operation                                  */
4148 /*                                                                    */
4149 /*  This routine performs the calculations for all four division      */
4150 /*  operators (divide, divideInteger, remainder, remainderNear).      */
4151 /*                                                                    */
4152 /*  C=A op B                                                          */
4153 /*                                                                    */
4154 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4155 /*   lhs is A                                                         */
4156 /*   rhs is B                                                         */
4157 /*   set is the context                                               */
4158 /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4159 /*   status is the usual accumulator                                  */
4160 /*                                                                    */
4161 /* C must have space for set->digits digits.                          */
4162 /*                                                                    */
4163 /* ------------------------------------------------------------------ */
4164 /*   The underlying algorithm of this routine is the same as in the   */
4165 /*   1981 S/370 implementation, that is, non-restoring long division  */
4166 /*   with bi-unit (rather than bi-digit) estimation for each unit     */
4167 /*   multiplier.  In this pseudocode overview, complications for the  */
4168 /*   Remainder operators and division residues for exact rounding are */
4169 /*   omitted for clarity.                                             */
4170 /*                                                                    */
4171 /*     Prepare operands and handle special values                     */
4172 /*     Test for x/0 and then 0/x                                      */
4173 /*     Exp =Exp1 - Exp2                                               */
4174 /*     Exp =Exp +len(var1) -len(var2)                                 */
4175 /*     Sign=Sign1 * Sign2                                             */
4176 /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4177 /*     Pad Var2 to same length as Var1                                */
4178 /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4179 /*     have=0                                                         */
4180 /*     Do until (have=digits+1 OR residue=0)                          */
4181 /*       if exp<0 then if integer divide/residue then leave           */
4182 /*       this_unit=0                                                  */
4183 /*       Do forever                                                   */
4184 /*          compare numbers                                           */
4185 /*          if <0 then leave inner_loop                               */
4186 /*          if =0 then (* quick exit without subtract *) do           */
4187 /*             this_unit=this_unit+1; output this_unit                */
4188 /*             leave outer_loop; end                                  */
4189 /*          Compare lengths of numbers (mantissae):                   */
4190 /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4191 /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4192 /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4193 /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4194 /*          if mult=0 then mult=1                                     */
4195 /*          this_unit=this_unit+mult                                  */
4196 /*          subtract                                                  */
4197 /*          end inner_loop                                            */
4198 /*        if have\=0 | this_unit\=0 then do                           */
4199 /*          output this_unit                                          */
4200 /*          have=have+1; end                                          */
4201 /*        var2=var2/10                                                */
4202 /*        exp=exp-1                                                   */
4203 /*        end outer_loop                                              */
4204 /*     exp=exp+1   -- set the proper exponent                         */
4205 /*     if have=0 then generate answer=0                               */
4206 /*     Return (Result is defined by Var1)                             */
4207 /*                                                                    */
4208 /* ------------------------------------------------------------------ */
4209 /* Two working buffers are needed during the division; one (digits+   */
4210 /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4211 /* long subtractions.  These are acc and var1 respectively.           */
4212 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4213 /* The static buffers may be larger than might be expected to allow   */
4214 /* for calls from higher-level funtions (notable exp).                */
4215 /* ------------------------------------------------------------------ */
4216 static decNumber * decDivideOp(decNumber *res,
4217                                const decNumber *lhs, const decNumber *rhs,
4218                                decContext *set, Flag op, uInt *status) {
4219   #if DECSUBSET
4220   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
4221   decNumber *allocrhs=NULL;        /* .., rhs */
4222   #endif
4223   Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4224   Unit  *acc=accbuff;              /* -> accumulator array for result */
4225   Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated */
4226   Unit  *accnext;                  /* -> where next digit will go */
4227   Int   acclength;                 /* length of acc needed [Units] */
4228   Int   accunits;                  /* count of units accumulated */
4229   Int   accdigits;                 /* count of digits accumulated */
4230
4231   Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  /* buffer for var1 */
4232   Unit  *var1=varbuff;             /* -> var1 array for long subtraction */
4233   Unit  *varalloc=NULL;            /* -> allocated buffer, iff used */
4234   Unit  *msu1;                     /* -> msu of var1 */
4235
4236   const Unit *var2;                /* -> var2 array */
4237   const Unit *msu2;                /* -> msu of var2 */
4238   Int   msu2plus;                  /* msu2 plus one [does not vary] */
4239   eInt  msu2pair;                  /* msu2 pair plus one [does not vary] */
4240
4241   Int   var1units, var2units;      /* actual lengths */
4242   Int   var2ulen;                  /* logical length (units) */
4243   Int   var1initpad=0;             /* var1 initial padding (digits) */
4244   Int   maxdigits;                 /* longest LHS or required acc length */
4245   Int   mult;                      /* multiplier for subtraction */
4246   Unit  thisunit;                  /* current unit being accumulated */
4247   Int   residue;                   /* for rounding */
4248   Int   reqdigits=set->digits;     /* requested DIGITS */
4249   Int   exponent;                  /* working exponent */
4250   Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded */
4251   uByte bits;                      /* working sign */
4252   Unit  *target;                   /* work */
4253   const Unit *source;              /* .. */
4254   uInt  const *pow;                /* .. */
4255   Int   shift, cut;                /* .. */
4256   #if DECSUBSET
4257   Int   dropped;                   /* work */
4258   #endif
4259
4260   #if DECCHECK
4261   if (decCheckOperands(res, lhs, rhs, set)) return res;
4262   #endif
4263
4264   do {                             /* protect allocated storage */
4265     #if DECSUBSET
4266     if (!set->extended) {
4267       /* reduce operands and set lostDigits status, as needed */
4268       if (lhs->digits>reqdigits) {
4269         alloclhs=decRoundOperand(lhs, set, status);
4270         if (alloclhs==NULL) break;
4271         lhs=alloclhs;
4272         }
4273       if (rhs->digits>reqdigits) {
4274         allocrhs=decRoundOperand(rhs, set, status);
4275         if (allocrhs==NULL) break;
4276         rhs=allocrhs;
4277         }
4278       }
4279     #endif
4280     /* [following code does not require input rounding] */
4281
4282     bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions */
4283
4284     /* handle infinities and NaNs */
4285     if (SPECIALARGS) {                  /* a special bit set */
4286       if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4287         decNaNs(res, lhs, rhs, set, status);
4288         break;
4289         }
4290       /* one or two infinities */
4291       if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite */
4292         if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4293             op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4294           *status|=DEC_Invalid_operation;
4295           break;
4296           }
4297         /* [Note that infinity/0 raises no exceptions] */
4298         decNumberZero(res);
4299         res->bits=bits|DECINF;          /* set +/- infinity */
4300         break;
4301         }
4302        else {                           /* RHS (divisor) is infinite */
4303         residue=0;
4304         if (op&(REMAINDER|REMNEAR)) {
4305           /* result is [finished clone of] lhs */
4306           decCopyFit(res, lhs, set, &residue, status);
4307           }
4308          else {  /* a division */
4309           decNumberZero(res);
4310           res->bits=bits;               /* set +/- zero */
4311           /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result */
4312           /* is a 0 with infinitely negative exponent, clamped to minimum */
4313           if (op&DIVIDE) {
4314             res->exponent=set->emin-set->digits+1;
4315             *status|=DEC_Clamped;
4316             }
4317           }
4318         decFinish(res, set, &residue, status);
4319         break;
4320         }
4321       }
4322
4323     /* handle 0 rhs (x/0) */
4324     if (ISZERO(rhs)) {                  /* x/0 is always exceptional */
4325       if (ISZERO(lhs)) {
4326         decNumberZero(res);             /* [after lhs test] */
4327         *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4328         }
4329        else {
4330         decNumberZero(res);
4331         if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4332          else {
4333           *status|=DEC_Division_by_zero; /* x/0 */
4334           res->bits=bits|DECINF;         /* .. is +/- Infinity */
4335           }
4336         }
4337       break;}
4338
4339     /* handle 0 lhs (0/x) */
4340     if (ISZERO(lhs)) {                  /* 0/x [x!=0] */
4341       #if DECSUBSET
4342       if (!set->extended) decNumberZero(res);
4343        else {
4344       #endif
4345         if (op&DIVIDE) {
4346           residue=0;
4347           exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4348           decNumberCopy(res, lhs);      /* [zeros always fit] */
4349           res->bits=bits;               /* sign as computed */
4350           res->exponent=exponent;       /* exponent, too */
4351           decFinalize(res, set, &residue, status);   /* check exponent */
4352           }
4353          else if (op&DIVIDEINT) {
4354           decNumberZero(res);           /* integer 0 */
4355           res->bits=bits;               /* sign as computed */
4356           }
4357          else {                         /* a remainder */
4358           exponent=rhs->exponent;       /* [save in case overwrite] */
4359           decNumberCopy(res, lhs);      /* [zeros always fit] */
4360           if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4361           }
4362       #if DECSUBSET
4363         }
4364       #endif
4365       break;}
4366
4367     /* Precalculate exponent.  This starts off adjusted (and hence fits */
4368     /* in 31 bits) and becomes the usual unadjusted exponent as the */
4369     /* division proceeds.  The order of evaluation is important, here, */
4370     /* to avoid wrap. */
4371     exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4372
4373     /* If the working exponent is -ve, then some quick exits are */
4374     /* possible because the quotient is known to be <1 */
4375     /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4376     if (exponent<0 && !(op==DIVIDE)) {
4377       if (op&DIVIDEINT) {
4378         decNumberZero(res);                  /* integer part is 0 */
4379         #if DECSUBSET
4380         if (set->extended)
4381         #endif
4382           res->bits=bits;                    /* set +/- zero */
4383         break;}
4384       /* fastpath remainders so long as the lhs has the smaller */
4385       /* (or equal) exponent */
4386       if (lhs->exponent<=rhs->exponent) {
4387         if (op&REMAINDER || exponent<-1) {
4388           /* It is REMAINDER or safe REMNEAR; result is [finished */
4389           /* clone of] lhs  (r = x - 0*y) */
4390           residue=0;
4391           decCopyFit(res, lhs, set, &residue, status);
4392           decFinish(res, set, &residue, status);
4393           break;
4394           }
4395         /* [unsafe REMNEAR drops through] */
4396         }
4397       } /* fastpaths */
4398
4399     /* Long (slow) division is needed; roll up the sleeves... */
4400
4401     /* The accumulator will hold the quotient of the division. */
4402     /* If it needs to be too long for stack storage, then allocate. */
4403     acclength=D2U(reqdigits+DECDPUN);   /* in Units */
4404     if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4405       /* printf("malloc dvacc %ld units\n", acclength); */
4406       allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4407       if (allocacc==NULL) {             /* hopeless -- abandon */
4408         *status|=DEC_Insufficient_storage;
4409         break;}
4410       acc=allocacc;                     /* use the allocated space */
4411       }
4412
4413     /* var1 is the padded LHS ready for subtractions. */
4414     /* If it needs to be too long for stack storage, then allocate. */
4415     /* The maximum units needed for var1 (long subtraction) is: */
4416     /* Enough for */
4417     /*     (rhs->digits+reqdigits-1) -- to allow full slide to right */
4418     /* or  (lhs->digits)             -- to allow for long lhs */
4419     /* whichever is larger */
4420     /*   +1                -- for rounding of slide to right */
4421     /*   +1                -- for leading 0s */
4422     /*   +1                -- for pre-adjust if a remainder or DIVIDEINT */
4423     /* [Note: unused units do not participate in decUnitAddSub data] */
4424     maxdigits=rhs->digits+reqdigits-1;
4425     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4426     var1units=D2U(maxdigits)+2;
4427     /* allocate a guard unit above msu1 for REMAINDERNEAR */
4428     if (!(op&DIVIDE)) var1units++;
4429     if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4430       /* printf("malloc dvvar %ld units\n", var1units+1); */
4431       varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4432       if (varalloc==NULL) {             /* hopeless -- abandon */
4433         *status|=DEC_Insufficient_storage;
4434         break;}
4435       var1=varalloc;                    /* use the allocated space */
4436       }
4437
4438     /* Extend the lhs and rhs to full long subtraction length.  The lhs */
4439     /* is truly extended into the var1 buffer, with 0 padding, so a */
4440     /* subtract in place is always possible.  The rhs (var2) has */
4441     /* virtual padding (implemented by decUnitAddSub). */
4442     /* One guard unit was allocated above msu1 for rem=rem+rem in */
4443     /* REMAINDERNEAR. */
4444     msu1=var1+var1units-1;              /* msu of var1 */
4445     source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4446     for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4447     for (; target>=var1; target--) *target=0;
4448
4449     /* rhs (var2) is left-aligned with var1 at the start */
4450     var2ulen=var1units;                 /* rhs logical length (units) */
4451     var2units=D2U(rhs->digits);         /* rhs actual length (units) */
4452     var2=rhs->lsu;                      /* -> rhs array */
4453     msu2=var2+var2units-1;              /* -> msu of var2 [never changes] */
4454     /* now set up the variables which will be used for estimating the */
4455     /* multiplication factor.  If these variables are not exact, add */
4456     /* 1 to make sure that the multiplier is never overestimated. */
4457     msu2plus=*msu2;                     /* it's value .. */
4458     if (var2units>1) msu2plus++;        /* .. +1 if any more */
4459     msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4460     if (var2units>1) {                  /* .. [else treat 2nd as 0] */
4461       msu2pair+=*(msu2-1);              /* .. */
4462       if (var2units>2) msu2pair++;      /* .. +1 if any more */
4463       }
4464
4465     /* The calculation is working in units, which may have leading zeros, */
4466     /* but the exponent was calculated on the assumption that they are */
4467     /* both left-aligned.  Adjust the exponent to compensate: add the */
4468     /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4469     /* [This is actually done by counting the digits and negating, as */
4470     /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4471     for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4472     for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4473
4474     /* Now, if doing an integer divide or remainder, ensure that */
4475     /* the result will be Unit-aligned.  To do this, shift the var1 */
4476     /* accumulator towards least if need be.  (It's much easier to */
4477     /* do this now than to reassemble the residue afterwards, if */
4478     /* doing a remainder.)  Also ensure the exponent is not negative. */
4479     if (!(op&DIVIDE)) {
4480       Unit *u;                          /* work */
4481       /* save the initial 'false' padding of var1, in digits */
4482       var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4483       /* Determine the shift to do. */
4484       if (exponent<0) cut=-exponent;
4485        else cut=DECDPUN-exponent%DECDPUN;
4486       decShiftToLeast(var1, var1units, cut);
4487       exponent+=cut;                    /* maintain numerical value */
4488       var1initpad-=cut;                 /* .. and reduce padding */
4489       /* clean any most-significant units which were just emptied */
4490       for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4491       } /* align */
4492      else { /* is DIVIDE */
4493       maxexponent=lhs->exponent-rhs->exponent;    /* save */
4494       /* optimization: if the first iteration will just produce 0, */
4495       /* preadjust to skip it [valid for DIVIDE only] */
4496       if (*msu1<*msu2) {
4497         var2ulen--;                     /* shift down */
4498         exponent-=DECDPUN;              /* update the exponent */
4499         }
4500       }
4501
4502     /* ---- start the long-division loops ------------------------------ */
4503     accunits=0;                         /* no units accumulated yet */
4504     accdigits=0;                        /* .. or digits */
4505     accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1] */
4506     for (;;) {                          /* outer forever loop */
4507       thisunit=0;                       /* current unit assumed 0 */
4508       /* find the next unit */
4509       for (;;) {                        /* inner forever loop */
4510         /* strip leading zero units [from either pre-adjust or from */
4511         /* subtract last time around].  Leave at least one unit. */
4512         for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4513
4514         if (var1units<var2ulen) break;       /* var1 too low for subtract */
4515         if (var1units==var2ulen) {           /* unit-by-unit compare needed */
4516           /* compare the two numbers, from msu */
4517           const Unit *pv1, *pv2;
4518           Unit v2;                           /* units to compare */
4519           pv2=msu2;                          /* -> msu */
4520           for (pv1=msu1; ; pv1--, pv2--) {
4521             /* v1=*pv1 -- always OK */
4522             v2=0;                            /* assume in padding */
4523             if (pv2>=var2) v2=*pv2;          /* in range */
4524             if (*pv1!=v2) break;             /* no longer the same */
4525             if (pv1==var1) break;            /* done; leave pv1 as is */
4526             }
4527           /* here when all inspected or a difference seen */
4528           if (*pv1<v2) break;                /* var1 too low to subtract */
4529           if (*pv1==v2) {                    /* var1 == var2 */
4530             /* reach here if var1 and var2 are identical; subtraction */
4531             /* would increase digit by one, and the residue will be 0 so */
4532             /* the calculation is done; leave the loop with residue=0. */
4533             thisunit++;                      /* as though subtracted */
4534             *var1=0;                         /* set var1 to 0 */
4535             var1units=1;                     /* .. */
4536             break;  /* from inner */
4537             } /* var1 == var2 */
4538           /* *pv1>v2.  Prepare for real subtraction; the lengths are equal */
4539           /* Estimate the multiplier (there's always a msu1-1)... */
4540           /* Bring in two units of var2 to provide a good estimate. */
4541           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4542           } /* lengths the same */
4543          else { /* var1units > var2ulen, so subtraction is safe */
4544           /* The var2 msu is one unit towards the lsu of the var1 msu, */
4545           /* so only one unit for var2 can be used. */
4546           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4547           }
4548         if (mult==0) mult=1;                 /* must always be at least 1 */
4549         /* subtraction needed; var1 is > var2 */
4550         thisunit=(Unit)(thisunit+mult);      /* accumulate */
4551         /* subtract var1-var2, into var1; only the overlap needs */
4552         /* processing, as this is an in-place calculation */
4553         shift=var2ulen-var2units;
4554         #if DECTRACE
4555           decDumpAr('1', &var1[shift], var1units-shift);
4556           decDumpAr('2', var2, var2units);
4557           printf("m=%ld\n", -mult);
4558         #endif
4559         decUnitAddSub(&var1[shift], var1units-shift,
4560                       var2, var2units, 0,
4561                       &var1[shift], -mult);
4562         #if DECTRACE
4563           decDumpAr('#', &var1[shift], var1units-shift);
4564         #endif
4565         /* var1 now probably has leading zeros; these are removed at the */
4566         /* top of the inner loop. */
4567         } /* inner loop */
4568
4569       /* The next unit has been calculated in full; unless it's a */
4570       /* leading zero, add to acc */
4571       if (accunits!=0 || thisunit!=0) {      /* is first or non-zero */
4572         *accnext=thisunit;                   /* store in accumulator */
4573         /* account exactly for the new digits */
4574         if (accunits==0) {
4575           accdigits++;                       /* at least one */
4576           for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4577           }
4578          else accdigits+=DECDPUN;
4579         accunits++;                          /* update count */
4580         accnext--;                           /* ready for next */
4581         if (accdigits>reqdigits) break;      /* have enough digits */
4582         }
4583
4584       /* if the residue is zero, the operation is done (unless divide */
4585       /* or divideInteger and still not enough digits yet) */
4586       if (*var1==0 && var1units==1) {        /* residue is 0 */
4587         if (op&(REMAINDER|REMNEAR)) break;
4588         if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4589         /* [drop through if divideInteger] */
4590         }
4591       /* also done enough if calculating remainder or integer */
4592       /* divide and just did the last ('units') unit */
4593       if (exponent==0 && !(op&DIVIDE)) break;
4594
4595       /* to get here, var1 is less than var2, so divide var2 by the per- */
4596       /* Unit power of ten and go for the next digit */
4597       var2ulen--;                            /* shift down */
4598       exponent-=DECDPUN;                     /* update the exponent */
4599       } /* outer loop */
4600
4601     /* ---- division is complete --------------------------------------- */
4602     /* here: acc      has at least reqdigits+1 of good results (or fewer */
4603     /*                if early stop), starting at accnext+1 (its lsu) */
4604     /*       var1     has any residue at the stopping point */
4605     /*       accunits is the number of digits collected in acc */
4606     if (accunits==0) {             /* acc is 0 */
4607       accunits=1;                  /* show have a unit .. */
4608       accdigits=1;                 /* .. */
4609       *accnext=0;                  /* .. whose value is 0 */
4610       }
4611      else accnext++;               /* back to last placed */
4612     /* accnext now -> lowest unit of result */
4613
4614     residue=0;                     /* assume no residue */
4615     if (op&DIVIDE) {
4616       /* record the presence of any residue, for rounding */
4617       if (*var1!=0 || var1units>1) residue=1;
4618        else { /* no residue */
4619         /* Had an exact division; clean up spurious trailing 0s. */
4620         /* There will be at most DECDPUN-1, from the final multiply, */
4621         /* and then only if the result is non-0 (and even) and the */
4622         /* exponent is 'loose'. */
4623         #if DECDPUN>1
4624         Unit lsu=*accnext;
4625         if (!(lsu&0x01) && (lsu!=0)) {
4626           /* count the trailing zeros */
4627           Int drop=0;
4628           for (;; drop++) {    /* [will terminate because lsu!=0] */
4629             if (exponent>=maxexponent) break;     /* don't chop real 0s */
4630             #if DECDPUN<=4
4631               if ((lsu-QUOT10(lsu, drop+1)
4632                   *powers[drop+1])!=0) break;     /* found non-0 digit */
4633             #else
4634               if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit */
4635             #endif
4636             exponent++;
4637             }
4638           if (drop>0) {
4639             accunits=decShiftToLeast(accnext, accunits, drop);
4640             accdigits=decGetDigits(accnext, accunits);
4641             accunits=D2U(accdigits);
4642             /* [exponent was adjusted in the loop] */
4643             }
4644           } /* neither odd nor 0 */
4645         #endif
4646         } /* exact divide */
4647       } /* divide */
4648      else /* op!=DIVIDE */ {
4649       /* check for coefficient overflow */
4650       if (accdigits+exponent>reqdigits) {
4651         *status|=DEC_Division_impossible;
4652         break;
4653         }
4654       if (op & (REMAINDER|REMNEAR)) {
4655         /* [Here, the exponent will be 0, because var1 was adjusted */
4656         /* appropriately.] */
4657         Int postshift;                       /* work */
4658         Flag wasodd=0;                       /* integer was odd */
4659         Unit *quotlsu;                       /* for save */
4660         Int  quotdigits;                     /* .. */
4661
4662         bits=lhs->bits;                      /* remainder sign is always as lhs */
4663
4664         /* Fastpath when residue is truly 0 is worthwhile [and */
4665         /* simplifies the code below] */
4666         if (*var1==0 && var1units==1) {      /* residue is 0 */
4667           Int exp=lhs->exponent;             /* save min(exponents) */
4668           if (rhs->exponent<exp) exp=rhs->exponent;
4669           decNumberZero(res);                /* 0 coefficient */
4670           #if DECSUBSET
4671           if (set->extended)
4672           #endif
4673           res->exponent=exp;                 /* .. with proper exponent */
4674           res->bits=(uByte)(bits&DECNEG);          /* [cleaned] */
4675           decFinish(res, set, &residue, status);   /* might clamp */
4676           break;
4677           }
4678         /* note if the quotient was odd */
4679         if (*accnext & 0x01) wasodd=1;       /* acc is odd */
4680         quotlsu=accnext;                     /* save in case need to reinspect */
4681         quotdigits=accdigits;                /* .. */
4682
4683         /* treat the residue, in var1, as the value to return, via acc */
4684         /* calculate the unused zero digits.  This is the smaller of: */
4685         /*   var1 initial padding (saved above) */
4686         /*   var2 residual padding, which happens to be given by: */
4687         postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4688         /* [the 'exponent' term accounts for the shifts during divide] */
4689         if (var1initpad<postshift) postshift=var1initpad;
4690
4691         /* shift var1 the requested amount, and adjust its digits */
4692         var1units=decShiftToLeast(var1, var1units, postshift);
4693         accnext=var1;
4694         accdigits=decGetDigits(var1, var1units);
4695         accunits=D2U(accdigits);
4696
4697         exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs */
4698         if (rhs->exponent<exponent) exponent=rhs->exponent;
4699
4700         /* Now correct the result if doing remainderNear; if it */
4701         /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4702         /* the integer was odd then the result should be rem-rhs. */
4703         if (op&REMNEAR) {
4704           Int compare, tarunits;        /* work */
4705           Unit *up;                     /* .. */
4706           /* calculate remainder*2 into the var1 buffer (which has */
4707           /* 'headroom' of an extra unit and hence enough space) */
4708           /* [a dedicated 'double' loop would be faster, here] */
4709           tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4710                                  0, accnext, 1);
4711           /* decDumpAr('r', accnext, tarunits); */
4712
4713           /* Here, accnext (var1) holds tarunits Units with twice the */
4714           /* remainder's coefficient, which must now be compared to the */
4715           /* RHS.  The remainder's exponent may be smaller than the RHS's. */
4716           compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4717                                  rhs->exponent-exponent);
4718           if (compare==BADINT) {             /* deep trouble */
4719             *status|=DEC_Insufficient_storage;
4720             break;}
4721
4722           /* now restore the remainder by dividing by two; the lsu */
4723           /* is known to be even. */
4724           for (up=accnext; up<accnext+tarunits; up++) {
4725             Int half;              /* half to add to lower unit */
4726             half=*up & 0x01;
4727             *up/=2;                /* [shift] */
4728             if (!half) continue;
4729             *(up-1)+=(DECDPUNMAX+1)/2;
4730             }
4731           /* [accunits still describes the original remainder length] */
4732
4733           if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4734             Int exp, expunits, exprem;       /* work */
4735             /* This is effectively causing round-up of the quotient, */
4736             /* so if it was the rare case where it was full and all */
4737             /* nines, it would overflow and hence division-impossible */
4738             /* should be raised */
4739             Flag allnines=0;                 /* 1 if quotient all nines */
4740             if (quotdigits==reqdigits) {     /* could be borderline */
4741               for (up=quotlsu; ; up++) {
4742                 if (quotdigits>DECDPUN) {
4743                   if (*up!=DECDPUNMAX) break;/* non-nines */
4744                   }
4745                  else {                      /* this is the last Unit */
4746                   if (*up==powers[quotdigits]-1) allnines=1;
4747                   break;
4748                   }
4749                 quotdigits-=DECDPUN;         /* checked those digits */
4750                 } /* up */
4751               } /* borderline check */
4752             if (allnines) {
4753               *status|=DEC_Division_impossible;
4754               break;}
4755
4756             /* rem-rhs is needed; the sign will invert.  Again, var1 */
4757             /* can safely be used for the working Units array. */
4758             exp=rhs->exponent-exponent;      /* RHS padding needed */
4759             /* Calculate units and remainder from exponent. */
4760             expunits=exp/DECDPUN;
4761             exprem=exp%DECDPUN;
4762             /* subtract [A+B*(-m)]; the result will always be negative */
4763             accunits=-decUnitAddSub(accnext, accunits,
4764                                     rhs->lsu, D2U(rhs->digits),
4765                                     expunits, accnext, -(Int)powers[exprem]);
4766             accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4767             accunits=D2U(accdigits);    /* and recalculate the units for copy */
4768             /* [exponent is as for original remainder] */
4769             bits^=DECNEG;               /* flip the sign */
4770             }
4771           } /* REMNEAR */
4772         } /* REMAINDER or REMNEAR */
4773       } /* not DIVIDE */
4774
4775     /* Set exponent and bits */
4776     res->exponent=exponent;
4777     res->bits=(uByte)(bits&DECNEG);          /* [cleaned] */
4778
4779     /* Now the coefficient. */
4780     decSetCoeff(res, set, accnext, accdigits, &residue, status);
4781
4782     decFinish(res, set, &residue, status);   /* final cleanup */
4783
4784     #if DECSUBSET
4785     /* If a divide then strip trailing zeros if subset [after round] */
4786     if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4787     #endif
4788     } while(0);                              /* end protected */
4789
4790   if (varalloc!=NULL) free(varalloc);   /* drop any storage used */
4791   if (allocacc!=NULL) free(allocacc);   /* .. */
4792   #if DECSUBSET
4793   if (allocrhs!=NULL) free(allocrhs);   /* .. */
4794   if (alloclhs!=NULL) free(alloclhs);   /* .. */
4795   #endif
4796   return res;
4797   } /* decDivideOp */
4798
4799 /* ------------------------------------------------------------------ */
4800 /* decMultiplyOp -- multiplication operation                          */
4801 /*                                                                    */
4802 /*  This routine performs the multiplication C=A x B.                 */
4803 /*                                                                    */
4804 /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4805 /*   lhs is A                                                         */
4806 /*   rhs is B                                                         */
4807 /*   set is the context                                               */
4808 /*   status is the usual accumulator                                  */
4809 /*                                                                    */
4810 /* C must have space for set->digits digits.                          */
4811 /*                                                                    */
4812 /* ------------------------------------------------------------------ */
4813 /* 'Classic' multiplication is used rather than Karatsuba, as the     */
4814 /* latter would give only a minor improvement for the short numbers   */
4815 /* expected to be handled most (and uses much more memory).           */
4816 /*                                                                    */
4817 /* There are two major paths here: the general-purpose ('old code')   */
4818 /* path which handles all DECDPUN values, and a fastpath version      */
4819 /* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4820 /* than two calls to decUnitAddSub would be made.                     */
4821 /*                                                                    */
4822 /* The fastpath version lumps units together into 8-digit or 9-digit  */
4823 /* chunks, and also uses a lazy carry strategy to minimise expensive  */
4824 /* 64-bit divisions.  The chunks are then broken apart again into     */
4825 /* units for continuing processing.  Despite this overhead, the       */
4826 /* fastpath can speed up some 16-digit operations by 10x (and much    */
4827 /* more for higher-precision calculations).                           */
4828 /*                                                                    */
4829 /* A buffer always has to be used for the accumulator; in the         */
4830 /* fastpath, buffers are also always needed for the chunked copies of */
4831 /* of the operand coefficients.                                       */
4832 /* Static buffers are larger than needed just for multiply, to allow  */
4833 /* for calls from other operations (notably exp).                     */
4834 /* ------------------------------------------------------------------ */
4835 #define FASTMUL (DECUSE64 && DECDPUN<5)
4836 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4837                                  const decNumber *rhs, decContext *set,
4838                                  uInt *status) {
4839   Int    accunits;                 /* Units of accumulator in use */
4840   Int    exponent;                 /* work */
4841   Int    residue=0;                /* rounding residue */
4842   uByte  bits;                     /* result sign */
4843   Unit  *acc;                      /* -> accumulator Unit array */
4844   Int    needbytes;                /* size calculator */
4845   void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated */
4846   Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4847                                    /* *4 for calls from other operations) */
4848   const Unit *mer, *mermsup;       /* work */
4849   Int   madlength;                 /* Units in multiplicand */
4850   Int   shift;                     /* Units to shift multiplicand by */
4851
4852   #if FASTMUL
4853     /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4854     /* (DECDPUN is 2 or 4) then work in base 10**8 */
4855     #if DECDPUN & 1                /* odd */
4856       #define FASTBASE 1000000000  /* base */
4857       #define FASTDIGS          9  /* digits in base */
4858       #define FASTLAZY         18  /* carry resolution point [1->18] */
4859     #else
4860       #define FASTBASE  100000000
4861       #define FASTDIGS          8
4862       #define FASTLAZY       1844  /* carry resolution point [1->1844] */
4863     #endif
4864     /* three buffers are used, two for chunked copies of the operands */
4865     /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4866     /* lazy carry evaluation */
4867     uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4868     uInt  *zlhi=zlhibuff;                 /* -> lhs array */
4869     uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated */
4870     uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4871     uInt  *zrhi=zrhibuff;                 /* -> rhs array */
4872     uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated */
4873     uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4874     /* [allocacc is shared for both paths, as only one will run] */
4875     uLong *zacc=zaccbuff;          /* -> accumulator array for exact result */
4876     #if DECDPUN==1
4877     Int    zoff;                   /* accumulator offset */
4878     #endif
4879     uInt  *lip, *rip;              /* item pointers */
4880     uInt  *lmsi, *rmsi;            /* most significant items */
4881     Int    ilhs, irhs, iacc;       /* item counts in the arrays */
4882     Int    lazy;                   /* lazy carry counter */
4883     uLong  lcarry;                 /* uLong carry */
4884     uInt   carry;                  /* carry (NB not uLong) */
4885     Int    count;                  /* work */
4886     const  Unit *cup;              /* .. */
4887     Unit  *up;                     /* .. */
4888     uLong *lp;                     /* .. */
4889     Int    p;                      /* .. */
4890   #endif
4891
4892   #if DECSUBSET
4893     decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated */
4894     decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated */
4895   #endif
4896
4897   #if DECCHECK
4898   if (decCheckOperands(res, lhs, rhs, set)) return res;
4899   #endif
4900
4901   /* precalculate result sign */
4902   bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4903
4904   /* handle infinities and NaNs */
4905   if (SPECIALARGS) {               /* a special bit set */
4906     if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4907       decNaNs(res, lhs, rhs, set, status);
4908       return res;}
4909     /* one or two infinities; Infinity * 0 is invalid */
4910     if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4911       ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4912       *status|=DEC_Invalid_operation;
4913       return res;}
4914     decNumberZero(res);
4915     res->bits=bits|DECINF;         /* infinity */
4916     return res;}
4917
4918   /* For best speed, as in DMSRCN [the original Rexx numerics */
4919   /* module], use the shorter number as the multiplier (rhs) and */
4920   /* the longer as the multiplicand (lhs) to minimise the number of */
4921   /* adds (partial products) */
4922   if (lhs->digits<rhs->digits) {   /* swap... */
4923     const decNumber *hold=lhs;
4924     lhs=rhs;
4925     rhs=hold;
4926     }
4927
4928   do {                             /* protect allocated storage */
4929     #if DECSUBSET
4930     if (!set->extended) {
4931       /* reduce operands and set lostDigits status, as needed */
4932       if (lhs->digits>set->digits) {
4933         alloclhs=decRoundOperand(lhs, set, status);
4934         if (alloclhs==NULL) break;
4935         lhs=alloclhs;
4936         }
4937       if (rhs->digits>set->digits) {
4938         allocrhs=decRoundOperand(rhs, set, status);
4939         if (allocrhs==NULL) break;
4940         rhs=allocrhs;
4941         }
4942       }
4943     #endif
4944     /* [following code does not require input rounding] */
4945
4946     #if FASTMUL                    /* fastpath can be used */
4947     /* use the fast path if there are enough digits in the shorter */
4948     /* operand to make the setup and takedown worthwhile */
4949     #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls */
4950     if (rhs->digits>NEEDTWO) {     /* use fastpath... */
4951       /* calculate the number of elements in each array */
4952       ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4953       irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4954       iacc=ilhs+irhs;
4955
4956       /* allocate buffers if required, as usual */
4957       needbytes=ilhs*sizeof(uInt);
4958       if (needbytes>(Int)sizeof(zlhibuff)) {
4959         alloclhi=(uInt *)malloc(needbytes);
4960         zlhi=alloclhi;}
4961       needbytes=irhs*sizeof(uInt);
4962       if (needbytes>(Int)sizeof(zrhibuff)) {
4963         allocrhi=(uInt *)malloc(needbytes);
4964         zrhi=allocrhi;}
4965
4966       /* Allocating the accumulator space needs a special case when */
4967       /* DECDPUN=1 because when converting the accumulator to Units */
4968       /* after the multiplication each 8-byte item becomes 9 1-byte */
4969       /* units.  Therefore iacc extra bytes are needed at the front */
4970       /* (rounded up to a multiple of 8 bytes), and the uLong */
4971       /* accumulator starts offset the appropriate number of units */
4972       /* to the right to avoid overwrite during the unchunking. */
4973       needbytes=iacc*sizeof(uLong);
4974       #if DECDPUN==1
4975       zoff=(iacc+7)/8;        /* items to offset by */
4976       needbytes+=zoff*8;
4977       #endif
4978       if (needbytes>(Int)sizeof(zaccbuff)) {
4979         allocacc=(uLong *)malloc(needbytes);
4980         zacc=(uLong *)allocacc;}
4981       if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4982         *status|=DEC_Insufficient_storage;
4983         break;}
4984
4985       acc=(Unit *)zacc;       /* -> target Unit array */
4986       #if DECDPUN==1
4987       zacc+=zoff;             /* start uLong accumulator to right */
4988       #endif
4989
4990       /* assemble the chunked copies of the left and right sides */
4991       for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4992         for (p=0, *lip=0; p<FASTDIGS && count>0;
4993              p+=DECDPUN, cup++, count-=DECDPUN)
4994           *lip+=*cup*powers[p];
4995       lmsi=lip-1;     /* save -> msi */
4996       for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
4997         for (p=0, *rip=0; p<FASTDIGS && count>0;
4998              p+=DECDPUN, cup++, count-=DECDPUN)
4999           *rip+=*cup*powers[p];
5000       rmsi=rip-1;     /* save -> msi */
5001
5002       /* zero the accumulator */
5003       for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5004
5005       /* Start the multiplication */
5006       /* Resolving carries can dominate the cost of accumulating the */
5007       /* partial products, so this is only done when necessary. */
5008       /* Each uLong item in the accumulator can hold values up to */
5009       /* 2**64-1, and each partial product can be as large as */
5010       /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to */
5011       /* itself 18.4 times in a uLong without overflowing, so during */
5012       /* the main calculation resolution is carried out every 18th */
5013       /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the */
5014       /* partial products can be added to themselves 1844.6 times in */
5015       /* a uLong without overflowing, so intermediate carry */
5016       /* resolution occurs only every 14752 digits.  Hence for common */
5017       /* short numbers usually only the one final carry resolution */
5018       /* occurs. */
5019       /* (The count is set via FASTLAZY to simplify experiments to */
5020       /* measure the value of this approach: a 35% improvement on a */
5021       /* [34x34] multiply.) */
5022       lazy=FASTLAZY;                         /* carry delay count */
5023       for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs */
5024         lp=zacc+(rip-zrhi);                  /* where to add the lhs */
5025         for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
5026           *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line] */
5027           } /* lip loop */
5028         lazy--;
5029         if (lazy>0 && rip!=rmsi) continue;
5030         lazy=FASTLAZY;                       /* reset delay count */
5031         /* spin up the accumulator resolving overflows */
5032         for (lp=zacc; lp<zacc+iacc; lp++) {
5033           if (*lp<FASTBASE) continue;        /* it fits */
5034           lcarry=*lp/FASTBASE;               /* top part [slow divide] */
5035           /* lcarry can exceed 2**32-1, so check again; this check */
5036           /* and occasional extra divide (slow) is well worth it, as */
5037           /* it allows FASTLAZY to be increased to 18 rather than 4 */
5038           /* in the FASTDIGS=9 case */
5039           if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual] */
5040            else { /* two-place carry [fairly rare] */
5041             uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part */
5042             *(lp+2)+=carry2;                        /* add to item+2 */
5043             *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5044             carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5045             }
5046           *(lp+1)+=carry;                    /* add to item above [inline] */
5047           *lp-=((uLong)FASTBASE*carry);      /* [inline] */
5048           } /* carry resolution */
5049         } /* rip loop */
5050
5051       /* The multiplication is complete; time to convert back into */
5052       /* units.  This can be done in-place in the accumulator and in */
5053       /* 32-bit operations, because carries were resolved after the */
5054       /* final add.  This needs N-1 divides and multiplies for */
5055       /* each item in the accumulator (which will become up to N */
5056       /* units, where 2<=N<=9). */
5057       for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5058         uInt item=(uInt)*lp;                 /* decapitate to uInt */
5059         for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5060           uInt part=item/(DECDPUNMAX+1);
5061           *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5062           item=part;
5063           } /* p */
5064         *up=(Unit)item; up++;                /* [final needs no division] */
5065         } /* lp */
5066       accunits=up-acc;                       /* count of units */
5067       }
5068      else { /* here to use units directly, without chunking ['old code'] */
5069     #endif
5070
5071       /* if accumulator will be too long for local storage, then allocate */
5072       acc=accbuff;                 /* -> assume buffer for accumulator */
5073       needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5074       if (needbytes>(Int)sizeof(accbuff)) {
5075         allocacc=(Unit *)malloc(needbytes);
5076         if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5077         acc=(Unit *)allocacc;                /* use the allocated space */
5078         }
5079
5080       /* Now the main long multiplication loop */
5081       /* Unlike the equivalent in the IBM Java implementation, there */
5082       /* is no advantage in calculating from msu to lsu.  So, do it */
5083       /* by the book, as it were. */
5084       /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5085       accunits=1;                  /* accumulator starts at '0' */
5086       *acc=0;                      /* .. (lsu=0) */
5087       shift=0;                     /* no multiplicand shift at first */
5088       madlength=D2U(lhs->digits);  /* this won't change */
5089       mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5090
5091       for (mer=rhs->lsu; mer<mermsup; mer++) {
5092         /* Here, *mer is the next Unit in the multiplier to use */
5093         /* If non-zero [optimization] add it... */
5094         if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5095                                             lhs->lsu, madlength, 0,
5096                                             &acc[shift], *mer)
5097                                             + shift;
5098          else { /* extend acc with a 0; it will be used shortly */
5099           *(acc+accunits)=0;       /* [this avoids length of <=0 later] */
5100           accunits++;
5101           }
5102         /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5103         shift++;                   /* add this for 'logical length' */
5104         } /* n */
5105     #if FASTMUL
5106       } /* unchunked units */
5107     #endif
5108     /* common end-path */
5109     #if DECTRACE
5110       decDumpAr('*', acc, accunits);         /* Show exact result */
5111     #endif
5112
5113     /* acc now contains the exact result of the multiplication, */
5114     /* possibly with a leading zero unit; build the decNumber from */
5115     /* it, noting if any residue */
5116     res->bits=bits;                          /* set sign */
5117     res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5118
5119     /* There can be a 31-bit wrap in calculating the exponent. */
5120     /* This can only happen if both input exponents are negative and */
5121     /* both their magnitudes are large.  If there was a wrap, set a */
5122     /* safe very negative exponent, from which decFinalize() will */
5123     /* raise a hard underflow shortly. */
5124     exponent=lhs->exponent+rhs->exponent;    /* calculate exponent */
5125     if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5126       exponent=-2*DECNUMMAXE;                /* force underflow */
5127     res->exponent=exponent;                  /* OK to overwrite now */
5128
5129
5130     /* Set the coefficient.  If any rounding, residue records */
5131     decSetCoeff(res, set, acc, res->digits, &residue, status);
5132     decFinish(res, set, &residue, status);   /* final cleanup */
5133     } while(0);                         /* end protected */
5134
5135   if (allocacc!=NULL) free(allocacc);   /* drop any storage used */
5136   #if DECSUBSET
5137   if (allocrhs!=NULL) free(allocrhs);   /* .. */
5138   if (alloclhs!=NULL) free(alloclhs);   /* .. */
5139   #endif
5140   #if FASTMUL
5141   if (allocrhi!=NULL) free(allocrhi);   /* .. */
5142   if (alloclhi!=NULL) free(alloclhi);   /* .. */
5143   #endif
5144   return res;
5145   } /* decMultiplyOp */
5146
5147 /* ------------------------------------------------------------------ */
5148 /* decExpOp -- effect exponentiation                                  */
5149 /*                                                                    */
5150 /*   This computes C = exp(A)                                         */
5151 /*                                                                    */
5152 /*   res is C, the result.  C may be A                                */
5153 /*   rhs is A                                                         */
5154 /*   set is the context; note that rounding mode has no effect        */
5155 /*                                                                    */
5156 /* C must have space for set->digits digits. status is updated but    */
5157 /* not set.                                                           */
5158 /*                                                                    */
5159 /* Restrictions:                                                      */
5160 /*                                                                    */
5161 /*   digits, emax, and -emin in the context must be less than         */
5162 /*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5163 /*   bounds or a zero.  This is an internal routine, so these         */
5164 /*   restrictions are contractual and not enforced.                   */
5165 /*                                                                    */
5166 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5167 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5168 /* error in rare cases.                                               */
5169 /*                                                                    */
5170 /* Finite results will always be full precision and Inexact, except   */
5171 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5172 /* ------------------------------------------------------------------ */
5173 /* This approach used here is similar to the algorithm described in   */
5174 /*                                                                    */
5175 /*   Variable Precision Exponential Function, T. E. Hull and          */
5176 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5177 /*   pp79-91, ACM, June 1986.                                         */
5178 /*                                                                    */
5179 /* with the main difference being that the iterations in the series   */
5180 /* evaluation are terminated dynamically (which does not require the  */
5181 /* extra variable-precision variables which are expensive in this     */
5182 /* context).                                                          */
5183 /*                                                                    */
5184 /* The error analysis in Hull & Abrham's paper applies except for the */
5185 /* round-off error accumulation during the series evaluation.  This   */
5186 /* code does not precalculate the number of iterations and so cannot  */
5187 /* use Horner's scheme.  Instead, the accumulation is done at double- */
5188 /* precision, which ensures that the additions of the terms are exact */
5189 /* and do not accumulate round-off (and any round-off errors in the   */
5190 /* terms themselves move 'to the right' faster than they can          */
5191 /* accumulate).  This code also extends the calculation by allowing,  */
5192 /* in the spirit of other decNumber operators, the input to be more   */
5193 /* precise than the result (the precision used is based on the more   */
5194 /* precise of the input or requested result).                         */
5195 /*                                                                    */
5196 /* Implementation notes:                                              */
5197 /*                                                                    */
5198 /* 1. This is separated out as decExpOp so it can be called from      */
5199 /*    other Mathematical functions (notably Ln) with a wider range    */
5200 /*    than normal.  In particular, it can handle the slightly wider   */
5201 /*    (double) range needed by Ln (which has to be able to calculate  */
5202 /*    exp(-x) where x can be the tiniest number (Ntiny).              */
5203 /*                                                                    */
5204 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5205 /*    iterations by appoximately a third with additional (although    */
5206 /*    diminishing) returns as the range is reduced to even smaller    */
5207 /*    fractions.  However, h (the power of 10 used to correct the     */
5208 /*    result at the end, see below) must be kept <=8 as otherwise     */
5209 /*    the final result cannot be computed.  Hence the leverage is a   */
5210 /*    sliding value (8-h), where potentially the range is reduced     */
5211 /*    more for smaller values.                                        */
5212 /*                                                                    */
5213 /*    The leverage that can be applied in this way is severely        */
5214 /*    limited by the cost of the raise-to-the power at the end,       */
5215 /*    which dominates when the number of iterations is small (less    */
5216 /*    than ten) or when rhs is short.  As an example, the adjustment  */
5217 /*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5218 /*                                                                    */
5219 /* 3. The restrictions (especially precision) could be raised with    */
5220 /*    care, but the full decNumber range seems very hard within the   */
5221 /*    32-bit limits.                                                  */
5222 /*                                                                    */
5223 /* 4. The working precisions for the static buffers are twice the     */
5224 /*    obvious size to allow for calls from decNumberPower.            */
5225 /* ------------------------------------------------------------------ */
5226 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5227                          decContext *set, uInt *status) {
5228   uInt ignore=0;                   /* working status */
5229   Int h;                           /* adjusted exponent for 0.xxxx */
5230   Int p;                           /* working precision */
5231   Int residue;                     /* rounding residue */
5232   uInt needbytes;                  /* for space calculations */
5233   const decNumber *x=rhs;          /* (may point to safe copy later) */
5234   decContext aset, tset, dset;     /* working contexts */
5235   Int comp;                        /* work */
5236
5237   /* the argument is often copied to normalize it, so (unusually) it */
5238   /* is treated like other buffers, using DECBUFFER, +1 in case */
5239   /* DECBUFFER is 0 */
5240   decNumber bufr[D2N(DECBUFFER*2+1)];
5241   decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated */
5242
5243   /* the working precision will be no more than set->digits+8+1 */
5244   /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5245   /* is 0 (and twice that for the accumulator) */
5246
5247   /* buffer for t, term (working precision plus) */
5248   decNumber buft[D2N(DECBUFFER*2+9+1)];
5249   decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated */
5250   decNumber *t=buft;               /* term */
5251   /* buffer for a, accumulator (working precision * 2), at least 9 */
5252   decNumber bufa[D2N(DECBUFFER*4+18+1)];
5253   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
5254   decNumber *a=bufa;               /* accumulator */
5255   /* decNumber for the divisor term; this needs at most 9 digits */
5256   /* and so can be fixed size [16 so can use standard context] */
5257   decNumber bufd[D2N(16)];
5258   decNumber *d=bufd;               /* divisor */
5259   decNumber numone;                /* constant 1 */
5260
5261   #if DECCHECK
5262   Int iterations=0;                /* for later sanity check */
5263   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5264   #endif
5265
5266   do {                                  /* protect allocated storage */
5267     if (SPECIALARG) {                   /* handle infinities and NaNs */
5268       if (decNumberIsInfinite(rhs)) {   /* an infinity */
5269         if (decNumberIsNegative(rhs))   /* -Infinity -> +0 */
5270           decNumberZero(res);
5271          else decNumberCopy(res, rhs);  /* +Infinity -> self */
5272         }
5273        else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5274       break;}
5275
5276     if (ISZERO(rhs)) {                  /* zeros -> exact 1 */
5277       decNumberZero(res);               /* make clean 1 */
5278       *res->lsu=1;                      /* .. */
5279       break;}                           /* [no status to set] */
5280
5281     /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5282     /* positive and negative tiny cases which will result in inexact */
5283     /* 1.  This also allows the later add-accumulate to always be */
5284     /* exact (because its length will never be more than twice the */
5285     /* working precision). */
5286     /* The comparator (tiny) needs just one digit, so use the */
5287     /* decNumber d for it (reused as the divisor, etc., below); its */
5288     /* exponent is such that if x is positive it will have */
5289     /* set->digits-1 zeros between the decimal point and the digit, */
5290     /* which is 4, and if x is negative one more zero there as the */
5291     /* more precise result will be of the form 0.9999999 rather than */
5292     /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0 */
5293     /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than */
5294     /* this then the result will be 1.000000 */
5295     decNumberZero(d);                   /* clean */
5296     *d->lsu=4;                          /* set 4 .. */
5297     d->exponent=-set->digits;           /* * 10**(-d) */
5298     if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case */
5299     comp=decCompare(d, rhs, 1);         /* signless compare */
5300     if (comp==BADINT) {
5301       *status|=DEC_Insufficient_storage;
5302       break;}
5303     if (comp>=0) {                      /* rhs < d */
5304       Int shift=set->digits-1;
5305       decNumberZero(res);               /* set 1 */
5306       *res->lsu=1;                      /* .. */
5307       res->digits=decShiftToMost(res->lsu, 1, shift);
5308       res->exponent=-shift;                  /* make 1.0000... */
5309       *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly */
5310       break;} /* tiny */
5311
5312     /* set up the context to be used for calculating a, as this is */
5313     /* used on both paths below */
5314     decContextDefault(&aset, DEC_INIT_DECIMAL64);
5315     /* accumulator bounds are as requested (could underflow) */
5316     aset.emax=set->emax;                /* usual bounds */
5317     aset.emin=set->emin;                /* .. */
5318     aset.clamp=0;                       /* and no concrete format */
5319
5320     /* calculate the adjusted (Hull & Abrham) exponent (where the */
5321     /* decimal point is just to the left of the coefficient msd) */
5322     h=rhs->exponent+rhs->digits;
5323     /* if h>8 then 10**h cannot be calculated safely; however, when */
5324     /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5325     /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5326     /* overflow (or underflow to 0) is guaranteed -- so this case can */
5327     /* be handled by simply forcing the appropriate excess */
5328     if (h>8) {                          /* overflow/underflow */
5329       /* set up here so Power call below will over or underflow to */
5330       /* zero; set accumulator to either 2 or 0.02 */
5331       /* [stack buffer for a is always big enough for this] */
5332       decNumberZero(a);
5333       *a->lsu=2;                        /* not 1 but < exp(1) */
5334       if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5335       h=8;                              /* clamp so 10**h computable */
5336       p=9;                              /* set a working precision */
5337       }
5338      else {                             /* h<=8 */
5339       Int maxlever=(rhs->digits>8?1:0);
5340       /* [could/should increase this for precisions >40 or so, too] */
5341
5342       /* if h is 8, cannot normalize to a lower upper limit because */
5343       /* the final result will not be computable (see notes above), */
5344       /* but leverage can be applied whenever h is less than 8. */
5345       /* Apply as much as possible, up to a MAXLEVER digits, which */
5346       /* sets the tradeoff against the cost of the later a**(10**h). */
5347       /* As h is increased, the working precision below also */
5348       /* increases to compensate for the "constant digits at the */
5349       /* front" effect. */
5350       Int lever=MINI(8-h, maxlever);    /* leverage attainable */
5351       Int use=-rhs->digits-lever;       /* exponent to use for RHS */
5352       h+=lever;                         /* apply leverage selected */
5353       if (h<0) {                        /* clamp */
5354         use+=h;                         /* [may end up subnormal] */
5355         h=0;
5356         }
5357       /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5358       if (rhs->exponent!=use) {
5359         decNumber *newrhs=bufr;         /* assume will fit on stack */
5360         needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5361         if (needbytes>sizeof(bufr)) {   /* need malloc space */
5362           allocrhs=(decNumber *)malloc(needbytes);
5363           if (allocrhs==NULL) {         /* hopeless -- abandon */
5364             *status|=DEC_Insufficient_storage;
5365             break;}
5366           newrhs=allocrhs;              /* use the allocated space */
5367           }
5368         decNumberCopy(newrhs, rhs);     /* copy to safe space */
5369         newrhs->exponent=use;           /* normalize; now <1 */
5370         x=newrhs;                       /* ready for use */
5371         /* decNumberShow(x); */
5372         }
5373
5374       /* Now use the usual power series to evaluate exp(x).  The */
5375       /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5376       /* third term by setting the term variable t=x, the accumulator */
5377       /* a=1, and the divisor d=2. */
5378
5379       /* First determine the working precision.  From Hull & Abrham */
5380       /* this is set->digits+h+2.  However, if x is 'over-precise' we */
5381       /* need to allow for all its digits to potentially participate */
5382       /* (consider an x where all the excess digits are 9s) so in */
5383       /* this case use x->digits+h+2 */
5384       p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8] */
5385
5386       /* a and t are variable precision, and depend on p, so space */
5387       /* must be allocated for them if necessary */
5388
5389       /* the accumulator needs to be able to hold 2p digits so that */
5390       /* the additions on the second and subsequent iterations are */
5391       /* sufficiently exact. */
5392       needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5393       if (needbytes>sizeof(bufa)) {     /* need malloc space */
5394         allocbufa=(decNumber *)malloc(needbytes);
5395         if (allocbufa==NULL) {          /* hopeless -- abandon */
5396           *status|=DEC_Insufficient_storage;
5397           break;}
5398         a=allocbufa;                    /* use the allocated space */
5399         }
5400       /* the term needs to be able to hold p digits (which is */
5401       /* guaranteed to be larger than x->digits, so the initial copy */
5402       /* is safe); it may also be used for the raise-to-power */
5403       /* calculation below, which needs an extra two digits */
5404       needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5405       if (needbytes>sizeof(buft)) {     /* need malloc space */
5406         allocbuft=(decNumber *)malloc(needbytes);
5407         if (allocbuft==NULL) {          /* hopeless -- abandon */
5408           *status|=DEC_Insufficient_storage;
5409           break;}
5410         t=allocbuft;                    /* use the allocated space */
5411         }
5412
5413       decNumberCopy(t, x);              /* term=x */
5414       decNumberZero(a); *a->lsu=1;      /* accumulator=1 */
5415       decNumberZero(d); *d->lsu=2;      /* divisor=2 */
5416       decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5417
5418       /* set up the contexts for calculating a, t, and d */
5419       decContextDefault(&tset, DEC_INIT_DECIMAL64);
5420       dset=tset;
5421       /* accumulator bounds are set above, set precision now */
5422       aset.digits=p*2;                  /* double */
5423       /* term bounds avoid any underflow or overflow */
5424       tset.digits=p;
5425       tset.emin=DEC_MIN_EMIN;           /* [emax is plenty] */
5426       /* [dset.digits=16, etc., are sufficient] */
5427
5428       /* finally ready to roll */
5429       for (;;) {
5430         #if DECCHECK
5431         iterations++;
5432         #endif
5433         /* only the status from the accumulation is interesting */
5434         /* [but it should remain unchanged after first add] */
5435         decAddOp(a, a, t, &aset, 0, status);           /* a=a+t */
5436         decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x */
5437         decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d */
5438         /* the iteration ends when the term cannot affect the result, */
5439         /* if rounded to p digits, which is when its value is smaller */
5440         /* than the accumulator by p+1 digits.  There must also be */
5441         /* full precision in a. */
5442         if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5443             && (a->digits>=p)) break;
5444         decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1 */
5445         } /* iterate */
5446
5447       #if DECCHECK
5448       /* just a sanity check; comment out test to show always */
5449       if (iterations>p+3)
5450         printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5451                (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5452       #endif
5453       } /* h<=8 */
5454
5455     /* apply postconditioning: a=a**(10**h) -- this is calculated */
5456     /* at a slightly higher precision than Hull & Abrham suggest */
5457     if (h>0) {
5458       Int seenbit=0;               /* set once a 1-bit is seen */
5459       Int i;                       /* counter */
5460       Int n=powers[h];             /* always positive */
5461       aset.digits=p+2;             /* sufficient precision */
5462       /* avoid the overhead and many extra digits of decNumberPower */
5463       /* as all that is needed is the short 'multipliers' loop; here */
5464       /* accumulate the answer into t */
5465       decNumberZero(t); *t->lsu=1; /* acc=1 */
5466       for (i=1;;i++){              /* for each bit [top bit ignored] */
5467         /* abandon if have had overflow or terminal underflow */
5468         if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5469           if (*status&DEC_Overflow || ISZERO(t)) break;}
5470         n=n<<1;                    /* move next bit to testable position */
5471         if (n<0) {                 /* top bit is set */
5472           seenbit=1;               /* OK, have a significant bit */
5473           decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5474           }
5475         if (i==31) break;          /* that was the last bit */
5476         if (!seenbit) continue;    /* no need to square 1 */
5477         decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5478         } /*i*/ /* 32 bits */
5479       /* decNumberShow(t); */
5480       a=t;                         /* and carry on using t instead of a */
5481       }
5482
5483     /* Copy and round the result to res */
5484     residue=1;                          /* indicate dirt to right .. */
5485     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0 */
5486     aset.digits=set->digits;            /* [use default rounding] */
5487     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5488     decFinish(res, set, &residue, status);       /* cleanup/set flags */
5489     } while(0);                         /* end protected */
5490
5491   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
5492   if (allocbufa!=NULL) free(allocbufa); /* .. */
5493   if (allocbuft!=NULL) free(allocbuft); /* .. */
5494   /* [status is handled by caller] */
5495   return res;
5496   } /* decExpOp */
5497
5498 /* ------------------------------------------------------------------ */
5499 /* Initial-estimate natural logarithm table                           */
5500 /*                                                                    */
5501 /*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5502 /*           The result is a 4-digit encode of the coefficient (c=the */
5503 /*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5504 /*           exponent (e=the bottom 2 bits encoding 0-3)              */
5505 /*                                                                    */
5506 /*           The resulting value is given by:                         */
5507 /*                                                                    */
5508 /*             v = -c * 10**(-e-3)                                    */
5509 /*                                                                    */
5510 /*           where e and c are extracted from entry k = LNnn[x-10]    */
5511 /*           where x is truncated (NB) into the range 10 through 99,  */
5512 /*           and then c = k>>2 and e = k&3.                           */
5513 /* ------------------------------------------------------------------ */
5514 const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5515   6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5516   5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5517  39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5518  29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5519  22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5520  15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5521  10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5522   5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5523  10130,  6046, 20055};
5524
5525 /* ------------------------------------------------------------------ */
5526 /* decLnOp -- effect natural logarithm                                */
5527 /*                                                                    */
5528 /*   This computes C = ln(A)                                          */
5529 /*                                                                    */
5530 /*   res is C, the result.  C may be A                                */
5531 /*   rhs is A                                                         */
5532 /*   set is the context; note that rounding mode has no effect        */
5533 /*                                                                    */
5534 /* C must have space for set->digits digits.                          */
5535 /*                                                                    */
5536 /* Notable cases:                                                     */
5537 /*   A<0 -> Invalid                                                   */
5538 /*   A=0 -> -Infinity (Exact)                                         */
5539 /*   A=+Infinity -> +Infinity (Exact)                                 */
5540 /*   A=1 exactly -> 0 (Exact)                                         */
5541 /*                                                                    */
5542 /* Restrictions (as for Exp):                                         */
5543 /*                                                                    */
5544 /*   digits, emax, and -emin in the context must be less than         */
5545 /*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5546 /*   bounds or a zero.  This is an internal routine, so these         */
5547 /*   restrictions are contractual and not enforced.                   */
5548 /*                                                                    */
5549 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5550 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5551 /* error in rare cases.                                               */
5552 /* ------------------------------------------------------------------ */
5553 /* The result is calculated using Newton's method, with each          */
5554 /* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5555 /* Epperson 1989.                                                     */
5556 /*                                                                    */
5557 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5558 /* This has to be calculated at the sum of the precision of x and the */
5559 /* working precision.                                                 */
5560 /*                                                                    */
5561 /* Implementation notes:                                              */
5562 /*                                                                    */
5563 /* 1. This is separated out as decLnOp so it can be called from       */
5564 /*    other Mathematical functions (e.g., Log 10) with a wider range  */
5565 /*    than normal.  In particular, it can handle the slightly wider   */
5566 /*    (+9+2) range needed by a power function.                        */
5567 /*                                                                    */
5568 /* 2. The speed of this function is about 10x slower than exp, as     */
5569 /*    it typically needs 4-6 iterations for short numbers, and the    */
5570 /*    extra precision needed adds a squaring effect, twice.           */
5571 /*                                                                    */
5572 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5573 /*    as these are common requests.  ln(10) is used by log10(x).      */
5574 /*                                                                    */
5575 /* 4. An iteration might be saved by widening the LNnn table, and     */
5576 /*    would certainly save at least one if it were made ten times     */
5577 /*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5578 /*    However, for most practical evaluations, at least four or five  */
5579 /*    iterations will be neede -- so this would only speed up by      */
5580 /*    20-25% and that probably does not justify increasing the table  */
5581 /*    size.                                                           */
5582 /*                                                                    */
5583 /* 5. The static buffers are larger than might be expected to allow   */
5584 /*    for calls from decNumberPower.                                  */
5585 /* ------------------------------------------------------------------ */
5586 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5587                     decContext *set, uInt *status) {
5588   uInt ignore=0;                   /* working status accumulator */
5589   uInt needbytes;                  /* for space calculations */
5590   Int residue;                     /* rounding residue */
5591   Int r;                           /* rhs=f*10**r [see below] */
5592   Int p;                           /* working precision */
5593   Int pp;                          /* precision for iteration */
5594   Int t;                           /* work */
5595
5596   /* buffers for a (accumulator, typically precision+2) and b */
5597   /* (adjustment calculator, same size) */
5598   decNumber bufa[D2N(DECBUFFER+12)];
5599   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
5600   decNumber *a=bufa;               /* accumulator/work */
5601   decNumber bufb[D2N(DECBUFFER*2+2)];
5602   decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated */
5603   decNumber *b=bufb;               /* adjustment/work */
5604
5605   decNumber  numone;               /* constant 1 */
5606   decNumber  cmp;                  /* work */
5607   decContext aset, bset;           /* working contexts */
5608
5609   #if DECCHECK
5610   Int iterations=0;                /* for later sanity check */
5611   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5612   #endif
5613
5614   do {                                  /* protect allocated storage */
5615     if (SPECIALARG) {                   /* handle infinities and NaNs */
5616       if (decNumberIsInfinite(rhs)) {   /* an infinity */
5617         if (decNumberIsNegative(rhs))   /* -Infinity -> error */
5618           *status|=DEC_Invalid_operation;
5619          else decNumberCopy(res, rhs);  /* +Infinity -> self */
5620         }
5621        else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5622       break;}
5623
5624     if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity */
5625       decNumberZero(res);               /* make clean */
5626       res->bits=DECINF|DECNEG;          /* set - infinity */
5627       break;}                           /* [no status to set] */
5628
5629     /* Non-zero negatives are bad... */
5630     if (decNumberIsNegative(rhs)) {     /* -x -> error */
5631       *status|=DEC_Invalid_operation;
5632       break;}
5633
5634     /* Here, rhs is positive, finite, and in range */
5635
5636     /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5637     if (rhs->exponent==0 && set->digits<=40) {
5638       #if DECDPUN==1
5639       if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5640       #else
5641       if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10) */
5642       #endif
5643         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5644         #define LN10 "2.302585092994045684017991454684364207601"
5645         decNumberFromString(res, LN10, &aset);
5646         *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5647         break;}
5648       if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5649         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5650         #define LN2 "0.6931471805599453094172321214581765680755"
5651         decNumberFromString(res, LN2, &aset);
5652         *status|=(DEC_Inexact | DEC_Rounded);
5653         break;}
5654       } /* integer and short */
5655
5656     /* Determine the working precision.  This is normally the */
5657     /* requested precision + 2, with a minimum of 9.  However, if */
5658     /* the rhs is 'over-precise' then allow for all its digits to */
5659     /* potentially participate (consider an rhs where all the excess */
5660     /* digits are 9s) so in this case use rhs->digits+2. */
5661     p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5662
5663     /* Allocate space for the accumulator and the high-precision */
5664     /* adjustment calculator, if necessary.  The accumulator must */
5665     /* be able to hold p digits, and the adjustment up to */
5666     /* rhs->digits+p digits.  They are also made big enough for 16 */
5667     /* digits so that they can be used for calculating the initial */
5668     /* estimate. */
5669     needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5670     if (needbytes>sizeof(bufa)) {     /* need malloc space */
5671       allocbufa=(decNumber *)malloc(needbytes);
5672       if (allocbufa==NULL) {          /* hopeless -- abandon */
5673         *status|=DEC_Insufficient_storage;
5674         break;}
5675       a=allocbufa;                    /* use the allocated space */
5676       }
5677     pp=p+rhs->digits;
5678     needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5679     if (needbytes>sizeof(bufb)) {     /* need malloc space */
5680       allocbufb=(decNumber *)malloc(needbytes);
5681       if (allocbufb==NULL) {          /* hopeless -- abandon */
5682         *status|=DEC_Insufficient_storage;
5683         break;}
5684       b=allocbufb;                    /* use the allocated space */
5685       }
5686
5687     /* Prepare an initial estimate in acc. Calculate this by */
5688     /* considering the coefficient of x to be a normalized fraction, */
5689     /* f, with the decimal point at far left and multiplied by */
5690     /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and */
5691     /*   ln(x) = ln(f) + ln(10)*r */
5692     /* Get the initial estimate for ln(f) from a small lookup */
5693     /* table (see above) indexed by the first two digits of f, */
5694     /* truncated. */
5695
5696     decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5697     r=rhs->exponent+rhs->digits;        /* 'normalised' exponent */
5698     decNumberFromInt32(a, r);           /* a=r */
5699     decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585) */
5700     b->exponent=-6;                     /*  .. */
5701     decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b */
5702     /* now get top two digits of rhs into b by simple truncate and */
5703     /* force to integer */
5704     residue=0;                          /* (no residue) */
5705     aset.digits=2; aset.round=DEC_ROUND_DOWN;
5706     decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5707     b->exponent=0;                      /* make integer */
5708     t=decGetInt(b);                     /* [cannot fail] */
5709     if (t<10) t=X10(t);                 /* adjust single-digit b */
5710     t=LNnn[t-10];                       /* look up ln(b) */
5711     decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient */
5712     b->exponent=-(t&3)-3;               /* set exponent */
5713     b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve */
5714     aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5715     decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5716     /* the initial estimate is now in a, with up to 4 digits correct. */
5717     /* When rhs is at or near Nmax the estimate will be low, so we */
5718     /* will approach it from below, avoiding overflow when calling exp. */
5719
5720     decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment */
5721
5722     /* accumulator bounds are as requested (could underflow, but */
5723     /* cannot overflow) */
5724     aset.emax=set->emax;
5725     aset.emin=set->emin;
5726     aset.clamp=0;                       /* no concrete format */
5727     /* set up a context to be used for the multiply and subtract */
5728     bset=aset;
5729     bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the */
5730     bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation */
5731                                         /* [see decExpOp call below] */
5732     /* for each iteration double the number of digits to calculate, */
5733     /* up to a maximum of p */
5734     pp=9;                               /* initial precision */
5735     /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5736     /* 34+2, which is ideal for standard-sized numbers] */
5737     aset.digits=pp;                     /* working context */
5738     bset.digits=pp+rhs->digits;         /* wider context */
5739     for (;;) {                          /* iterate */
5740       #if DECCHECK
5741       iterations++;
5742       if (iterations>24) break;         /* consider 9 * 2**24 */
5743       #endif
5744       /* calculate the adjustment (exp(-a)*x-1) into b.  This is a */
5745       /* catastrophic subtraction but it really is the difference */
5746       /* from 1 that is of interest. */
5747       /* Use the internal entry point to Exp as it allows the double */
5748       /* range for calculating exp(-a) when a is the tiniest subnormal. */
5749       a->bits^=DECNEG;                  /* make -a */
5750       decExpOp(b, a, &bset, &ignore);   /* b=exp(-a) */
5751       a->bits^=DECNEG;                  /* restore sign of a */
5752       /* now multiply by rhs and subtract 1, at the wider precision */
5753       decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs */
5754       decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5755
5756       /* the iteration ends when the adjustment cannot affect the */
5757       /* result by >=0.5 ulp (at the requested digits), which */
5758       /* is when its value is smaller than the accumulator by */
5759       /* set->digits+1 digits (or it is zero) -- this is a looser */
5760       /* requirement than for Exp because all that happens to the */
5761       /* accumulator after this is the final rounding (but note that */
5762       /* there must also be full precision in a, or a=0). */
5763
5764       if (decNumberIsZero(b) ||
5765           (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5766         if (a->digits==p) break;
5767         if (decNumberIsZero(a)) {
5768           decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5769           if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0 */
5770            else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact */
5771           break;
5772           }
5773         /* force padding if adjustment has gone to 0 before full length */
5774         if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5775         }
5776
5777       /* not done yet ... */
5778       decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate */
5779       if (pp==p) continue;                   /* precision is at maximum */
5780       /* lengthen the next calculation */
5781       pp=pp*2;                               /* double precision */
5782       if (pp>p) pp=p;                        /* clamp to maximum */
5783       aset.digits=pp;                        /* working context */
5784       bset.digits=pp+rhs->digits;            /* wider context */
5785       } /* Newton's iteration */
5786
5787     #if DECCHECK
5788     /* just a sanity check; remove the test to show always */
5789     if (iterations>24)
5790       printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5791             (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5792     #endif
5793
5794     /* Copy and round the result to res */
5795     residue=1;                          /* indicate dirt to right */
5796     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0 */
5797     aset.digits=set->digits;            /* [use default rounding] */
5798     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5799     decFinish(res, set, &residue, status);       /* cleanup/set flags */
5800     } while(0);                         /* end protected */
5801
5802   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5803   if (allocbufb!=NULL) free(allocbufb); /* .. */
5804   /* [status is handled by caller] */
5805   return res;
5806   } /* decLnOp */
5807
5808 /* ------------------------------------------------------------------ */
5809 /* decQuantizeOp  -- force exponent to requested value                */
5810 /*                                                                    */
5811 /*   This computes C = op(A, B), where op adjusts the coefficient     */
5812 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
5813 /*   of C has the value B or matches the exponent of B.               */
5814 /*   The numerical value of C will equal A, except for the effects of */
5815 /*   any rounding that occurred.                                      */
5816 /*                                                                    */
5817 /*   res is C, the result.  C may be A or B                           */
5818 /*   lhs is A, the number to adjust                                   */
5819 /*   rhs is B, the requested exponent                                 */
5820 /*   set is the context                                               */
5821 /*   quant is 1 for quantize or 0 for rescale                         */
5822 /*   status is the status accumulator (this can be called without     */
5823 /*          risk of control loss)                                     */
5824 /*                                                                    */
5825 /* C must have space for set->digits digits.                          */
5826 /*                                                                    */
5827 /* Unless there is an error or the result is infinite, the exponent   */
5828 /* after the operation is guaranteed to be that requested.            */
5829 /* ------------------------------------------------------------------ */
5830 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5831                                  const decNumber *rhs, decContext *set,
5832                                  Flag quant, uInt *status) {
5833   #if DECSUBSET
5834   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
5835   decNumber *allocrhs=NULL;        /* .., rhs */
5836   #endif
5837   const decNumber *inrhs=rhs;      /* save original rhs */
5838   Int   reqdigits=set->digits;     /* requested DIGITS */
5839   Int   reqexp;                    /* requested exponent [-scale] */
5840   Int   residue=0;                 /* rounding residue */
5841   Int   etiny=set->emin-(reqdigits-1);
5842
5843   #if DECCHECK
5844   if (decCheckOperands(res, lhs, rhs, set)) return res;
5845   #endif
5846
5847   do {                             /* protect allocated storage */
5848     #if DECSUBSET
5849     if (!set->extended) {
5850       /* reduce operands and set lostDigits status, as needed */
5851       if (lhs->digits>reqdigits) {
5852         alloclhs=decRoundOperand(lhs, set, status);
5853         if (alloclhs==NULL) break;
5854         lhs=alloclhs;
5855         }
5856       if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5857         allocrhs=decRoundOperand(rhs, set, status);
5858         if (allocrhs==NULL) break;
5859         rhs=allocrhs;
5860         }
5861       }
5862     #endif
5863     /* [following code does not require input rounding] */
5864
5865     /* Handle special values */
5866     if (SPECIALARGS) {
5867       /* NaNs get usual processing */
5868       if (SPECIALARGS & (DECSNAN | DECNAN))
5869         decNaNs(res, lhs, rhs, set, status);
5870       /* one infinity but not both is bad */
5871       else if ((lhs->bits ^ rhs->bits) & DECINF)
5872         *status|=DEC_Invalid_operation;
5873       /* both infinity: return lhs */
5874       else decNumberCopy(res, lhs);          /* [nop if in place] */
5875       break;
5876       }
5877
5878     /* set requested exponent */
5879     if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents */
5880      else {                             /* rescale -- use value of rhs */
5881       /* Original rhs must be an integer that fits and is in range, */
5882       /* which could be from -1999999997 to +999999999, thanks to */
5883       /* subnormals */
5884       reqexp=decGetInt(inrhs);               /* [cannot fail] */
5885       }
5886
5887     #if DECSUBSET
5888     if (!set->extended) etiny=set->emin;     /* no subnormals */
5889     #endif
5890
5891     if (reqexp==BADINT                       /* bad (rescale only) or .. */
5892      || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or .. */
5893      || (reqexp<etiny)                       /* < lowest */
5894      || (reqexp>set->emax)) {                /* > emax */
5895       *status|=DEC_Invalid_operation;
5896       break;}
5897
5898     /* the RHS has been processed, so it can be overwritten now if necessary */
5899     if (ISZERO(lhs)) {                       /* zero coefficient unchanged */
5900       decNumberCopy(res, lhs);               /* [nop if in place] */
5901       res->exponent=reqexp;                  /* .. just set exponent */
5902       #if DECSUBSET
5903       if (!set->extended) res->bits=0;       /* subset specification; no -0 */
5904       #endif
5905       }
5906      else {                                  /* non-zero lhs */
5907       Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed */
5908       /* if adjusted coefficient will definitely not fit, give up now */
5909       if ((lhs->digits-adjust)>reqdigits) {
5910         *status|=DEC_Invalid_operation;
5911         break;
5912         }
5913
5914       if (adjust>0) {                        /* increasing exponent */
5915         /* this will decrease the length of the coefficient by adjust */
5916         /* digits, and must round as it does so */
5917         decContext workset;                  /* work */
5918         workset=*set;                        /* clone rounding, etc. */
5919         workset.digits=lhs->digits-adjust;   /* set requested length */
5920         /* [note that the latter can be <1, here] */
5921         decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5922         decApplyRound(res, &workset, residue, status);    /* .. and round */
5923         residue=0;                                        /* [used] */
5924         /* If just rounded a 999s case, exponent will be off by one; */
5925         /* adjust back (after checking space), if so. */
5926         if (res->exponent>reqexp) {
5927           /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5928           /* set->digits==3 */
5929           if (res->digits==reqdigits) {      /* cannot shift by 1 */
5930             *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5931             *status|=DEC_Invalid_operation;
5932             break;
5933             }
5934           res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5935           res->exponent--;                   /* (re)adjust the exponent. */
5936           }
5937         #if DECSUBSET
5938         if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5939         #endif
5940         } /* increase */
5941        else /* adjust<=0 */ {                /* decreasing or = exponent */
5942         /* this will increase the length of the coefficient by -adjust */
5943         /* digits, by adding zero or more trailing zeros; this is */
5944         /* already checked for fit, above */
5945         decNumberCopy(res, lhs);             /* [it will fit] */
5946         /* if padding needed (adjust<0), add it now... */
5947         if (adjust<0) {
5948           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5949           res->exponent+=adjust;             /* adjust the exponent */
5950           }
5951         } /* decrease */
5952       } /* non-zero */
5953
5954     /* Check for overflow [do not use Finalize in this case, as an */
5955     /* overflow here is a "don't fit" situation] */
5956     if (res->exponent>set->emax-res->digits+1) {  /* too big */
5957       *status|=DEC_Invalid_operation;
5958       break;
5959       }
5960      else {
5961       decFinalize(res, set, &residue, status);    /* set subnormal flags */
5962       *status&=~DEC_Underflow;          /* suppress Underflow [as per 754] */
5963       }
5964     } while(0);                         /* end protected */
5965
5966   #if DECSUBSET
5967   if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used */
5968   if (alloclhs!=NULL) free(alloclhs);   /* .. */
5969   #endif
5970   return res;
5971   } /* decQuantizeOp */
5972
5973 /* ------------------------------------------------------------------ */
5974 /* decCompareOp -- compare, min, or max two Numbers                   */
5975 /*                                                                    */
5976 /*   This computes C = A ? B and carries out one of four operations:  */
5977 /*     COMPARE    -- returns the signum (as a number) giving the      */
5978 /*                   result of a comparison unless one or both        */
5979 /*                   operands is a NaN (in which case a NaN results)  */
5980 /*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5981 /*                   Invalid operation.                               */
5982 /*     COMPMAX    -- returns the larger of the operands, using the    */
5983 /*                   754 maxnum operation                             */
5984 /*     COMPMAXMAG -- ditto, comparing absolute values                 */
5985 /*     COMPMIN    -- the 754 minnum operation                         */
5986 /*     COMPMINMAG -- ditto, comparing absolute values                 */
5987 /*     COMTOTAL   -- returns the signum (as a number) giving the      */
5988 /*                   result of a comparison using 754 total ordering  */
5989 /*                                                                    */
5990 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
5991 /*   lhs is A                                                         */
5992 /*   rhs is B                                                         */
5993 /*   set is the context                                               */
5994 /*   op  is the operation flag                                        */
5995 /*   status is the usual accumulator                                  */
5996 /*                                                                    */
5997 /* C must have space for one digit for COMPARE or set->digits for     */
5998 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
5999 /* ------------------------------------------------------------------ */
6000 /* The emphasis here is on speed for common cases, and avoiding       */
6001 /* coefficient comparison if possible.                                */
6002 /* ------------------------------------------------------------------ */
6003 decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6004                          const decNumber *rhs, decContext *set,
6005                          Flag op, uInt *status) {
6006   #if DECSUBSET
6007   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
6008   decNumber *allocrhs=NULL;        /* .., rhs */
6009   #endif
6010   Int   result=0;                  /* default result value */
6011   uByte merged;                    /* work */
6012
6013   #if DECCHECK
6014   if (decCheckOperands(res, lhs, rhs, set)) return res;
6015   #endif
6016
6017   do {                             /* protect allocated storage */
6018     #if DECSUBSET
6019     if (!set->extended) {
6020       /* reduce operands and set lostDigits status, as needed */
6021       if (lhs->digits>set->digits) {
6022         alloclhs=decRoundOperand(lhs, set, status);
6023         if (alloclhs==NULL) {result=BADINT; break;}
6024         lhs=alloclhs;
6025         }
6026       if (rhs->digits>set->digits) {
6027         allocrhs=decRoundOperand(rhs, set, status);
6028         if (allocrhs==NULL) {result=BADINT; break;}
6029         rhs=allocrhs;
6030         }
6031       }
6032     #endif
6033     /* [following code does not require input rounding] */
6034
6035     /* If total ordering then handle differing signs 'up front' */
6036     if (op==COMPTOTAL) {                /* total ordering */
6037       if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6038         result=-1;
6039         break;
6040         }
6041       if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6042         result=+1;
6043         break;
6044         }
6045       }
6046
6047     /* handle NaNs specially; let infinities drop through */
6048     /* This assumes sNaN (even just one) leads to NaN. */
6049     merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6050     if (merged) {                       /* a NaN bit set */
6051       if (op==COMPARE);                 /* result will be NaN */
6052        else if (op==COMPSIG)            /* treat qNaN as sNaN */
6053         *status|=DEC_Invalid_operation | DEC_sNaN;
6054        else if (op==COMPTOTAL) {        /* total ordering, always finite */
6055         /* signs are known to be the same; compute the ordering here */
6056         /* as if the signs are both positive, then invert for negatives */
6057         if (!decNumberIsNaN(lhs)) result=-1;
6058          else if (!decNumberIsNaN(rhs)) result=+1;
6059          /* here if both NaNs */
6060          else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6061          else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6062          else { /* both NaN or both sNaN */
6063           /* now it just depends on the payload */
6064           result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6065                                 rhs->lsu, D2U(rhs->digits), 0);
6066           /* [Error not possible, as these are 'aligned'] */
6067           } /* both same NaNs */
6068         if (decNumberIsNegative(lhs)) result=-result;
6069         break;
6070         } /* total order */
6071
6072        else if (merged & DECSNAN);           /* sNaN -> qNaN */
6073        else { /* here if MIN or MAX and one or two quiet NaNs */
6074         /* min or max -- 754 rules ignore single NaN */
6075         if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6076           /* just one NaN; force choice to be the non-NaN operand */
6077           op=COMPMAX;
6078           if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6079                              else result=+1; /* pick lhs */
6080           break;
6081           }
6082         } /* max or min */
6083       op=COMPNAN;                            /* use special path */
6084       decNaNs(res, lhs, rhs, set, status);   /* propagate NaN */
6085       break;
6086       }
6087     /* have numbers */
6088     if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6089      else result=decCompare(lhs, rhs, 0);    /* sign matters */
6090     } while(0);                              /* end protected */
6091
6092   if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6093    else {
6094     if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6095       if (op==COMPTOTAL && result==0) {
6096         /* operands are numerically equal or same NaN (and same sign, */
6097         /* tested first); if identical, leave result 0 */
6098         if (lhs->exponent!=rhs->exponent) {
6099           if (lhs->exponent<rhs->exponent) result=-1;
6100            else result=+1;
6101           if (decNumberIsNegative(lhs)) result=-result;
6102           } /* lexp!=rexp */
6103         } /* total-order by exponent */
6104       decNumberZero(res);               /* [always a valid result] */
6105       if (result!=0) {                  /* must be -1 or +1 */
6106         *res->lsu=1;
6107         if (result<0) res->bits=DECNEG;
6108         }
6109       }
6110      else if (op==COMPNAN);             /* special, drop through */
6111      else {                             /* MAX or MIN, non-NaN result */
6112       Int residue=0;                    /* rounding accumulator */
6113       /* choose the operand for the result */
6114       const decNumber *choice;
6115       if (result==0) { /* operands are numerically equal */
6116         /* choose according to sign then exponent (see 754) */
6117         uByte slhs=(lhs->bits & DECNEG);
6118         uByte srhs=(rhs->bits & DECNEG);
6119         #if DECSUBSET
6120         if (!set->extended) {           /* subset: force left-hand */
6121           op=COMPMAX;
6122           result=+1;
6123           }
6124         else
6125         #endif
6126         if (slhs!=srhs) {          /* signs differ */
6127           if (slhs) result=-1;     /* rhs is max */
6128                else result=+1;     /* lhs is max */
6129           }
6130          else if (slhs && srhs) {  /* both negative */
6131           if (lhs->exponent<rhs->exponent) result=+1;
6132                                       else result=-1;
6133           /* [if equal, use lhs, technically identical] */
6134           }
6135          else {                    /* both positive */
6136           if (lhs->exponent>rhs->exponent) result=+1;
6137                                       else result=-1;
6138           /* [ditto] */
6139           }
6140         } /* numerically equal */
6141       /* here result will be non-0; reverse if looking for MIN */
6142       if (op==COMPMIN || op==COMPMINMAG) result=-result;
6143       choice=(result>0 ? lhs : rhs);    /* choose */
6144       /* copy chosen to result, rounding if need be */
6145       decCopyFit(res, choice, set, &residue, status);
6146       decFinish(res, set, &residue, status);
6147       }
6148     }
6149   #if DECSUBSET
6150   if (allocrhs!=NULL) free(allocrhs);   /* free any storage used */
6151   if (alloclhs!=NULL) free(alloclhs);   /* .. */
6152   #endif
6153   return res;
6154   } /* decCompareOp */
6155
6156 /* ------------------------------------------------------------------ */
6157 /* decCompare -- compare two decNumbers by numerical value            */
6158 /*                                                                    */
6159 /*  This routine compares A ? B without altering them.                */
6160 /*                                                                    */
6161 /*  Arg1 is A, a decNumber which is not a NaN                         */
6162 /*  Arg2 is B, a decNumber which is not a NaN                         */
6163 /*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6164 /*                                                                    */
6165 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6166 /*  (the only possible failure is an allocation error)                */
6167 /* ------------------------------------------------------------------ */
6168 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6169                       Flag abs) {
6170   Int   result;                    /* result value */
6171   Int   sigr;                      /* rhs signum */
6172   Int   compare;                   /* work */
6173
6174   result=1;                                  /* assume signum(lhs) */
6175   if (ISZERO(lhs)) result=0;
6176   if (abs) {
6177     if (ISZERO(rhs)) return result;          /* LHS wins or both 0 */
6178     /* RHS is non-zero */
6179     if (result==0) return -1;                /* LHS is 0; RHS wins */
6180     /* [here, both non-zero, result=1] */
6181     }
6182    else {                                    /* signs matter */
6183     if (result && decNumberIsNegative(lhs)) result=-1;
6184     sigr=1;                                  /* compute signum(rhs) */
6185     if (ISZERO(rhs)) sigr=0;
6186      else if (decNumberIsNegative(rhs)) sigr=-1;
6187     if (result > sigr) return +1;            /* L > R, return 1 */
6188     if (result < sigr) return -1;            /* L < R, return -1 */
6189     if (result==0) return 0;                   /* both 0 */
6190     }
6191
6192   /* signums are the same; both are non-zero */
6193   if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities */
6194     if (decNumberIsInfinite(rhs)) {
6195       if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6196        else result=-result;                  /* only rhs infinite */
6197       }
6198     return result;
6199     }
6200   /* must compare the coefficients, allowing for exponents */
6201   if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger */
6202     /* swap sides, and sign */
6203     const decNumber *temp=lhs;
6204     lhs=rhs;
6205     rhs=temp;
6206     result=-result;
6207     }
6208   compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6209                          rhs->lsu, D2U(rhs->digits),
6210                          rhs->exponent-lhs->exponent);
6211   if (compare!=BADINT) compare*=result;      /* comparison succeeded */
6212   return compare;
6213   } /* decCompare */
6214
6215 /* ------------------------------------------------------------------ */
6216 /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6217 /*                                                                    */
6218 /*  This routine compares A ? B*10**E where A and B are unit arrays   */
6219 /*  A is a plain integer                                              */
6220 /*  B has an exponent of E (which must be non-negative)               */
6221 /*                                                                    */
6222 /*  Arg1 is A first Unit (lsu)                                        */
6223 /*  Arg2 is A length in Units                                         */
6224 /*  Arg3 is B first Unit (lsu)                                        */
6225 /*  Arg4 is B length in Units                                         */
6226 /*  Arg5 is E (0 if the units are aligned)                            */
6227 /*                                                                    */
6228 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6229 /*  (the only possible failure is an allocation error, which can      */
6230 /*  only occur if E!=0)                                               */
6231 /* ------------------------------------------------------------------ */
6232 static Int decUnitCompare(const Unit *a, Int alength,
6233                           const Unit *b, Int blength, Int exp) {
6234   Unit  *acc;                      /* accumulator for result */
6235   Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6236   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated */
6237   Int   accunits, need;            /* units in use or needed for acc */
6238   const Unit *l, *r, *u;           /* work */
6239   Int   expunits, exprem, result;  /* .. */
6240
6241   if (exp==0) {                    /* aligned; fastpath */
6242     if (alength>blength) return 1;
6243     if (alength<blength) return -1;
6244     /* same number of units in both -- need unit-by-unit compare */
6245     l=a+alength-1;
6246     r=b+alength-1;
6247     for (;l>=a; l--, r--) {
6248       if (*l>*r) return 1;
6249       if (*l<*r) return -1;
6250       }
6251     return 0;                      /* all units match */
6252     } /* aligned */
6253
6254   /* Unaligned.  If one is >1 unit longer than the other, padded */
6255   /* approximately, then can return easily */
6256   if (alength>blength+(Int)D2U(exp)) return 1;
6257   if (alength+1<blength+(Int)D2U(exp)) return -1;
6258
6259   /* Need to do a real subtract.  For this, a result buffer is needed */
6260   /* even though only the sign is of interest.  Its length needs */
6261   /* to be the larger of alength and padded blength, +2 */
6262   need=blength+D2U(exp);                /* maximum real length of B */
6263   if (need<alength) need=alength;
6264   need+=2;
6265   acc=accbuff;                          /* assume use local buffer */
6266   if (need*sizeof(Unit)>sizeof(accbuff)) {
6267     allocacc=(Unit *)malloc(need*sizeof(Unit));
6268     if (allocacc==NULL) return BADINT;  /* hopeless -- abandon */
6269     acc=allocacc;
6270     }
6271   /* Calculate units and remainder from exponent. */
6272   expunits=exp/DECDPUN;
6273   exprem=exp%DECDPUN;
6274   /* subtract [A+B*(-m)] */
6275   accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6276                          -(Int)powers[exprem]);
6277   /* [UnitAddSub result may have leading zeros, even on zero] */
6278   if (accunits<0) result=-1;            /* negative result */
6279    else {                               /* non-negative result */
6280     /* check units of the result before freeing any storage */
6281     for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6282     result=(*u==0 ? 0 : +1);
6283     }
6284   /* clean up and return the result */
6285   if (allocacc!=NULL) free(allocacc);   /* drop any storage used */
6286   return result;
6287   } /* decUnitCompare */
6288
6289 /* ------------------------------------------------------------------ */
6290 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6291 /*                                                                    */
6292 /*  This routine performs the calculation:                            */
6293 /*                                                                    */
6294 /*  C=A+(B*M)                                                         */
6295 /*                                                                    */
6296 /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6297 /*                                                                    */
6298 /*  A may be shorter or longer than B.                                */
6299 /*                                                                    */
6300 /*  Leading zeros are not removed after a calculation.  The result is */
6301 /*  either the same length as the longer of A and B (adding any       */
6302 /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6303 /*                                                                    */
6304 /*  A and B content are not altered unless C is also A or B.          */
6305 /*  C may be the same array as A or B, but only if no zero padding is */
6306 /*  requested (that is, C may be B only if bshift==0).                */
6307 /*  C is filled from the lsu; only those units necessary to complete  */
6308 /*  the calculation are referenced.                                   */
6309 /*                                                                    */
6310 /*  Arg1 is A first Unit (lsu)                                        */
6311 /*  Arg2 is A length in Units                                         */
6312 /*  Arg3 is B first Unit (lsu)                                        */
6313 /*  Arg4 is B length in Units                                         */
6314 /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6315 /*  Arg6 is C first Unit (lsu)                                        */
6316 /*  Arg7 is M, the multiplier                                         */
6317 /*                                                                    */
6318 /*  returns the count of Units written to C, which will be non-zero   */
6319 /*  and negated if the result is negative.  That is, the sign of the  */
6320 /*  returned Int is the sign of the result (positive for zero) and    */
6321 /*  the absolute value of the Int is the count of Units.              */
6322 /*                                                                    */
6323 /*  It is the caller's responsibility to make sure that C size is     */
6324 /*  safe, allowing space if necessary for a one-Unit carry.           */
6325 /*                                                                    */
6326 /*  This routine is severely performance-critical; *any* change here  */
6327 /*  must be measured (timed) to assure no performance degradation.    */
6328 /*  In particular, trickery here tends to be counter-productive, as   */
6329 /*  increased complexity of code hurts register optimizations on      */
6330 /*  register-poor architectures.  Avoiding divisions is nearly        */
6331 /*  always a Good Idea, however.                                      */
6332 /*                                                                    */
6333 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6334 /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6335 /* ------------------------------------------------------------------ */
6336 static Int decUnitAddSub(const Unit *a, Int alength,
6337                          const Unit *b, Int blength, Int bshift,
6338                          Unit *c, Int m) {
6339   const Unit *alsu=a;              /* A lsu [need to remember it] */
6340   Unit *clsu=c;                    /* C ditto */
6341   Unit *minC;                      /* low water mark for C */
6342   Unit *maxC;                      /* high water mark for C */
6343   eInt carry=0;                    /* carry integer (could be Long) */
6344   Int  add;                        /* work */
6345   #if DECDPUN<=4                   /* myriadal, millenary, etc. */
6346   Int  est;                        /* estimated quotient */
6347   #endif
6348
6349   #if DECTRACE
6350   if (alength<1 || blength<1)
6351     printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6352   #endif
6353
6354   maxC=c+alength;                  /* A is usually the longer */
6355   minC=c+blength;                  /* .. and B the shorter */
6356   if (bshift!=0) {                 /* B is shifted; low As copy across */
6357     minC+=bshift;
6358     /* if in place [common], skip copy unless there's a gap [rare] */
6359     if (a==c && bshift<=alength) {
6360       c+=bshift;
6361       a+=bshift;
6362       }
6363      else for (; c<clsu+bshift; a++, c++) {  /* copy needed */
6364       if (a<alsu+alength) *c=*a;
6365        else *c=0;
6366       }
6367     }
6368   if (minC>maxC) { /* swap */
6369     Unit *hold=minC;
6370     minC=maxC;
6371     maxC=hold;
6372     }
6373
6374   /* For speed, do the addition as two loops; the first where both A */
6375   /* and B contribute, and the second (if necessary) where only one or */
6376   /* other of the numbers contribute. */
6377   /* Carry handling is the same (i.e., duplicated) in each case. */
6378   for (; c<minC; c++) {
6379     carry+=*a;
6380     a++;
6381     carry+=((eInt)*b)*m;                /* [special-casing m=1/-1 */
6382     b++;                                /* here is not a win] */
6383     /* here carry is new Unit of digits; it could be +ve or -ve */
6384     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX */
6385       *c=(Unit)carry;
6386       carry=0;
6387       continue;
6388       }
6389     #if DECDPUN==4                           /* use divide-by-multiply */
6390       if (carry>=0) {
6391         est=(((ueInt)carry>>11)*53687)>>18;
6392         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6393         carry=est;                           /* likely quotient [89%] */
6394         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6395         carry++;
6396         *c-=DECDPUNMAX+1;
6397         continue;
6398         }
6399       /* negative case */
6400       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6401       est=(((ueInt)carry>>11)*53687)>>18;
6402       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6403       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6404       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6405       carry++;
6406       *c-=DECDPUNMAX+1;
6407     #elif DECDPUN==3
6408       if (carry>=0) {
6409         est=(((ueInt)carry>>3)*16777)>>21;
6410         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6411         carry=est;                           /* likely quotient [99%] */
6412         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6413         carry++;
6414         *c-=DECDPUNMAX+1;
6415         continue;
6416         }
6417       /* negative case */
6418       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6419       est=(((ueInt)carry>>3)*16777)>>21;
6420       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6421       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6422       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6423       carry++;
6424       *c-=DECDPUNMAX+1;
6425     #elif DECDPUN<=2
6426       /* Can use QUOT10 as carry <= 4 digits */
6427       if (carry>=0) {
6428         est=QUOT10(carry, DECDPUN);
6429         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6430         carry=est;                           /* quotient */
6431         continue;
6432         }
6433       /* negative case */
6434       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6435       est=QUOT10(carry, DECDPUN);
6436       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6437       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6438     #else
6439       /* remainder operator is undefined if negative, so must test */
6440       if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1 */
6441         *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions] */
6442         carry=1;
6443         continue;
6444         }
6445       if (carry>=0) {
6446         *c=(Unit)(carry%(DECDPUNMAX+1));
6447         carry=carry/(DECDPUNMAX+1);
6448         continue;
6449         }
6450       /* negative case */
6451       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6452       *c=(Unit)(carry%(DECDPUNMAX+1));
6453       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6454     #endif
6455     } /* c */
6456
6457   /* now may have one or other to complete */
6458   /* [pretest to avoid loop setup/shutdown] */
6459   if (c<maxC) for (; c<maxC; c++) {
6460     if (a<alsu+alength) {               /* still in A */
6461       carry+=*a;
6462       a++;
6463       }
6464      else {                             /* inside B */
6465       carry+=((eInt)*b)*m;
6466       b++;
6467       }
6468     /* here carry is new Unit of digits; it could be +ve or -ve and */
6469     /* magnitude up to DECDPUNMAX squared */
6470     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX */
6471       *c=(Unit)carry;
6472       carry=0;
6473       continue;
6474       }
6475     /* result for this unit is negative or >DECDPUNMAX */
6476     #if DECDPUN==4                           /* use divide-by-multiply */
6477       if (carry>=0) {
6478         est=(((ueInt)carry>>11)*53687)>>18;
6479         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6480         carry=est;                           /* likely quotient [79.7%] */
6481         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6482         carry++;
6483         *c-=DECDPUNMAX+1;
6484         continue;
6485         }
6486       /* negative case */
6487       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6488       est=(((ueInt)carry>>11)*53687)>>18;
6489       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6490       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6491       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6492       carry++;
6493       *c-=DECDPUNMAX+1;
6494     #elif DECDPUN==3
6495       if (carry>=0) {
6496         est=(((ueInt)carry>>3)*16777)>>21;
6497         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6498         carry=est;                           /* likely quotient [99%] */
6499         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6500         carry++;
6501         *c-=DECDPUNMAX+1;
6502         continue;
6503         }
6504       /* negative case */
6505       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6506       est=(((ueInt)carry>>3)*16777)>>21;
6507       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6508       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6509       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6510       carry++;
6511       *c-=DECDPUNMAX+1;
6512     #elif DECDPUN<=2
6513       if (carry>=0) {
6514         est=QUOT10(carry, DECDPUN);
6515         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6516         carry=est;                           /* quotient */
6517         continue;
6518         }
6519       /* negative case */
6520       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6521       est=QUOT10(carry, DECDPUN);
6522       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6523       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6524     #else
6525       if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1 */
6526         *c=(Unit)(carry-(DECDPUNMAX+1));
6527         carry=1;
6528         continue;
6529         }
6530       /* remainder operator is undefined if negative, so must test */
6531       if (carry>=0) {
6532         *c=(Unit)(carry%(DECDPUNMAX+1));
6533         carry=carry/(DECDPUNMAX+1);
6534         continue;
6535         }
6536       /* negative case */
6537       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6538       *c=(Unit)(carry%(DECDPUNMAX+1));
6539       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6540     #endif
6541     } /* c */
6542
6543   /* OK, all A and B processed; might still have carry or borrow */
6544   /* return number of Units in the result, negated if a borrow */
6545   if (carry==0) return c-clsu;     /* no carry, so no more to do */
6546   if (carry>0) {                   /* positive carry */
6547     *c=(Unit)carry;                /* place as new unit */
6548     c++;                           /* .. */
6549     return c-clsu;
6550     }
6551   /* -ve carry: it's a borrow; complement needed */
6552   add=1;                           /* temporary carry... */
6553   for (c=clsu; c<maxC; c++) {
6554     add=DECDPUNMAX+add-*c;
6555     if (add<=DECDPUNMAX) {
6556       *c=(Unit)add;
6557       add=0;
6558       }
6559      else {
6560       *c=0;
6561       add=1;
6562       }
6563     }
6564   /* add an extra unit iff it would be non-zero */
6565   #if DECTRACE
6566     printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6567   #endif
6568   if ((add-carry-1)!=0) {
6569     *c=(Unit)(add-carry-1);
6570     c++;                      /* interesting, include it */
6571     }
6572   return clsu-c;              /* -ve result indicates borrowed */
6573   } /* decUnitAddSub */
6574
6575 /* ------------------------------------------------------------------ */
6576 /* decTrim -- trim trailing zeros or normalize                        */
6577 /*                                                                    */
6578 /*   dn is the number to trim or normalize                            */
6579 /*   set is the context to use to check for clamp                     */
6580 /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6581 /*   noclamp is 1 to unconditional (unclamped) trim                   */
6582 /*   dropped returns the number of discarded trailing zeros           */
6583 /*   returns dn                                                       */
6584 /*                                                                    */
6585 /* If clamp is set in the context then the number of zeros trimmed    */
6586 /* may be limited if the exponent is high.                            */
6587 /* All fields are updated as required.  This is a utility operation,  */
6588 /* so special values are unchanged and no error is possible.          */
6589 /* ------------------------------------------------------------------ */
6590 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6591                            Flag noclamp, Int *dropped) {
6592   Int   d, exp;                    /* work */
6593   uInt  cut;                       /* .. */
6594   Unit  *up;                       /* -> current Unit */
6595
6596   #if DECCHECK
6597   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6598   #endif
6599
6600   *dropped=0;                           /* assume no zeros dropped */
6601   if ((dn->bits & DECSPECIAL)           /* fast exit if special .. */
6602     || (*dn->lsu & 0x01)) return dn;    /* .. or odd */
6603   if (ISZERO(dn)) {                     /* .. or 0 */
6604     dn->exponent=0;                     /* (sign is preserved) */
6605     return dn;
6606     }
6607
6608   /* have a finite number which is even */
6609   exp=dn->exponent;
6610   cut=1;                           /* digit (1-DECDPUN) in Unit */
6611   up=dn->lsu;                      /* -> current Unit */
6612   for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6613     /* slice by powers */
6614     #if DECDPUN<=4
6615       uInt quot=QUOT10(*up, cut);
6616       if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit */
6617     #else
6618       if (*up%powers[cut]!=0) break;         /* found non-0 digit */
6619     #endif
6620     /* have a trailing 0 */
6621     if (!all) {                    /* trimming */
6622       /* [if exp>0 then all trailing 0s are significant for trim] */
6623       if (exp<=0) {                /* if digit might be significant */
6624         if (exp==0) break;         /* then quit */
6625         exp++;                     /* next digit might be significant */
6626         }
6627       }
6628     cut++;                         /* next power */
6629     if (cut>DECDPUN) {             /* need new Unit */
6630       up++;
6631       cut=1;
6632       }
6633     } /* d */
6634   if (d==0) return dn;             /* none to drop */
6635
6636   /* may need to limit drop if clamping */
6637   if (set->clamp && !noclamp) {
6638     Int maxd=set->emax-set->digits+1-dn->exponent;
6639     if (maxd<=0) return dn;        /* nothing possible */
6640     if (d>maxd) d=maxd;
6641     }
6642
6643   /* effect the drop */
6644   decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6645   dn->exponent+=d;                 /* maintain numerical value */
6646   dn->digits-=d;                   /* new length */
6647   *dropped=d;                      /* report the count */
6648   return dn;
6649   } /* decTrim */
6650
6651 /* ------------------------------------------------------------------ */
6652 /* decReverse -- reverse a Unit array in place                        */
6653 /*                                                                    */
6654 /*   ulo    is the start of the array                                 */
6655 /*   uhi    is the end of the array (highest Unit to include)         */
6656 /*                                                                    */
6657 /* The units ulo through uhi are reversed in place (if the number     */
6658 /* of units is odd, the middle one is untouched).  Note that the      */
6659 /* digit(s) in each unit are unaffected.                              */
6660 /* ------------------------------------------------------------------ */
6661 static void decReverse(Unit *ulo, Unit *uhi) {
6662   Unit temp;
6663   for (; ulo<uhi; ulo++, uhi--) {
6664     temp=*ulo;
6665     *ulo=*uhi;
6666     *uhi=temp;
6667     }
6668   return;
6669   } /* decReverse */
6670
6671 /* ------------------------------------------------------------------ */
6672 /* decShiftToMost -- shift digits in array towards most significant   */
6673 /*                                                                    */
6674 /*   uar    is the array                                              */
6675 /*   digits is the count of digits in use in the array                */
6676 /*   shift  is the number of zeros to pad with (least significant);   */
6677 /*     it must be zero or positive                                    */
6678 /*                                                                    */
6679 /*   returns the new length of the integer in the array, in digits    */
6680 /*                                                                    */
6681 /* No overflow is permitted (that is, the uar array must be known to  */
6682 /* be large enough to hold the result, after shifting).               */
6683 /* ------------------------------------------------------------------ */
6684 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6685   Unit  *target, *source, *first;  /* work */
6686   Int   cut;                       /* odd 0's to add */
6687   uInt  next;                      /* work */
6688
6689   if (shift==0) return digits;     /* [fastpath] nothing to do */
6690   if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case */
6691     *uar=(Unit)(*uar*powers[shift]);
6692     return digits+shift;
6693     }
6694
6695   next=0;                          /* all paths */
6696   source=uar+D2U(digits)-1;        /* where msu comes from */
6697   target=source+D2U(shift);        /* where upper part of first cut goes */
6698   cut=DECDPUN-MSUDIGITS(shift);    /* where to slice */
6699   if (cut==0) {                    /* unit-boundary case */
6700     for (; source>=uar; source--, target--) *target=*source;
6701     }
6702    else {
6703     first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6704     for (; source>=uar; source--, target--) {
6705       /* split the source Unit and accumulate remainder for next */
6706       #if DECDPUN<=4
6707         uInt quot=QUOT10(*source, cut);
6708         uInt rem=*source-quot*powers[cut];
6709         next+=quot;
6710       #else
6711         uInt rem=*source%powers[cut];
6712         next+=*source/powers[cut];
6713       #endif
6714       if (target<=first) *target=(Unit)next;   /* write to target iff valid */
6715       next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit */
6716       }
6717     } /* shift-move */
6718
6719   /* propagate any partial unit to one below and clear the rest */
6720   for (; target>=uar; target--) {
6721     *target=(Unit)next;
6722     next=0;
6723     }
6724   return digits+shift;
6725   } /* decShiftToMost */
6726
6727 /* ------------------------------------------------------------------ */
6728 /* decShiftToLeast -- shift digits in array towards least significant */
6729 /*                                                                    */
6730 /*   uar   is the array                                               */
6731 /*   units is length of the array, in units                           */
6732 /*   shift is the number of digits to remove from the lsu end; it     */
6733 /*     must be zero or positive and <= than units*DECDPUN.            */
6734 /*                                                                    */
6735 /*   returns the new length of the integer in the array, in units     */
6736 /*                                                                    */
6737 /* Removed digits are discarded (lost).  Units not required to hold   */
6738 /* the final result are unchanged.                                    */
6739 /* ------------------------------------------------------------------ */
6740 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6741   Unit  *target, *up;              /* work */
6742   Int   cut, count;                /* work */
6743   Int   quot, rem;                 /* for division */
6744
6745   if (shift==0) return units;      /* [fastpath] nothing to do */
6746   if (shift==units*DECDPUN) {      /* [fastpath] little to do */
6747     *uar=0;                        /* all digits cleared gives zero */
6748     return 1;                      /* leaves just the one */
6749     }
6750
6751   target=uar;                      /* both paths */
6752   cut=MSUDIGITS(shift);
6753   if (cut==DECDPUN) {              /* unit-boundary case; easy */
6754     up=uar+D2U(shift);
6755     for (; up<uar+units; target++, up++) *target=*up;
6756     return target-uar;
6757     }
6758
6759   /* messier */
6760   up=uar+D2U(shift-cut);           /* source; correct to whole Units */
6761   count=units*DECDPUN-shift;       /* the maximum new length */
6762   #if DECDPUN<=4
6763     quot=QUOT10(*up, cut);
6764   #else
6765     quot=*up/powers[cut];
6766   #endif
6767   for (; ; target++) {
6768     *target=(Unit)quot;
6769     count-=(DECDPUN-cut);
6770     if (count<=0) break;
6771     up++;
6772     quot=*up;
6773     #if DECDPUN<=4
6774       quot=QUOT10(quot, cut);
6775       rem=*up-quot*powers[cut];
6776     #else
6777       rem=quot%powers[cut];
6778       quot=quot/powers[cut];
6779     #endif
6780     *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6781     count-=cut;
6782     if (count<=0) break;
6783     }
6784   return target-uar+1;
6785   } /* decShiftToLeast */
6786
6787 #if DECSUBSET
6788 /* ------------------------------------------------------------------ */
6789 /* decRoundOperand -- round an operand  [used for subset only]        */
6790 /*                                                                    */
6791 /*   dn is the number to round (dn->digits is > set->digits)          */
6792 /*   set is the relevant context                                      */
6793 /*   status is the status accumulator                                 */
6794 /*                                                                    */
6795 /*   returns an allocated decNumber with the rounded result.          */
6796 /*                                                                    */
6797 /* lostDigits and other status may be set by this.                    */
6798 /*                                                                    */
6799 /* Since the input is an operand, it must not be modified.            */
6800 /* Instead, return an allocated decNumber, rounded as required.       */
6801 /* It is the caller's responsibility to free the allocated storage.   */
6802 /*                                                                    */
6803 /* If no storage is available then the result cannot be used, so NULL */
6804 /* is returned.                                                       */
6805 /* ------------------------------------------------------------------ */
6806 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6807                                   uInt *status) {
6808   decNumber *res;                       /* result structure */
6809   uInt newstatus=0;                     /* status from round */
6810   Int  residue=0;                       /* rounding accumulator */
6811
6812   /* Allocate storage for the returned decNumber, big enough for the */
6813   /* length specified by the context */
6814   res=(decNumber *)malloc(sizeof(decNumber)
6815                           +(D2U(set->digits)-1)*sizeof(Unit));
6816   if (res==NULL) {
6817     *status|=DEC_Insufficient_storage;
6818     return NULL;
6819     }
6820   decCopyFit(res, dn, set, &residue, &newstatus);
6821   decApplyRound(res, set, residue, &newstatus);
6822
6823   /* If that set Inexact then "lost digits" is raised... */
6824   if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6825   *status|=newstatus;
6826   return res;
6827   } /* decRoundOperand */
6828 #endif
6829
6830 /* ------------------------------------------------------------------ */
6831 /* decCopyFit -- copy a number, truncating the coefficient if needed  */
6832 /*                                                                    */
6833 /*   dest is the target decNumber                                     */
6834 /*   src  is the source decNumber                                     */
6835 /*   set is the context [used for length (digits) and rounding mode]  */
6836 /*   residue is the residue accumulator                               */
6837 /*   status contains the current status to be updated                 */
6838 /*                                                                    */
6839 /* (dest==src is allowed and will be a no-op if fits)                 */
6840 /* All fields are updated as required.                                */
6841 /* ------------------------------------------------------------------ */
6842 static void decCopyFit(decNumber *dest, const decNumber *src,
6843                        decContext *set, Int *residue, uInt *status) {
6844   dest->bits=src->bits;
6845   dest->exponent=src->exponent;
6846   decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6847   } /* decCopyFit */
6848
6849 /* ------------------------------------------------------------------ */
6850 /* decSetCoeff -- set the coefficient of a number                     */
6851 /*                                                                    */
6852 /*   dn    is the number whose coefficient array is to be set.        */
6853 /*         It must have space for set->digits digits                  */
6854 /*   set   is the context [for size]                                  */
6855 /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6856 /*   len   is digits in the source coefficient [may be dn->digits]    */
6857 /*   residue is the residue accumulator.  This has values as in       */
6858 /*         decApplyRound, and will be unchanged unless the            */
6859 /*         target size is less than len.  In this case, the           */
6860 /*         coefficient is truncated and the residue is updated to     */
6861 /*         reflect the previous residue and the dropped digits.       */
6862 /*   status is the status accumulator, as usual                       */
6863 /*                                                                    */
6864 /* The coefficient may already be in the number, or it can be an      */
6865 /* external intermediate array.  If it is in the number, lsu must ==  */
6866 /* dn->lsu and len must == dn->digits.                                */
6867 /*                                                                    */
6868 /* Note that the coefficient length (len) may be < set->digits, and   */
6869 /* in this case this merely copies the coefficient (or is a no-op     */
6870 /* if dn->lsu==lsu).                                                  */
6871 /*                                                                    */
6872 /* Note also that (only internally, from decQuantizeOp and            */
6873 /* decSetSubnormal) the value of set->digits may be less than one,    */
6874 /* indicating a round to left.  This routine handles that case        */
6875 /* correctly; caller ensures space.                                   */
6876 /*                                                                    */
6877 /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6878 /* updated as necessary.   dn->bits (sign) is unchanged.              */
6879 /*                                                                    */
6880 /* DEC_Rounded status is set if any digits are discarded.             */
6881 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6882 /*                       incoming residue was non-0 (implies rounded) */
6883 /* ------------------------------------------------------------------ */
6884 /* mapping array: maps 0-9 to canonical residues, so that a residue */
6885 /* can be adjusted in the range [-1, +1] and achieve correct rounding */
6886 /*                             0  1  2  3  4  5  6  7  8  9 */
6887 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6888 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6889                         Int len, Int *residue, uInt *status) {
6890   Int   discard;              /* number of digits to discard */
6891   uInt  cut;                  /* cut point in Unit */
6892   const Unit *up;             /* work */
6893   Unit  *target;              /* .. */
6894   Int   count;                /* .. */
6895   #if DECDPUN<=4
6896   uInt  temp;                 /* .. */
6897   #endif
6898
6899   discard=len-set->digits;    /* digits to discard */
6900   if (discard<=0) {           /* no digits are being discarded */
6901     if (dn->lsu!=lsu) {       /* copy needed */
6902       /* copy the coefficient array to the result number; no shift needed */
6903       count=len;              /* avoids D2U */
6904       up=lsu;
6905       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6906         *target=*up;
6907       dn->digits=len;         /* set the new length */
6908       }
6909     /* dn->exponent and residue are unchanged, record any inexactitude */
6910     if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6911     return;
6912     }
6913
6914   /* some digits must be discarded ... */
6915   dn->exponent+=discard;      /* maintain numerical value */
6916   *status|=DEC_Rounded;       /* accumulate Rounded status */
6917   if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6918
6919   if (discard>len) {          /* everything, +1, is being discarded */
6920     /* guard digit is 0 */
6921     /* residue is all the number [NB could be all 0s] */
6922     if (*residue<=0) {        /* not already positive */
6923       count=len;              /* avoids D2U */
6924       for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6925         *residue=1;
6926         break;                /* no need to check any others */
6927         }
6928       }
6929     if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6930     *dn->lsu=0;               /* coefficient will now be 0 */
6931     dn->digits=1;             /* .. */
6932     return;
6933     } /* total discard */
6934
6935   /* partial discard [most common case] */
6936   /* here, at least the first (most significant) discarded digit exists */
6937
6938   /* spin up the number, noting residue during the spin, until get to */
6939   /* the Unit with the first discarded digit.  When reach it, extract */
6940   /* it and remember its position */
6941   count=0;
6942   for (up=lsu;; up++) {
6943     count+=DECDPUN;
6944     if (count>=discard) break; /* full ones all checked */
6945     if (*up!=0) *residue=1;
6946     } /* up */
6947
6948   /* here up -> Unit with first discarded digit */
6949   cut=discard-(count-DECDPUN)-1;
6950   if (cut==DECDPUN-1) {       /* unit-boundary case (fast) */
6951     Unit half=(Unit)powers[DECDPUN]>>1;
6952     /* set residue directly */
6953     if (*up>=half) {
6954       if (*up>half) *residue=7;
6955       else *residue+=5;       /* add sticky bit */
6956       }
6957      else { /* <half */
6958       if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
6959       }
6960     if (set->digits<=0) {     /* special for Quantize/Subnormal :-( */
6961       *dn->lsu=0;             /* .. result is 0 */
6962       dn->digits=1;           /* .. */
6963       }
6964      else {                   /* shift to least */
6965       count=set->digits;      /* now digits to end up with */
6966       dn->digits=count;       /* set the new length */
6967       up++;                   /* move to next */
6968       /* on unit boundary, so shift-down copy loop is simple */
6969       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6970         *target=*up;
6971       }
6972     } /* unit-boundary case */
6973
6974    else { /* discard digit is in low digit(s), and not top digit */
6975     uInt  discard1;                /* first discarded digit */
6976     uInt  quot, rem;               /* for divisions */
6977     if (cut==0) quot=*up;          /* is at bottom of unit */
6978      else /* cut>0 */ {            /* it's not at bottom of unit */
6979       #if DECDPUN<=4
6980         quot=QUOT10(*up, cut);
6981         rem=*up-quot*powers[cut];
6982       #else
6983         rem=*up%powers[cut];
6984         quot=*up/powers[cut];
6985       #endif
6986       if (rem!=0) *residue=1;
6987       }
6988     /* discard digit is now at bottom of quot */
6989     #if DECDPUN<=4
6990       temp=(quot*6554)>>16;        /* fast /10 */
6991       /* Vowels algorithm here not a win (9 instructions) */
6992       discard1=quot-X10(temp);
6993       quot=temp;
6994     #else
6995       discard1=quot%10;
6996       quot=quot/10;
6997     #endif
6998     /* here, discard1 is the guard digit, and residue is everything */
6999     /* else [use mapping array to accumulate residue safely] */
7000     *residue+=resmap[discard1];
7001     cut++;                         /* update cut */
7002     /* here: up -> Unit of the array with bottom digit */
7003     /*       cut is the division point for each Unit */
7004     /*       quot holds the uncut high-order digits for the current unit */
7005     if (set->digits<=0) {          /* special for Quantize/Subnormal :-( */
7006       *dn->lsu=0;                  /* .. result is 0 */
7007       dn->digits=1;                /* .. */
7008       }
7009      else {                        /* shift to least needed */
7010       count=set->digits;           /* now digits to end up with */
7011       dn->digits=count;            /* set the new length */
7012       /* shift-copy the coefficient array to the result number */
7013       for (target=dn->lsu; ; target++) {
7014         *target=(Unit)quot;
7015         count-=(DECDPUN-cut);
7016         if (count<=0) break;
7017         up++;
7018         quot=*up;
7019         #if DECDPUN<=4
7020           quot=QUOT10(quot, cut);
7021           rem=*up-quot*powers[cut];
7022         #else
7023           rem=quot%powers[cut];
7024           quot=quot/powers[cut];
7025         #endif
7026         *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7027         count-=cut;
7028         if (count<=0) break;
7029         } /* shift-copy loop */
7030       } /* shift to least */
7031     } /* not unit boundary */
7032
7033   if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7034   return;
7035   } /* decSetCoeff */
7036
7037 /* ------------------------------------------------------------------ */
7038 /* decApplyRound -- apply pending rounding to a number                */
7039 /*                                                                    */
7040 /*   dn    is the number, with space for set->digits digits           */
7041 /*   set   is the context [for size and rounding mode]                */
7042 /*   residue indicates pending rounding, being any accumulated        */
7043 /*         guard and sticky information.  It may be:                  */
7044 /*         6-9: rounding digit is >5                                  */
7045 /*         5:   rounding digit is exactly half-way                    */
7046 /*         1-4: rounding digit is <5 and >0                           */
7047 /*         0:   the coefficient is exact                              */
7048 /*        -1:   as 1, but the hidden digits are subtractive, that     */
7049 /*              is, of the opposite sign to dn.  In this case the     */
7050 /*              coefficient must be non-0.  This case occurs when     */
7051 /*              subtracting a small number (which can be reduced to   */
7052 /*              a sticky bit); see decAddOp.                          */
7053 /*   status is the status accumulator, as usual                       */
7054 /*                                                                    */
7055 /* This routine applies rounding while keeping the length of the      */
7056 /* coefficient constant.  The exponent and status are unchanged       */
7057 /* except if:                                                         */
7058 /*                                                                    */
7059 /*   -- the coefficient was increased and is all nines (in which      */
7060 /*      case Overflow could occur, and is handled directly here so    */
7061 /*      the caller does not need to re-test for overflow)             */
7062 /*                                                                    */
7063 /*   -- the coefficient was decreased and becomes all nines (in which */
7064 /*      case Underflow could occur, and is also handled directly).    */
7065 /*                                                                    */
7066 /* All fields in dn are updated as required.                          */
7067 /*                                                                    */
7068 /* ------------------------------------------------------------------ */
7069 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7070                           uInt *status) {
7071   Int  bump;                  /* 1 if coefficient needs to be incremented */
7072                               /* -1 if coefficient needs to be decremented */
7073
7074   if (residue==0) return;     /* nothing to apply */
7075
7076   bump=0;                     /* assume a smooth ride */
7077
7078   /* now decide whether, and how, to round, depending on mode */
7079   switch (set->round) {
7080     case DEC_ROUND_05UP: {    /* round zero or five up (for reround) */
7081       /* This is the same as DEC_ROUND_DOWN unless there is a */
7082       /* positive residue and the lsd of dn is 0 or 5, in which case */
7083       /* it is bumped; when residue is <0, the number is therefore */
7084       /* bumped down unless the final digit was 1 or 6 (in which */
7085       /* case it is bumped down and then up -- a no-op) */
7086       Int lsd5=*dn->lsu%5;     /* get lsd and quintate */
7087       if (residue<0 && lsd5!=1) bump=-1;
7088        else if (residue>0 && lsd5==0) bump=1;
7089       /* [bump==1 could be applied directly; use common path for clarity] */
7090       break;} /* r-05 */
7091
7092     case DEC_ROUND_DOWN: {
7093       /* no change, except if negative residue */
7094       if (residue<0) bump=-1;
7095       break;} /* r-d */
7096
7097     case DEC_ROUND_HALF_DOWN: {
7098       if (residue>5) bump=1;
7099       break;} /* r-h-d */
7100
7101     case DEC_ROUND_HALF_EVEN: {
7102       if (residue>5) bump=1;            /* >0.5 goes up */
7103        else if (residue==5) {           /* exactly 0.5000... */
7104         /* 0.5 goes up iff [new] lsd is odd */
7105         if (*dn->lsu & 0x01) bump=1;
7106         }
7107       break;} /* r-h-e */
7108
7109     case DEC_ROUND_HALF_UP: {
7110       if (residue>=5) bump=1;
7111       break;} /* r-h-u */
7112
7113     case DEC_ROUND_UP: {
7114       if (residue>0) bump=1;
7115       break;} /* r-u */
7116
7117     case DEC_ROUND_CEILING: {
7118       /* same as _UP for positive numbers, and as _DOWN for negatives */
7119       /* [negative residue cannot occur on 0] */
7120       if (decNumberIsNegative(dn)) {
7121         if (residue<0) bump=-1;
7122         }
7123        else {
7124         if (residue>0) bump=1;
7125         }
7126       break;} /* r-c */
7127
7128     case DEC_ROUND_FLOOR: {
7129       /* same as _UP for negative numbers, and as _DOWN for positive */
7130       /* [negative residue cannot occur on 0] */
7131       if (!decNumberIsNegative(dn)) {
7132         if (residue<0) bump=-1;
7133         }
7134        else {
7135         if (residue>0) bump=1;
7136         }
7137       break;} /* r-f */
7138
7139     default: {      /* e.g., DEC_ROUND_MAX */
7140       *status|=DEC_Invalid_context;
7141       #if DECTRACE || (DECCHECK && DECVERB)
7142       printf("Unknown rounding mode: %d\n", set->round);
7143       #endif
7144       break;}
7145     } /* switch */
7146
7147   /* now bump the number, up or down, if need be */
7148   if (bump==0) return;                       /* no action required */
7149
7150   /* Simply use decUnitAddSub unless bumping up and the number is */
7151   /* all nines.  In this special case set to 100... explicitly */
7152   /* and adjust the exponent by one (as otherwise could overflow */
7153   /* the array) */
7154   /* Similarly handle all-nines result if bumping down. */
7155   if (bump>0) {
7156     Unit *up;                                /* work */
7157     uInt count=dn->digits;                   /* digits to be checked */
7158     for (up=dn->lsu; ; up++) {
7159       if (count<=DECDPUN) {
7160         /* this is the last Unit (the msu) */
7161         if (*up!=powers[count]-1) break;     /* not still 9s */
7162         /* here if it, too, is all nines */
7163         *up=(Unit)powers[count-1];           /* here 999 -> 100 etc. */
7164         for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7165         dn->exponent++;                      /* and bump exponent */
7166         /* [which, very rarely, could cause Overflow...] */
7167         if ((dn->exponent+dn->digits)>set->emax+1) {
7168           decSetOverflow(dn, set, status);
7169           }
7170         return;                              /* done */
7171         }
7172       /* a full unit to check, with more to come */
7173       if (*up!=DECDPUNMAX) break;            /* not still 9s */
7174       count-=DECDPUN;
7175       } /* up */
7176     } /* bump>0 */
7177    else {                                    /* -1 */
7178     /* here checking for a pre-bump of 1000... (leading 1, all */
7179     /* other digits zero) */
7180     Unit *up, *sup;                          /* work */
7181     uInt count=dn->digits;                   /* digits to be checked */
7182     for (up=dn->lsu; ; up++) {
7183       if (count<=DECDPUN) {
7184         /* this is the last Unit (the msu) */
7185         if (*up!=powers[count-1]) break;     /* not 100.. */
7186         /* here if have the 1000... case */
7187         sup=up;                              /* save msu pointer */
7188         *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999 */
7189         /* others all to all-nines, too */
7190         for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7191         dn->exponent--;                      /* and bump exponent */
7192
7193         /* iff the number was at the subnormal boundary (exponent=etiny) */
7194         /* then the exponent is now out of range, so it will in fact get */
7195         /* clamped to etiny and the final 9 dropped. */
7196         /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7197         /*        dn->exponent, set->digits); */
7198         if (dn->exponent+1==set->emin-set->digits+1) {
7199           if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9] */
7200            else {
7201             *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99.. */
7202             dn->digits--;
7203             }
7204           dn->exponent++;
7205           *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7206           }
7207         return;                              /* done */
7208         }
7209
7210       /* a full unit to check, with more to come */
7211       if (*up!=0) break;                     /* not still 0s */
7212       count-=DECDPUN;
7213       } /* up */
7214
7215     } /* bump<0 */
7216
7217   /* Actual bump needed.  Do it. */
7218   decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7219   } /* decApplyRound */
7220
7221 #if DECSUBSET
7222 /* ------------------------------------------------------------------ */
7223 /* decFinish -- finish processing a number                            */
7224 /*                                                                    */
7225 /*   dn is the number                                                 */
7226 /*   set is the context                                               */
7227 /*   residue is the rounding accumulator (as in decApplyRound)        */
7228 /*   status is the accumulator                                        */
7229 /*                                                                    */
7230 /* This finishes off the current number by:                           */
7231 /*    1. If not extended:                                             */
7232 /*       a. Converting a zero result to clean '0'                     */
7233 /*       b. Reducing positive exponents to 0, if would fit in digits  */
7234 /*    2. Checking for overflow and subnormals (always)                */
7235 /* Note this is just Finalize when no subset arithmetic.              */
7236 /* All fields are updated as required.                                */
7237 /* ------------------------------------------------------------------ */
7238 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7239                       uInt *status) {
7240   if (!set->extended) {
7241     if ISZERO(dn) {                /* value is zero */
7242       dn->exponent=0;              /* clean exponent .. */
7243       dn->bits=0;                  /* .. and sign */
7244       return;                      /* no error possible */
7245       }
7246     if (dn->exponent>=0) {         /* non-negative exponent */
7247       /* >0; reduce to integer if possible */
7248       if (set->digits >= (dn->exponent+dn->digits)) {
7249         dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7250         dn->exponent=0;
7251         }
7252       }
7253     } /* !extended */
7254
7255   decFinalize(dn, set, residue, status);
7256   } /* decFinish */
7257 #endif
7258
7259 /* ------------------------------------------------------------------ */
7260 /* decFinalize -- final check, clamp, and round of a number           */
7261 /*                                                                    */
7262 /*   dn is the number                                                 */
7263 /*   set is the context                                               */
7264 /*   residue is the rounding accumulator (as in decApplyRound)        */
7265 /*   status is the status accumulator                                 */
7266 /*                                                                    */
7267 /* This finishes off the current number by checking for subnormal     */
7268 /* results, applying any pending rounding, checking for overflow,     */
7269 /* and applying any clamping.                                         */
7270 /* Underflow and overflow conditions are raised as appropriate.       */
7271 /* All fields are updated as required.                                */
7272 /* ------------------------------------------------------------------ */
7273 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7274                         uInt *status) {
7275   Int shift;                            /* shift needed if clamping */
7276   Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary */
7277
7278   /* Must be careful, here, when checking the exponent as the */
7279   /* adjusted exponent could overflow 31 bits [because it may already */
7280   /* be up to twice the expected]. */
7281
7282   /* First test for subnormal.  This must be done before any final */
7283   /* round as the result could be rounded to Nmin or 0. */
7284   if (dn->exponent<=tinyexp) {          /* prefilter */
7285     Int comp;
7286     decNumber nmin;
7287     /* A very nasty case here is dn == Nmin and residue<0 */
7288     if (dn->exponent<tinyexp) {
7289       /* Go handle subnormals; this will apply round if needed. */
7290       decSetSubnormal(dn, set, residue, status);
7291       return;
7292       }
7293     /* Equals case: only subnormal if dn=Nmin and negative residue */
7294     decNumberZero(&nmin);
7295     nmin.lsu[0]=1;
7296     nmin.exponent=set->emin;
7297     comp=decCompare(dn, &nmin, 1);                /* (signless compare) */
7298     if (comp==BADINT) {                           /* oops */
7299       *status|=DEC_Insufficient_storage;          /* abandon... */
7300       return;
7301       }
7302     if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin */
7303       decApplyRound(dn, set, *residue, status);   /* might force down */
7304       decSetSubnormal(dn, set, residue, status);
7305       return;
7306       }
7307     }
7308
7309   /* now apply any pending round (this could raise overflow). */
7310   if (*residue!=0) decApplyRound(dn, set, *residue, status);
7311
7312   /* Check for overflow [redundant in the 'rare' case] or clamp */
7313   if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed */
7314
7315
7316   /* here when might have an overflow or clamp to do */
7317   if (dn->exponent>set->emax-dn->digits+1) {           /* too big */
7318     decSetOverflow(dn, set, status);
7319     return;
7320     }
7321   /* here when the result is normal but in clamp range */
7322   if (!set->clamp) return;
7323
7324   /* here when need to apply the IEEE exponent clamp (fold-down) */
7325   shift=dn->exponent-(set->emax-set->digits+1);
7326
7327   /* shift coefficient (if non-zero) */
7328   if (!ISZERO(dn)) {
7329     dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7330     }
7331   dn->exponent-=shift;   /* adjust the exponent to match */
7332   *status|=DEC_Clamped;  /* and record the dirty deed */
7333   return;
7334   } /* decFinalize */
7335
7336 /* ------------------------------------------------------------------ */
7337 /* decSetOverflow -- set number to proper overflow value              */
7338 /*                                                                    */
7339 /*   dn is the number (used for sign [only] and result)               */
7340 /*   set is the context [used for the rounding mode, etc.]            */
7341 /*   status contains the current status to be updated                 */
7342 /*                                                                    */
7343 /* This sets the sign of a number and sets its value to either        */
7344 /* Infinity or the maximum finite value, depending on the sign of     */
7345 /* dn and the rounding mode, following IEEE 754 rules.                */
7346 /* ------------------------------------------------------------------ */
7347 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7348   Flag needmax=0;                  /* result is maximum finite value */
7349   uByte sign=dn->bits&DECNEG;      /* clean and save sign bit */
7350
7351   if (ISZERO(dn)) {                /* zero does not overflow magnitude */
7352     Int emax=set->emax;                      /* limit value */
7353     if (set->clamp) emax-=set->digits-1;     /* lower if clamping */
7354     if (dn->exponent>emax) {                 /* clamp required */
7355       dn->exponent=emax;
7356       *status|=DEC_Clamped;
7357       }
7358     return;
7359     }
7360
7361   decNumberZero(dn);
7362   switch (set->round) {
7363     case DEC_ROUND_DOWN: {
7364       needmax=1;                   /* never Infinity */
7365       break;} /* r-d */
7366     case DEC_ROUND_05UP: {
7367       needmax=1;                   /* never Infinity */
7368       break;} /* r-05 */
7369     case DEC_ROUND_CEILING: {
7370       if (sign) needmax=1;         /* Infinity if non-negative */
7371       break;} /* r-c */
7372     case DEC_ROUND_FLOOR: {
7373       if (!sign) needmax=1;        /* Infinity if negative */
7374       break;} /* r-f */
7375     default: break;                /* Infinity in all other cases */
7376     }
7377   if (needmax) {
7378     decSetMaxValue(dn, set);
7379     dn->bits=sign;                 /* set sign */
7380     }
7381    else dn->bits=sign|DECINF;      /* Value is +/-Infinity */
7382   *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7383   } /* decSetOverflow */
7384
7385 /* ------------------------------------------------------------------ */
7386 /* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7387 /*                                                                    */
7388 /*   dn is the number to set                                          */
7389 /*   set is the context [used for digits and emax]                    */
7390 /*                                                                    */
7391 /* This sets the number to the maximum positive value.                */
7392 /* ------------------------------------------------------------------ */
7393 static void decSetMaxValue(decNumber *dn, decContext *set) {
7394   Unit *up;                        /* work */
7395   Int count=set->digits;           /* nines to add */
7396   dn->digits=count;
7397   /* fill in all nines to set maximum value */
7398   for (up=dn->lsu; ; up++) {
7399     if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines */
7400      else {                             /* this is the msu */
7401       *up=(Unit)(powers[count]-1);
7402       break;
7403       }
7404     count-=DECDPUN;                /* filled those digits */
7405     } /* up */
7406   dn->bits=0;                      /* + sign */
7407   dn->exponent=set->emax-set->digits+1;
7408   } /* decSetMaxValue */
7409
7410 /* ------------------------------------------------------------------ */
7411 /* decSetSubnormal -- process value whose exponent is <Emin           */
7412 /*                                                                    */
7413 /*   dn is the number (used as input as well as output; it may have   */
7414 /*         an allowed subnormal value, which may need to be rounded)  */
7415 /*   set is the context [used for the rounding mode]                  */
7416 /*   residue is any pending residue                                   */
7417 /*   status contains the current status to be updated                 */
7418 /*                                                                    */
7419 /* If subset mode, set result to zero and set Underflow flags.        */
7420 /*                                                                    */
7421 /* Value may be zero with a low exponent; this does not set Subnormal */
7422 /* but the exponent will be clamped to Etiny.                         */
7423 /*                                                                    */
7424 /* Otherwise ensure exponent is not out of range, and round as        */
7425 /* necessary.  Underflow is set if the result is Inexact.             */
7426 /* ------------------------------------------------------------------ */
7427 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7428                             uInt *status) {
7429   decContext workset;         /* work */
7430   Int        etiny, adjust;   /* .. */
7431
7432   #if DECSUBSET
7433   /* simple set to zero and 'hard underflow' for subset */
7434   if (!set->extended) {
7435     decNumberZero(dn);
7436     /* always full overflow */
7437     *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7438     return;
7439     }
7440   #endif
7441
7442   /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7443   /* (Etiny) if needed */
7444   etiny=set->emin-(set->digits-1);      /* smallest allowed exponent */
7445
7446   if ISZERO(dn) {                       /* value is zero */
7447     /* residue can never be non-zero here */
7448     #if DECCHECK
7449       if (*residue!=0) {
7450         printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7451         *status|=DEC_Invalid_operation;
7452         }
7453     #endif
7454     if (dn->exponent<etiny) {           /* clamp required */
7455       dn->exponent=etiny;
7456       *status|=DEC_Clamped;
7457       }
7458     return;
7459     }
7460
7461   *status|=DEC_Subnormal;               /* have a non-zero subnormal */
7462   adjust=etiny-dn->exponent;            /* calculate digits to remove */
7463   if (adjust<=0) {                      /* not out of range; unrounded */
7464     /* residue can never be non-zero here, except in the Nmin-residue */
7465     /* case (which is a subnormal result), so can take fast-path here */
7466     /* it may already be inexact (from setting the coefficient) */
7467     if (*status&DEC_Inexact) *status|=DEC_Underflow;
7468     return;
7469     }
7470
7471   /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7472   /* [this code is similar to that in rescale] */
7473   workset=*set;                         /* clone rounding, etc. */
7474   workset.digits=dn->digits-adjust;     /* set requested length */
7475   workset.emin-=adjust;                 /* and adjust emin to match */
7476   /* [note that the latter can be <1, here, similar to Rescale case] */
7477   decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7478   decApplyRound(dn, &workset, *residue, status);
7479
7480   /* Use 754 default rule: Underflow is set iff Inexact */
7481   /* [independent of whether trapped] */
7482   if (*status&DEC_Inexact) *status|=DEC_Underflow;
7483
7484   /* if rounded up a 999s case, exponent will be off by one; adjust */
7485   /* back if so [it will fit, because it was shortened earlier] */
7486   if (dn->exponent>etiny) {
7487     dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7488     dn->exponent--;                     /* (re)adjust the exponent. */
7489     }
7490
7491   /* if rounded to zero, it is by definition clamped... */
7492   if (ISZERO(dn)) *status|=DEC_Clamped;
7493   } /* decSetSubnormal */
7494
7495 /* ------------------------------------------------------------------ */
7496 /* decCheckMath - check entry conditions for a math function          */
7497 /*                                                                    */
7498 /*   This checks the context and the operand                          */
7499 /*                                                                    */
7500 /*   rhs is the operand to check                                      */
7501 /*   set is the context to check                                      */
7502 /*   status is unchanged if both are good                             */
7503 /*                                                                    */
7504 /* returns non-zero if status is changed, 0 otherwise                 */
7505 /*                                                                    */
7506 /* Restrictions enforced:                                             */
7507 /*                                                                    */
7508 /*   digits, emax, and -emin in the context must be less than         */
7509 /*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7510 /*   non-zero.  Invalid_operation is set in the status if a           */
7511 /*   restriction is violated.                                         */
7512 /* ------------------------------------------------------------------ */
7513 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7514                          uInt *status) {
7515   uInt save=*status;                         /* record */
7516   if (set->digits>DEC_MAX_MATH
7517    || set->emax>DEC_MAX_MATH
7518    || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7519    else if ((rhs->digits>DEC_MAX_MATH
7520      || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7521      || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7522      && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7523   return (*status!=save);
7524   } /* decCheckMath */
7525
7526 /* ------------------------------------------------------------------ */
7527 /* decGetInt -- get integer from a number                             */
7528 /*                                                                    */
7529 /*   dn is the number [which will not be altered]                     */
7530 /*                                                                    */
7531 /*   returns one of:                                                  */
7532 /*     BADINT if there is a non-zero fraction                         */
7533 /*     the converted integer                                          */
7534 /*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7535 /*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7536 /*                                                                    */
7537 /* This checks and gets a whole number from the input decNumber.      */
7538 /* The sign can be determined from dn by the caller when BIGEVEN or   */
7539 /* BIGODD is returned.                                                */
7540 /* ------------------------------------------------------------------ */
7541 static Int decGetInt(const decNumber *dn) {
7542   Int  theInt;                          /* result accumulator */
7543   const Unit *up;                       /* work */
7544   Int  got;                             /* digits (real or not) processed */
7545   Int  ilength=dn->digits+dn->exponent; /* integral length */
7546   Flag neg=decNumberIsNegative(dn);     /* 1 if -ve */
7547
7548   /* The number must be an integer that fits in 10 digits */
7549   /* Assert, here, that 10 is enough for any rescale Etiny */
7550   #if DEC_MAX_EMAX > 999999999
7551     #error GetInt may need updating [for Emax]
7552   #endif
7553   #if DEC_MIN_EMIN < -999999999
7554     #error GetInt may need updating [for Emin]
7555   #endif
7556   if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent */
7557
7558   up=dn->lsu;                           /* ready for lsu */
7559   theInt=0;                             /* ready to accumulate */
7560   if (dn->exponent>=0) {                /* relatively easy */
7561     /* no fractional part [usual]; allow for positive exponent */
7562     got=dn->exponent;
7563     }
7564    else { /* -ve exponent; some fractional part to check and discard */
7565     Int count=-dn->exponent;            /* digits to discard */
7566     /* spin up whole units until reach the Unit with the unit digit */
7567     for (; count>=DECDPUN; up++) {
7568       if (*up!=0) return BADINT;        /* non-zero Unit to discard */
7569       count-=DECDPUN;
7570       }
7571     if (count==0) got=0;                /* [a multiple of DECDPUN] */
7572      else {                             /* [not multiple of DECDPUN] */
7573       Int rem;                          /* work */
7574       /* slice off fraction digits and check for non-zero */
7575       #if DECDPUN<=4
7576         theInt=QUOT10(*up, count);
7577         rem=*up-theInt*powers[count];
7578       #else
7579         rem=*up%powers[count];          /* slice off discards */
7580         theInt=*up/powers[count];
7581       #endif
7582       if (rem!=0) return BADINT;        /* non-zero fraction */
7583       /* it looks good */
7584       got=DECDPUN-count;                /* number of digits so far */
7585       up++;                             /* ready for next */
7586       }
7587     }
7588   /* now it's known there's no fractional part */
7589
7590   /* tricky code now, to accumulate up to 9.3 digits */
7591   if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7592
7593   if (ilength<11) {
7594     Int save=theInt;
7595     /* collect any remaining unit(s) */
7596     for (; got<ilength; up++) {
7597       theInt+=*up*powers[got];
7598       got+=DECDPUN;
7599       }
7600     if (ilength==10) {                  /* need to check for wrap */
7601       if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7602          /* [that test also disallows the BADINT result case] */
7603        else if (neg && theInt>1999999997) ilength=11;
7604        else if (!neg && theInt>999999999) ilength=11;
7605       if (ilength==11) theInt=save;     /* restore correct low bit */
7606       }
7607     }
7608
7609   if (ilength>10) {                     /* too big */
7610     if (theInt&1) return BIGODD;        /* bottom bit 1 */
7611     return BIGEVEN;                     /* bottom bit 0 */
7612     }
7613
7614   if (neg) theInt=-theInt;              /* apply sign */
7615   return theInt;
7616   } /* decGetInt */
7617
7618 /* ------------------------------------------------------------------ */
7619 /* decDecap -- decapitate the coefficient of a number                 */
7620 /*                                                                    */
7621 /*   dn   is the number to be decapitated                             */
7622 /*   drop is the number of digits to be removed from the left of dn;  */
7623 /*     this must be <= dn->digits (if equal, the coefficient is       */
7624 /*     set to 0)                                                      */
7625 /*                                                                    */
7626 /* Returns dn; dn->digits will be <= the initial digits less drop     */
7627 /* (after removing drop digits there may be leading zero digits       */
7628 /* which will also be removed).  Only dn->lsu and dn->digits change.  */
7629 /* ------------------------------------------------------------------ */
7630 static decNumber *decDecap(decNumber *dn, Int drop) {
7631   Unit *msu;                            /* -> target cut point */
7632   Int cut;                              /* work */
7633   if (drop>=dn->digits) {               /* losing the whole thing */
7634     #if DECCHECK
7635     if (drop>dn->digits)
7636       printf("decDecap called with drop>digits [%ld>%ld]\n",
7637              (LI)drop, (LI)dn->digits);
7638     #endif
7639     dn->lsu[0]=0;
7640     dn->digits=1;
7641     return dn;
7642     }
7643   msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu */
7644   cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu */
7645   if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits */
7646   /* that may have left leading zero digits, so do a proper count... */
7647   dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7648   return dn;
7649   } /* decDecap */
7650
7651 /* ------------------------------------------------------------------ */
7652 /* decBiStr -- compare string with pairwise options                   */
7653 /*                                                                    */
7654 /*   targ is the string to compare                                    */
7655 /*   str1 is one of the strings to compare against (length may be 0)  */
7656 /*   str2 is the other; it must be the same length as str1            */
7657 /*                                                                    */
7658 /*   returns 1 if strings compare equal, (that is, it is the same     */
7659 /*   length as str1 and str2, and each character of targ is in either */
7660 /*   str1 or str2 in the corresponding position), or 0 otherwise      */
7661 /*                                                                    */
7662 /* This is used for generic caseless compare, including the awkward   */
7663 /* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7664 /*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7665 /* ------------------------------------------------------------------ */
7666 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7667   for (;;targ++, str1++, str2++) {
7668     if (*targ!=*str1 && *targ!=*str2) return 0;
7669     /* *targ has a match in one (or both, if terminator) */
7670     if (*targ=='\0') break;
7671     } /* forever */
7672   return 1;
7673   } /* decBiStr */
7674
7675 /* ------------------------------------------------------------------ */
7676 /* decNaNs -- handle NaN operand or operands                          */
7677 /*                                                                    */
7678 /*   res     is the result number                                     */
7679 /*   lhs     is the first operand                                     */
7680 /*   rhs     is the second operand, or NULL if none                   */
7681 /*   context is used to limit payload length                          */
7682 /*   status  contains the current status                              */
7683 /*   returns res in case convenient                                   */
7684 /*                                                                    */
7685 /* Called when one or both operands is a NaN, and propagates the      */
7686 /* appropriate result to res.  When an sNaN is found, it is changed   */
7687 /* to a qNaN and Invalid operation is set.                            */
7688 /* ------------------------------------------------------------------ */
7689 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7690                            const decNumber *rhs, decContext *set,
7691                            uInt *status) {
7692   /* This decision tree ends up with LHS being the source pointer, */
7693   /* and status updated if need be */
7694   if (lhs->bits & DECSNAN)
7695     *status|=DEC_Invalid_operation | DEC_sNaN;
7696    else if (rhs==NULL);
7697    else if (rhs->bits & DECSNAN) {
7698     lhs=rhs;
7699     *status|=DEC_Invalid_operation | DEC_sNaN;
7700     }
7701    else if (lhs->bits & DECNAN);
7702    else lhs=rhs;
7703
7704   /* propagate the payload */
7705   if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */
7706    else { /* too long */
7707     const Unit *ul;
7708     Unit *ur, *uresp1;
7709     /* copy safe number of units, then decapitate */
7710     res->bits=lhs->bits;                /* need sign etc. */
7711     uresp1=res->lsu+D2U(set->digits);
7712     for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7713     res->digits=D2U(set->digits)*DECDPUN;
7714     /* maybe still too long */
7715     if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7716     }
7717
7718   res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while */
7719   res->bits|=DECNAN;          /* .. preserving sign */
7720   res->exponent=0;            /* clean exponent */
7721                               /* [coefficient was copied/decapitated] */
7722   return res;
7723   } /* decNaNs */
7724
7725 /* ------------------------------------------------------------------ */
7726 /* decStatus -- apply non-zero status                                 */
7727 /*                                                                    */
7728 /*   dn     is the number to set if error                             */
7729 /*   status contains the current status (not yet in context)          */
7730 /*   set    is the context                                            */
7731 /*                                                                    */
7732 /* If the status is an error status, the number is set to a NaN,      */
7733 /* unless the error was an overflow, divide-by-zero, or underflow,    */
7734 /* in which case the number will have already been set.               */
7735 /*                                                                    */
7736 /* The context status is then updated with the new status.  Note that */
7737 /* this may raise a signal, so control may never return from this     */
7738 /* routine (hence resources must be recovered before it is called).   */
7739 /* ------------------------------------------------------------------ */
7740 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7741   if (status & DEC_NaNs) {              /* error status -> NaN */
7742     /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7743     if (status & DEC_sNaN) status&=~DEC_sNaN;
7744      else {
7745       decNumberZero(dn);                /* other error: clean throughout */
7746       dn->bits=DECNAN;                  /* and make a quiet NaN */
7747       }
7748     }
7749   decContextSetStatus(set, status);     /* [may not return] */
7750   return;
7751   } /* decStatus */
7752
7753 /* ------------------------------------------------------------------ */
7754 /* decGetDigits -- count digits in a Units array                      */
7755 /*                                                                    */
7756 /*   uar is the Unit array holding the number (this is often an       */
7757 /*          accumulator of some sort)                                 */
7758 /*   len is the length of the array in units [>=1]                    */
7759 /*                                                                    */
7760 /*   returns the number of (significant) digits in the array          */
7761 /*                                                                    */
7762 /* All leading zeros are excluded, except the last if the array has   */
7763 /* only zero Units.                                                   */
7764 /* ------------------------------------------------------------------ */
7765 /* This may be called twice during some operations. */
7766 static Int decGetDigits(Unit *uar, Int len) {
7767   Unit *up=uar+(len-1);            /* -> msu */
7768   Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu */
7769   #if DECDPUN>4
7770   uInt const *pow;                 /* work */
7771   #endif
7772                                    /* (at least 1 in final msu) */
7773   #if DECCHECK
7774   if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7775   #endif
7776
7777   for (; up>=uar; up--) {
7778     if (*up==0) {                  /* unit is all 0s */
7779       if (digits==1) break;        /* a zero has one digit */
7780       digits-=DECDPUN;             /* adjust for 0 unit */
7781       continue;}
7782     /* found the first (most significant) non-zero Unit */
7783     #if DECDPUN>1                  /* not done yet */
7784     if (*up<10) break;             /* is 1-9 */
7785     digits++;
7786     #if DECDPUN>2                  /* not done yet */
7787     if (*up<100) break;            /* is 10-99 */
7788     digits++;
7789     #if DECDPUN>3                  /* not done yet */
7790     if (*up<1000) break;           /* is 100-999 */
7791     digits++;
7792     #if DECDPUN>4                  /* count the rest ... */
7793     for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7794     #endif
7795     #endif
7796     #endif
7797     #endif
7798     break;
7799     } /* up */
7800   return digits;
7801   } /* decGetDigits */
7802
7803 #if DECTRACE | DECCHECK
7804 /* ------------------------------------------------------------------ */
7805 /* decNumberShow -- display a number [debug aid]                      */
7806 /*   dn is the number to show                                         */
7807 /*                                                                    */
7808 /* Shows: sign, exponent, coefficient (msu first), digits             */
7809 /*    or: sign, special-value                                         */
7810 /* ------------------------------------------------------------------ */
7811 /* this is public so other modules can use it */
7812 void decNumberShow(const decNumber *dn) {
7813   const Unit *up;                  /* work */
7814   uInt u, d;                       /* .. */
7815   Int cut;                         /* .. */
7816   char isign='+';                  /* main sign */
7817   if (dn==NULL) {
7818     printf("NULL\n");
7819     return;}
7820   if (decNumberIsNegative(dn)) isign='-';
7821   printf(" >> %c ", isign);
7822   if (dn->bits&DECSPECIAL) {       /* Is a special value */
7823     if (decNumberIsInfinite(dn)) printf("Infinity");
7824      else {                                  /* a NaN */
7825       if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN */
7826        else printf("NaN");
7827       }
7828     /* if coefficient and exponent are 0, no more to do */
7829     if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7830       printf("\n");
7831       return;}
7832     /* drop through to report other information */
7833     printf(" ");
7834     }
7835
7836   /* now carefully display the coefficient */
7837   up=dn->lsu+D2U(dn->digits)-1;         /* msu */
7838   printf("%ld", (LI)*up);
7839   for (up=up-1; up>=dn->lsu; up--) {
7840     u=*up;
7841     printf(":");
7842     for (cut=DECDPUN-1; cut>=0; cut--) {
7843       d=u/powers[cut];
7844       u-=d*powers[cut];
7845       printf("%ld", (LI)d);
7846       } /* cut */
7847     } /* up */
7848   if (dn->exponent!=0) {
7849     char esign='+';
7850     if (dn->exponent<0) esign='-';
7851     printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7852     }
7853   printf(" [%ld]\n", (LI)dn->digits);
7854   } /* decNumberShow */
7855 #endif
7856
7857 #if DECTRACE || DECCHECK
7858 /* ------------------------------------------------------------------ */
7859 /* decDumpAr -- display a unit array [debug/check aid]                */
7860 /*   name is a single-character tag name                              */
7861 /*   ar   is the array to display                                     */
7862 /*   len  is the length of the array in Units                         */
7863 /* ------------------------------------------------------------------ */
7864 static void decDumpAr(char name, const Unit *ar, Int len) {
7865   Int i;
7866   const char *spec;
7867   #if DECDPUN==9
7868     spec="%09d ";
7869   #elif DECDPUN==8
7870     spec="%08d ";
7871   #elif DECDPUN==7
7872     spec="%07d ";
7873   #elif DECDPUN==6
7874     spec="%06d ";
7875   #elif DECDPUN==5
7876     spec="%05d ";
7877   #elif DECDPUN==4
7878     spec="%04d ";
7879   #elif DECDPUN==3
7880     spec="%03d ";
7881   #elif DECDPUN==2
7882     spec="%02d ";
7883   #else
7884     spec="%d ";
7885   #endif
7886   printf("  :%c: ", name);
7887   for (i=len-1; i>=0; i--) {
7888     if (i==len-1) printf("%ld ", (LI)ar[i]);
7889      else printf(spec, ar[i]);
7890     }
7891   printf("\n");
7892   return;}
7893 #endif
7894
7895 #if DECCHECK
7896 /* ------------------------------------------------------------------ */
7897 /* decCheckOperands -- check operand(s) to a routine                  */
7898 /*   res is the result structure (not checked; it will be set to      */
7899 /*          quiet NaN if error found (and it is not NULL))            */
7900 /*   lhs is the first operand (may be DECUNRESU)                      */
7901 /*   rhs is the second (may be DECUNUSED)                             */
7902 /*   set is the context (may be DECUNCONT)                            */
7903 /*   returns 0 if both operands, and the context are clean, or 1      */
7904 /*     otherwise (in which case the context will show an error,       */
7905 /*     unless NULL).  Note that res is not cleaned; caller should     */
7906 /*     handle this so res=NULL case is safe.                          */
7907 /* The caller is expected to abandon immediately if 1 is returned.    */
7908 /* ------------------------------------------------------------------ */
7909 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7910                              const decNumber *rhs, decContext *set) {
7911   Flag bad=0;
7912   if (set==NULL) {                 /* oops; hopeless */
7913     #if DECTRACE || DECVERB
7914     printf("Reference to context is NULL.\n");
7915     #endif
7916     bad=1;
7917     return 1;}
7918    else if (set!=DECUNCONT
7919      && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7920     bad=1;
7921     #if DECTRACE || DECVERB
7922     printf("Bad context [digits=%ld round=%ld].\n",
7923            (LI)set->digits, (LI)set->round);
7924     #endif
7925     }
7926    else {
7927     if (res==NULL) {
7928       bad=1;
7929       #if DECTRACE
7930       /* this one not DECVERB as standard tests include NULL */
7931       printf("Reference to result is NULL.\n");
7932       #endif
7933       }
7934     if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7935     if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7936     }
7937   if (bad) {
7938     if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7939     if (res!=DECUNRESU && res!=NULL) {
7940       decNumberZero(res);
7941       res->bits=DECNAN;       /* qNaN */
7942       }
7943     }
7944   return bad;
7945   } /* decCheckOperands */
7946
7947 /* ------------------------------------------------------------------ */
7948 /* decCheckNumber -- check a number                                   */
7949 /*   dn is the number to check                                        */
7950 /*   returns 0 if the number is clean, or 1 otherwise                 */
7951 /*                                                                    */
7952 /* The number is considered valid if it could be a result from some   */
7953 /* operation in some valid context.                                   */
7954 /* ------------------------------------------------------------------ */
7955 static Flag decCheckNumber(const decNumber *dn) {
7956   const Unit *up;             /* work */
7957   uInt maxuint;               /* .. */
7958   Int ae, d, digits;          /* .. */
7959   Int emin, emax;             /* .. */
7960
7961   if (dn==NULL) {             /* hopeless */
7962     #if DECTRACE
7963     /* this one not DECVERB as standard tests include NULL */
7964     printf("Reference to decNumber is NULL.\n");
7965     #endif
7966     return 1;}
7967
7968   /* check special values */
7969   if (dn->bits & DECSPECIAL) {
7970     if (dn->exponent!=0) {
7971       #if DECTRACE || DECVERB
7972       printf("Exponent %ld (not 0) for a special value [%02x].\n",
7973              (LI)dn->exponent, dn->bits);
7974       #endif
7975       return 1;}
7976
7977     /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
7978     if (decNumberIsInfinite(dn)) {
7979       if (dn->digits!=1) {
7980         #if DECTRACE || DECVERB
7981         printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7982         #endif
7983         return 1;}
7984       if (*dn->lsu!=0) {
7985         #if DECTRACE || DECVERB
7986         printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7987         #endif
7988         decDumpAr('I', dn->lsu, D2U(dn->digits));
7989         return 1;}
7990       } /* Inf */
7991     /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
7992     /*             concrete formats (decimal64, etc.). */
7993     return 0;
7994     }
7995
7996   /* check the coefficient */
7997   if (dn->digits<1 || dn->digits>DECNUMMAXP) {
7998     #if DECTRACE || DECVERB
7999     printf("Digits %ld in number.\n", (LI)dn->digits);
8000     #endif
8001     return 1;}
8002
8003   d=dn->digits;
8004
8005   for (up=dn->lsu; d>0; up++) {
8006     if (d>DECDPUN) maxuint=DECDPUNMAX;
8007      else {                   /* reached the msu */
8008       maxuint=powers[d]-1;
8009       if (dn->digits>1 && *up<powers[d-1]) {
8010         #if DECTRACE || DECVERB
8011         printf("Leading 0 in number.\n");
8012         decNumberShow(dn);
8013         #endif
8014         return 1;}
8015       }
8016     if (*up>maxuint) {
8017       #if DECTRACE || DECVERB
8018       printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8019               (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8020       #endif
8021       return 1;}
8022     d-=DECDPUN;
8023     }
8024
8025   /* check the exponent.  Note that input operands can have exponents */
8026   /* which are out of the set->emin/set->emax and set->digits range */
8027   /* (just as they can have more digits than set->digits). */
8028   ae=dn->exponent+dn->digits-1;    /* adjusted exponent */
8029   emax=DECNUMMAXE;
8030   emin=DECNUMMINE;
8031   digits=DECNUMMAXP;
8032   if (ae<emin-(digits-1)) {
8033     #if DECTRACE || DECVERB
8034     printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8035     decNumberShow(dn);
8036     #endif
8037     return 1;}
8038   if (ae>+emax) {
8039     #if DECTRACE || DECVERB
8040     printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8041     decNumberShow(dn);
8042     #endif
8043     return 1;}
8044
8045   return 0;              /* it's OK */
8046   } /* decCheckNumber */
8047
8048 /* ------------------------------------------------------------------ */
8049 /* decCheckInexact -- check a normal finite inexact result has digits */
8050 /*   dn is the number to check                                        */
8051 /*   set is the context (for status and precision)                    */
8052 /*   sets Invalid operation, etc., if some digits are missing         */
8053 /* [this check is not made for DECSUBSET compilation or when          */
8054 /* subnormal is not set]                                              */
8055 /* ------------------------------------------------------------------ */
8056 static void decCheckInexact(const decNumber *dn, decContext *set) {
8057   #if !DECSUBSET && DECEXTFLAG
8058     if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8059      && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8060       #if DECTRACE || DECVERB
8061       printf("Insufficient digits [%ld] on normal Inexact result.\n",
8062              (LI)dn->digits);
8063       decNumberShow(dn);
8064       #endif
8065       decContextSetStatus(set, DEC_Invalid_operation);
8066       }
8067   #else
8068     /* next is a noop for quiet compiler */
8069     if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8070   #endif
8071   return;
8072   } /* decCheckInexact */
8073 #endif
8074
8075 #if DECALLOC
8076 #undef malloc
8077 #undef free
8078 /* ------------------------------------------------------------------ */
8079 /* decMalloc -- accountable allocation routine                        */
8080 /*   n is the number of bytes to allocate                             */
8081 /*                                                                    */
8082 /* Semantics is the same as the stdlib malloc routine, but bytes      */
8083 /* allocated are accounted for globally, and corruption fences are    */
8084 /* added before and after the 'actual' storage.                       */
8085 /* ------------------------------------------------------------------ */
8086 /* This routine allocates storage with an extra twelve bytes; 8 are   */
8087 /* at the start and hold:                                             */
8088 /*   0-3 the original length requested                                */
8089 /*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8090 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8091 /* ------------------------------------------------------------------ */
8092 static void *decMalloc(size_t n) {
8093   uInt  size=n+12;                 /* true size */
8094   void  *alloc;                    /* -> allocated storage */
8095   uByte *b, *b0;                   /* work */
8096   uInt  uiwork;                    /* for macros */
8097
8098   alloc=malloc(size);              /* -> allocated storage */
8099   if (alloc==NULL) return NULL;    /* out of strorage */
8100   b0=(uByte *)alloc;               /* as bytes */
8101   decAllocBytes+=n;                /* account for storage */
8102   UBFROMUI(alloc, n);              /* save n */
8103   /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n); */
8104   for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8105   for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8106   return b0+8;                     /* -> play area */
8107   } /* decMalloc */
8108
8109 /* ------------------------------------------------------------------ */
8110 /* decFree -- accountable free routine                                */
8111 /*   alloc is the storage to free                                     */
8112 /*                                                                    */
8113 /* Semantics is the same as the stdlib malloc routine, except that    */
8114 /* the global storage accounting is updated and the fences are        */
8115 /* checked to ensure that no routine has written 'out of bounds'.     */
8116 /* ------------------------------------------------------------------ */
8117 /* This routine first checks that the fences have not been corrupted. */
8118 /* It then frees the storage using the 'truw' storage address (that   */
8119 /* is, offset by 8).                                                  */
8120 /* ------------------------------------------------------------------ */
8121 static void decFree(void *alloc) {
8122   uInt  n;                         /* original length */
8123   uByte *b, *b0;                   /* work */
8124   uInt  uiwork;                    /* for macros */
8125
8126   if (alloc==NULL) return;         /* allowed; it's a nop */
8127   b0=(uByte *)alloc;               /* as bytes */
8128   b0-=8;                           /* -> true start of storage */
8129   n=UBTOUI(b0);                    /* lift length */
8130   for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8131     printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8132            b-b0-8, (LI)b0);
8133   for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8134     printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8135            b-b0-8, (LI)b0, (LI)n);
8136   free(b0);                        /* drop the storage */
8137   decAllocBytes-=n;                /* account for storage */
8138   /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8139   } /* decFree */
8140 #define malloc(a) decMalloc(a)
8141 #define free(a) decFree(a)
8142 #endif