Merge branch 'vendor/GCC44' into gcc441
[dragonfly.git] / contrib / gcc-4.4 / libdecnumber / decNumber.c
1 /* Decimal number arithmetic module for the decNumber C Library.
2    Copyright (C) 2005, 2007, 2009 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 3, or (at your option) any later
10    version.
11
12    GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13    WARRANTY; without even the implied warranty of MERCHANTABILITY or
14    FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15    for more details.
16
17 Under Section 7 of GPL version 3, you are granted additional
18 permissions described in the GCC Runtime Library Exception, version
19 3.1, as published by the Free Software Foundation.
20
21 You should have received a copy of the GNU General Public License and
22 a copy of the GCC Runtime Library Exception along with this program;
23 see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see
24 <http://www.gnu.org/licenses/>.  */
25
26 /* ------------------------------------------------------------------ */
27 /* Decimal Number arithmetic module                                   */
28 /* ------------------------------------------------------------------ */
29 /* This module comprises the routines for General Decimal Arithmetic  */
30 /* as defined in the specification which may be found on the          */
31 /* http://www2.hursley.ibm.com/decimal web pages.  It implements both */
32 /* the full ('extended') arithmetic and the simpler ('subset')        */
33 /* arithmetic.                                                        */
34 /*                                                                    */
35 /* Usage notes:                                                       */
36 /*                                                                    */
37 /* 1. This code is ANSI C89 except:                                   */
38 /*                                                                    */
39 /*       If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
40 /*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
41 /*       and DECDPUN<=4 (see documentation).                          */
42 /*                                                                    */
43 /* 2. The decNumber format which this library uses is optimized for   */
44 /*    efficient processing of relatively short numbers; in particular */
45 /*    it allows the use of fixed sized structures and minimizes copy  */
46 /*    and move operations.  It does, however, support arbitrary       */
47 /*    precision (up to 999,999,999 digits) and arbitrary exponent     */
48 /*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
49 /*    range -999,999,999 through 0).  Mathematical functions (for     */
50 /*    example decNumberExp) as identified below are restricted more   */
51 /*    tightly: digits, emax, and -emin in the context must be <=      */
52 /*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
53 /*    these bounds.                                                   */
54 /*                                                                    */
55 /* 3. Logical functions are further restricted; their operands must   */
56 /*    be finite, positive, have an exponent of zero, and all digits   */
57 /*    must be either 0 or 1.  The result will only contain digits     */
58 /*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
59 /*                                                                    */
60 /* 4. Operands to operator functions are never modified unless they   */
61 /*    are also specified to be the result number (which is always     */
62 /*    permitted).  Other than that case, operands must not overlap.   */
63 /*                                                                    */
64 /* 5. Error handling: the type of the error is ORed into the status   */
65 /*    flags in the current context (decContext structure).  The       */
66 /*    SIGFPE signal is then raised if the corresponding trap-enabler  */
67 /*    flag in the decContext is set (is 1).                           */
68 /*                                                                    */
69 /*    It is the responsibility of the caller to clear the status      */
70 /*    flags as required.                                              */
71 /*                                                                    */
72 /*    The result of any routine which returns a number will always    */
73 /*    be a valid number (which may be a special value, such as an     */
74 /*    Infinity or NaN).                                               */
75 /*                                                                    */
76 /* 6. The decNumber format is not an exchangeable concrete            */
77 /*    representation as it comprises fields which may be machine-     */
78 /*    dependent (packed or unpacked, or special length, for example). */
79 /*    Canonical conversions to and from strings are provided; other   */
80 /*    conversions are available in separate modules.                  */
81 /*                                                                    */
82 /* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
83 /*    to 1 for extended operand checking (including NULL operands).   */
84 /*    Results are undefined if a badly-formed structure (or a NULL    */
85 /*    pointer to a structure) is provided, though with DECCHECK       */
86 /*    enabled the operator routines are protected against exceptions. */
87 /*    (Except if the result pointer is NULL, which is unrecoverable.) */
88 /*                                                                    */
89 /*    However, the routines will never cause exceptions if they are   */
90 /*    given well-formed operands, even if the value of the operands   */
91 /*    is inappropriate for the operation and DECCHECK is not set.     */
92 /*    (Except for SIGFPE, as and where documented.)                   */
93 /*                                                                    */
94 /* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
95 /* ------------------------------------------------------------------ */
96 /* Implementation notes for maintenance of this module:               */
97 /*                                                                    */
98 /* 1. Storage leak protection:  Routines which use malloc are not     */
99 /*    permitted to use return for fastpath or error exits (i.e.,      */
100 /*    they follow strict structured programming conventions).         */
101 /*    Instead they have a do{}while(0); construct surrounding the     */
102 /*    code which is protected -- break may be used to exit this.      */
103 /*    Other routines can safely use the return statement inline.      */
104 /*                                                                    */
105 /*    Storage leak accounting can be enabled using DECALLOC.          */
106 /*                                                                    */
107 /* 2. All loops use the for(;;) construct.  Any do construct does     */
108 /*    not loop; it is for allocation protection as just described.    */
109 /*                                                                    */
110 /* 3. Setting status in the context must always be the very last      */
111 /*    action in a routine, as non-0 status may raise a trap and hence */
112 /*    the call to set status may not return (if the handler uses long */
113 /*    jump).  Therefore all cleanup must be done first.  In general,  */
114 /*    to achieve this status is accumulated and is only applied just  */
115 /*    before return by calling decContextSetStatus (via decStatus).   */
116 /*                                                                    */
117 /*    Routines which allocate storage cannot, in general, use the     */
118 /*    'top level' routines which could cause a non-returning          */
119 /*    transfer of control.  The decXxxxOp routines are safe (do not   */
120 /*    call decStatus even if traps are set in the context) and should */
121 /*    be used instead (they are also a little faster).                */
122 /*                                                                    */
123 /* 4. Exponent checking is minimized by allowing the exponent to      */
124 /*    grow outside its limits during calculations, provided that      */
125 /*    the decFinalize function is called later.  Multiplication and   */
126 /*    division, and intermediate calculations in exponentiation,      */
127 /*    require more careful checks because of the risk of 31-bit       */
128 /*    overflow (the most negative valid exponent is -1999999997, for  */
129 /*    a 999999999-digit number with adjusted exponent of -999999999). */
130 /*                                                                    */
131 /* 5. Rounding is deferred until finalization of results, with any    */
132 /*    'off to the right' data being represented as a single digit     */
133 /*    residue (in the range -1 through 9).  This avoids any double-   */
134 /*    rounding when more than one shortening takes place (for         */
135 /*    example, when a result is subnormal).                           */
136 /*                                                                    */
137 /* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
138 /*    during many operations, so whole Units are handled and exact    */
139 /*    accounting of digits is not needed.  The correct digits value   */
140 /*    is found by decGetDigits, which accounts for leading zeros.     */
141 /*    This must be called before any rounding if the number of digits */
142 /*    is not known exactly.                                           */
143 /*                                                                    */
144 /* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
145 /*    numbers up to four digits, using appropriate constants.  This   */
146 /*    is not useful for longer numbers because overflow of 32 bits    */
147 /*    would lead to 4 multiplies, which is almost as expensive as     */
148 /*    a divide (unless a floating-point or 64-bit multiply is         */
149 /*    assumed to be available).                                       */
150 /*                                                                    */
151 /* 8. Unusual abbreviations that may be used in the commentary:       */
152 /*      lhs -- left hand side (operand, of an operation)              */
153 /*      lsd -- least significant digit (of coefficient)               */
154 /*      lsu -- least significant Unit (of coefficient)                */
155 /*      msd -- most significant digit (of coefficient)                */
156 /*      msi -- most significant item (in an array)                    */
157 /*      msu -- most significant Unit (of coefficient)                 */
158 /*      rhs -- right hand side (operand, of an operation)             */
159 /*      +ve -- positive                                               */
160 /*      -ve -- negative                                               */
161 /*      **  -- raise to the power                                     */
162 /* ------------------------------------------------------------------ */
163
164 #include <stdlib.h>                /* for malloc, free, etc. */
165 #include <stdio.h>                 /* for printf [if needed] */
166 #include <string.h>                /* for strcpy */
167 #include <ctype.h>                 /* for lower */
168 #include "dconfig.h"               /* for GCC definitions */
169 #include "decNumber.h"             /* base number library */
170 #include "decNumberLocal.h"        /* decNumber local types, etc. */
171
172 /* Constants */
173 /* Public lookup table used by the D2U macro */
174 const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
175
176 #define DECVERB     1              /* set to 1 for verbose DECCHECK */
177 #define powers      DECPOWERS      /* old internal name */
178
179 /* Local constants */
180 #define DIVIDE      0x80           /* Divide operators */
181 #define REMAINDER   0x40           /* .. */
182 #define DIVIDEINT   0x20           /* .. */
183 #define REMNEAR     0x10           /* .. */
184 #define COMPARE     0x01           /* Compare operators */
185 #define COMPMAX     0x02           /* .. */
186 #define COMPMIN     0x03           /* .. */
187 #define COMPTOTAL   0x04           /* .. */
188 #define COMPNAN     0x05           /* .. [NaN processing] */
189 #define COMPSIG     0x06           /* .. [signaling COMPARE] */
190 #define COMPMAXMAG  0x07           /* .. */
191 #define COMPMINMAG  0x08           /* .. */
192
193 #define DEC_sNaN     0x40000000    /* local status: sNaN signal */
194 #define BADINT  (Int)0x80000000    /* most-negative Int; error indicator */
195 /* Next two indicate an integer >= 10**6, and its parity (bottom bit) */
196 #define BIGEVEN (Int)0x80000002
197 #define BIGODD  (Int)0x80000003
198
199 static Unit uarrone[1]={1};   /* Unit array of 1, used for incrementing */
200
201 /* Granularity-dependent code */
202 #if DECDPUN<=4
203   #define eInt  Int           /* extended integer */
204   #define ueInt uInt          /* unsigned extended integer */
205   /* Constant multipliers for divide-by-power-of five using reciprocal */
206   /* multiply, after removing powers of 2 by shifting, and final shift */
207   /* of 17 [we only need up to **4] */
208   static const uInt multies[]={131073, 26215, 5243, 1049, 210};
209   /* QUOT10 -- macro to return the quotient of unit u divided by 10**n */
210   #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
211 #else
212   /* For DECDPUN>4 non-ANSI-89 64-bit types are needed. */
213   #if !DECUSE64
214     #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
215   #endif
216   #define eInt  Long          /* extended integer */
217   #define ueInt uLong         /* unsigned extended integer */
218 #endif
219
220 /* Local routines */
221 static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
222                               decContext *, uByte, uInt *);
223 static Flag        decBiStr(const char *, const char *, const char *);
224 static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
225 static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
226 static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
227 static decNumber * decCompareOp(decNumber *, const decNumber *,
228                               const decNumber *, decContext *,
229                               Flag, uInt *);
230 static void        decCopyFit(decNumber *, const decNumber *, decContext *,
231                               Int *, uInt *);
232 static decNumber * decDecap(decNumber *, Int);
233 static decNumber * decDivideOp(decNumber *, const decNumber *,
234                               const decNumber *, decContext *, Flag, uInt *);
235 static decNumber * decExpOp(decNumber *, const decNumber *,
236                               decContext *, uInt *);
237 static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
238 static Int         decGetDigits(Unit *, Int);
239 static Int         decGetInt(const decNumber *);
240 static decNumber * decLnOp(decNumber *, const decNumber *,
241                               decContext *, uInt *);
242 static decNumber * decMultiplyOp(decNumber *, const decNumber *,
243                               const decNumber *, decContext *,
244                               uInt *);
245 static decNumber * decNaNs(decNumber *, const decNumber *,
246                               const decNumber *, decContext *, uInt *);
247 static decNumber * decQuantizeOp(decNumber *, const decNumber *,
248                               const decNumber *, decContext *, Flag,
249                               uInt *);
250 static void        decReverse(Unit *, Unit *);
251 static void        decSetCoeff(decNumber *, decContext *, const Unit *,
252                               Int, Int *, uInt *);
253 static void        decSetMaxValue(decNumber *, decContext *);
254 static void        decSetOverflow(decNumber *, decContext *, uInt *);
255 static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
256 static Int         decShiftToLeast(Unit *, Int, Int);
257 static Int         decShiftToMost(Unit *, Int, Int);
258 static void        decStatus(decNumber *, uInt, decContext *);
259 static void        decToString(const decNumber *, char[], Flag);
260 static decNumber * decTrim(decNumber *, decContext *, Flag, Int *);
261 static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
262                               Unit *, Int);
263 static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
264
265 #if !DECSUBSET
266 /* decFinish == decFinalize when no subset arithmetic needed */
267 #define decFinish(a,b,c,d) decFinalize(a,b,c,d)
268 #else
269 static void        decFinish(decNumber *, decContext *, Int *, uInt *);
270 static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
271 #endif
272
273 /* Local macros */
274 /* masked special-values bits */
275 #define SPECIALARG  (rhs->bits & DECSPECIAL)
276 #define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
277
278 /* Diagnostic macros, etc. */
279 #if DECALLOC
280 /* Handle malloc/free accounting.  If enabled, our accountable routines */
281 /* are used; otherwise the code just goes straight to the system malloc */
282 /* and free routines. */
283 #define malloc(a) decMalloc(a)
284 #define free(a) decFree(a)
285 #define DECFENCE 0x5a              /* corruption detector */
286 /* 'Our' malloc and free: */
287 static void *decMalloc(size_t);
288 static void  decFree(void *);
289 uInt decAllocBytes=0;              /* count of bytes allocated */
290 /* Note that DECALLOC code only checks for storage buffer overflow. */
291 /* To check for memory leaks, the decAllocBytes variable must be */
292 /* checked to be 0 at appropriate times (e.g., after the test */
293 /* harness completes a set of tests).  This checking may be unreliable */
294 /* if the testing is done in a multi-thread environment. */
295 #endif
296
297 #if DECCHECK
298 /* Optional checking routines.  Enabling these means that decNumber */
299 /* and decContext operands to operator routines are checked for */
300 /* correctness.  This roughly doubles the execution time of the */
301 /* fastest routines (and adds 600+ bytes), so should not normally be */
302 /* used in 'production'. */
303 /* decCheckInexact is used to check that inexact results have a full */
304 /* complement of digits (where appropriate -- this is not the case */
305 /* for Quantize, for example) */
306 #define DECUNRESU ((decNumber *)(void *)0xffffffff)
307 #define DECUNUSED ((const decNumber *)(void *)0xffffffff)
308 #define DECUNCONT ((decContext *)(void *)(0xffffffff))
309 static Flag decCheckOperands(decNumber *, const decNumber *,
310                              const decNumber *, decContext *);
311 static Flag decCheckNumber(const decNumber *);
312 static void decCheckInexact(const decNumber *, decContext *);
313 #endif
314
315 #if DECTRACE || DECCHECK
316 /* Optional trace/debugging routines (may or may not be used) */
317 void decNumberShow(const decNumber *);  /* displays the components of a number */
318 static void decDumpAr(char, const Unit *, Int);
319 #endif
320
321 /* ================================================================== */
322 /* Conversions                                                        */
323 /* ================================================================== */
324
325 /* ------------------------------------------------------------------ */
326 /* from-int32 -- conversion from Int or uInt                          */
327 /*                                                                    */
328 /*  dn is the decNumber to receive the integer                        */
329 /*  in or uin is the integer to be converted                          */
330 /*  returns dn                                                        */
331 /*                                                                    */
332 /* No error is possible.                                              */
333 /* ------------------------------------------------------------------ */
334 decNumber * decNumberFromInt32(decNumber *dn, Int in) {
335   uInt unsig;
336   if (in>=0) unsig=in;
337    else {                               /* negative (possibly BADINT) */
338     if (in==BADINT) unsig=(uInt)1073741824*2; /* special case */
339      else unsig=-in;                    /* invert */
340     }
341   /* in is now positive */
342   decNumberFromUInt32(dn, unsig);
343   if (in<0) dn->bits=DECNEG;            /* sign needed */
344   return dn;
345   } /* decNumberFromInt32 */
346
347 decNumber * decNumberFromUInt32(decNumber *dn, uInt uin) {
348   Unit *up;                             /* work pointer */
349   decNumberZero(dn);                    /* clean */
350   if (uin==0) return dn;                /* [or decGetDigits bad call] */
351   for (up=dn->lsu; uin>0; up++) {
352     *up=(Unit)(uin%(DECDPUNMAX+1));
353     uin=uin/(DECDPUNMAX+1);
354     }
355   dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
356   return dn;
357   } /* decNumberFromUInt32 */
358
359 /* ------------------------------------------------------------------ */
360 /* to-int32 -- conversion to Int or uInt                              */
361 /*                                                                    */
362 /*  dn is the decNumber to convert                                    */
363 /*  set is the context for reporting errors                           */
364 /*  returns the converted decNumber, or 0 if Invalid is set           */
365 /*                                                                    */
366 /* Invalid is set if the decNumber does not have exponent==0 or if    */
367 /* it is a NaN, Infinite, or out-of-range.                            */
368 /* ------------------------------------------------------------------ */
369 Int decNumberToInt32(const decNumber *dn, decContext *set) {
370   #if DECCHECK
371   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
372   #endif
373
374   /* special or too many digits, or bad exponent */
375   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad */
376    else { /* is a finite integer with 10 or fewer digits */
377     Int d;                         /* work */
378     const Unit *up;                /* .. */
379     uInt hi=0, lo;                 /* .. */
380     up=dn->lsu;                    /* -> lsu */
381     lo=*up;                        /* get 1 to 9 digits */
382     #if DECDPUN>1                  /* split to higher */
383       hi=lo/10;
384       lo=lo%10;
385     #endif
386     up++;
387     /* collect remaining Units, if any, into hi */
388     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
389     /* now low has the lsd, hi the remainder */
390     if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range? */
391       /* most-negative is a reprieve */
392       if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
393       /* bad -- drop through */
394       }
395      else { /* in-range always */
396       Int i=X10(hi)+lo;
397       if (dn->bits&DECNEG) return -i;
398       return i;
399       }
400     } /* integer */
401   decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
402   return 0;
403   } /* decNumberToInt32 */
404
405 uInt decNumberToUInt32(const decNumber *dn, decContext *set) {
406   #if DECCHECK
407   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
408   #endif
409   /* special or too many digits, or bad exponent, or negative (<0) */
410   if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
411     || (dn->bits&DECNEG && !ISZERO(dn)));                   /* bad */
412    else { /* is a finite integer with 10 or fewer digits */
413     Int d;                         /* work */
414     const Unit *up;                /* .. */
415     uInt hi=0, lo;                 /* .. */
416     up=dn->lsu;                    /* -> lsu */
417     lo=*up;                        /* get 1 to 9 digits */
418     #if DECDPUN>1                  /* split to higher */
419       hi=lo/10;
420       lo=lo%10;
421     #endif
422     up++;
423     /* collect remaining Units, if any, into hi */
424     for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
425
426     /* now low has the lsd, hi the remainder */
427     if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible */
428      else return X10(hi)+lo;
429     } /* integer */
430   decContextSetStatus(set, DEC_Invalid_operation); /* [may not return] */
431   return 0;
432   } /* decNumberToUInt32 */
433
434 /* ------------------------------------------------------------------ */
435 /* to-scientific-string -- conversion to numeric string               */
436 /* to-engineering-string -- conversion to numeric string              */
437 /*                                                                    */
438 /*   decNumberToString(dn, string);                                   */
439 /*   decNumberToEngString(dn, string);                                */
440 /*                                                                    */
441 /*  dn is the decNumber to convert                                    */
442 /*  string is the string where the result will be laid out            */
443 /*                                                                    */
444 /*  string must be at least dn->digits+14 characters long             */
445 /*                                                                    */
446 /*  No error is possible, and no status can be set.                   */
447 /* ------------------------------------------------------------------ */
448 char * decNumberToString(const decNumber *dn, char *string){
449   decToString(dn, string, 0);
450   return string;
451   } /* DecNumberToString */
452
453 char * decNumberToEngString(const decNumber *dn, char *string){
454   decToString(dn, string, 1);
455   return string;
456   } /* DecNumberToEngString */
457
458 /* ------------------------------------------------------------------ */
459 /* to-number -- conversion from numeric string                        */
460 /*                                                                    */
461 /* decNumberFromString -- convert string to decNumber                 */
462 /*   dn        -- the number structure to fill                        */
463 /*   chars[]   -- the string to convert ('\0' terminated)             */
464 /*   set       -- the context used for processing any error,          */
465 /*                determining the maximum precision available         */
466 /*                (set.digits), determining the maximum and minimum   */
467 /*                exponent (set.emax and set.emin), determining if    */
468 /*                extended values are allowed, and checking the       */
469 /*                rounding mode if overflow occurs or rounding is     */
470 /*                needed.                                             */
471 /*                                                                    */
472 /* The length of the coefficient and the size of the exponent are     */
473 /* checked by this routine, so the correct error (Underflow or        */
474 /* Overflow) can be reported or rounding applied, as necessary.       */
475 /*                                                                    */
476 /* If bad syntax is detected, the result will be a quiet NaN.         */
477 /* ------------------------------------------------------------------ */
478 decNumber * decNumberFromString(decNumber *dn, const char chars[],
479                                 decContext *set) {
480   Int   exponent=0;                /* working exponent [assume 0] */
481   uByte bits=0;                    /* working flags [assume +ve] */
482   Unit  *res;                      /* where result will be built */
483   Unit  resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary */
484                                    /* [+9 allows for ln() constants] */
485   Unit  *allocres=NULL;            /* -> allocated result, iff allocated */
486   Int   d=0;                       /* count of digits found in decimal part */
487   const char *dotchar=NULL;        /* where dot was found */
488   const char *cfirst=chars;        /* -> first character of decimal part */
489   const char *last=NULL;           /* -> last digit of decimal part */
490   const char *c;                   /* work */
491   Unit  *up;                       /* .. */
492   #if DECDPUN>1
493   Int   cut, out;                  /* .. */
494   #endif
495   Int   residue;                   /* rounding residue */
496   uInt  status=0;                  /* error code */
497
498   #if DECCHECK
499   if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
500     return decNumberZero(dn);
501   #endif
502
503   do {                             /* status & malloc protection */
504     for (c=chars;; c++) {          /* -> input character */
505       if (*c>='0' && *c<='9') {    /* test for Arabic digit */
506         last=c;
507         d++;                       /* count of real digits */
508         continue;                  /* still in decimal part */
509         }
510       if (*c=='.' && dotchar==NULL) { /* first '.' */
511         dotchar=c;                 /* record offset into decimal part */
512         if (c==cfirst) cfirst++;   /* first digit must follow */
513         continue;}
514       if (c==chars) {              /* first in string... */
515         if (*c=='-') {             /* valid - sign */
516           cfirst++;
517           bits=DECNEG;
518           continue;}
519         if (*c=='+') {             /* valid + sign */
520           cfirst++;
521           continue;}
522         }
523       /* *c is not a digit, or a valid +, -, or '.' */
524       break;
525       } /* c */
526
527     if (last==NULL) {              /* no digits yet */
528       status=DEC_Conversion_syntax;/* assume the worst */
529       if (*c=='\0') break;         /* and no more to come... */
530       #if DECSUBSET
531       /* if subset then infinities and NaNs are not allowed */
532       if (!set->extended) break;   /* hopeless */
533       #endif
534       /* Infinities and NaNs are possible, here */
535       if (dotchar!=NULL) break;    /* .. unless had a dot */
536       decNumberZero(dn);           /* be optimistic */
537       if (decBiStr(c, "infinity", "INFINITY")
538        || decBiStr(c, "inf", "INF")) {
539         dn->bits=bits | DECINF;
540         status=0;                  /* is OK */
541         break; /* all done */
542         }
543       /* a NaN expected */
544       /* 2003.09.10 NaNs are now permitted to have a sign */
545       dn->bits=bits | DECNAN;      /* assume simple NaN */
546       if (*c=='s' || *c=='S') {    /* looks like an sNaN */
547         c++;
548         dn->bits=bits | DECSNAN;
549         }
550       if (*c!='n' && *c!='N') break;    /* check caseless "NaN" */
551       c++;
552       if (*c!='a' && *c!='A') break;    /* .. */
553       c++;
554       if (*c!='n' && *c!='N') break;    /* .. */
555       c++;
556       /* now either nothing, or nnnn payload, expected */
557       /* -> start of integer and skip leading 0s [including plain 0] */
558       for (cfirst=c; *cfirst=='0';) cfirst++;
559       if (*cfirst=='\0') {         /* "NaN" or "sNaN", maybe with all 0s */
560         status=0;                  /* it's good */
561         break;                     /* .. */
562         }
563       /* something other than 0s; setup last and d as usual [no dots] */
564       for (c=cfirst;; c++, d++) {
565         if (*c<'0' || *c>'9') break; /* test for Arabic digit */
566         last=c;
567         }
568       if (*c!='\0') break;         /* not all digits */
569       if (d>set->digits-1) {
570         /* [NB: payload in a decNumber can be full length unless */
571         /* clamped, in which case can only be digits-1] */
572         if (set->clamp) break;
573         if (d>set->digits) break;
574         } /* too many digits? */
575       /* good; drop through to convert the integer to coefficient */
576       status=0;                    /* syntax is OK */
577       bits=dn->bits;               /* for copy-back */
578       } /* last==NULL */
579
580      else if (*c!='\0') {          /* more to process... */
581       /* had some digits; exponent is only valid sequence now */
582       Flag nege;                   /* 1=negative exponent */
583       const char *firstexp;        /* -> first significant exponent digit */
584       status=DEC_Conversion_syntax;/* assume the worst */
585       if (*c!='e' && *c!='E') break;
586       /* Found 'e' or 'E' -- now process explicit exponent */
587       /* 1998.07.11: sign no longer required */
588       nege=0;
589       c++;                         /* to (possible) sign */
590       if (*c=='-') {nege=1; c++;}
591        else if (*c=='+') c++;
592       if (*c=='\0') break;
593
594       for (; *c=='0' && *(c+1)!='\0';) c++;  /* strip insignificant zeros */
595       firstexp=c;                            /* save exponent digit place */
596       for (; ;c++) {
597         if (*c<'0' || *c>'9') break;         /* not a digit */
598         exponent=X10(exponent)+(Int)*c-(Int)'0';
599         } /* c */
600       /* if not now on a '\0', *c must not be a digit */
601       if (*c!='\0') break;
602
603       /* (this next test must be after the syntax checks) */
604       /* if it was too long the exponent may have wrapped, so check */
605       /* carefully and set it to a certain overflow if wrap possible */
606       if (c>=firstexp+9+1) {
607         if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
608         /* [up to 1999999999 is OK, for example 1E-1000000998] */
609         }
610       if (nege) exponent=-exponent;     /* was negative */
611       status=0;                         /* is OK */
612       } /* stuff after digits */
613
614     /* Here when whole string has been inspected; syntax is good */
615     /* cfirst->first digit (never dot), last->last digit (ditto) */
616
617     /* strip leading zeros/dot [leave final 0 if all 0's] */
618     if (*cfirst=='0') {                 /* [cfirst has stepped over .] */
619       for (c=cfirst; c<last; c++, cfirst++) {
620         if (*c=='.') continue;          /* ignore dots */
621         if (*c!='0') break;             /* non-zero found */
622         d--;                            /* 0 stripped */
623         } /* c */
624       #if DECSUBSET
625       /* make a rapid exit for easy zeros if !extended */
626       if (*cfirst=='0' && !set->extended) {
627         decNumberZero(dn);              /* clean result */
628         break;                          /* [could be return] */
629         }
630       #endif
631       } /* at least one leading 0 */
632
633     /* Handle decimal point... */
634     if (dotchar!=NULL && dotchar<last)  /* non-trailing '.' found? */
635       exponent-=(last-dotchar);         /* adjust exponent */
636     /* [we can now ignore the .] */
637
638     /* OK, the digits string is good.  Assemble in the decNumber, or in */
639     /* a temporary units array if rounding is needed */
640     if (d<=set->digits) res=dn->lsu;    /* fits into supplied decNumber */
641      else {                             /* rounding needed */
642       Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed */
643       res=resbuff;                      /* assume use local buffer */
644       if (needbytes>(Int)sizeof(resbuff)) { /* too big for local */
645         allocres=(Unit *)malloc(needbytes);
646         if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
647         res=allocres;
648         }
649       }
650     /* res now -> number lsu, buffer, or allocated storage for Unit array */
651
652     /* Place the coefficient into the selected Unit array */
653     /* [this is often 70% of the cost of this function when DECDPUN>1] */
654     #if DECDPUN>1
655     out=0;                         /* accumulator */
656     up=res+D2U(d)-1;               /* -> msu */
657     cut=d-(up-res)*DECDPUN;        /* digits in top unit */
658     for (c=cfirst;; c++) {         /* along the digits */
659       if (*c=='.') continue;       /* ignore '.' [don't decrement cut] */
660       out=X10(out)+(Int)*c-(Int)'0';
661       if (c==last) break;          /* done [never get to trailing '.'] */
662       cut--;
663       if (cut>0) continue;         /* more for this unit */
664       *up=(Unit)out;               /* write unit */
665       up--;                        /* prepare for unit below.. */
666       cut=DECDPUN;                 /* .. */
667       out=0;                       /* .. */
668       } /* c */
669     *up=(Unit)out;                 /* write lsu */
670
671     #else
672     /* DECDPUN==1 */
673     up=res;                        /* -> lsu */
674     for (c=last; c>=cfirst; c--) { /* over each character, from least */
675       if (*c=='.') continue;       /* ignore . [don't step up] */
676       *up=(Unit)((Int)*c-(Int)'0');
677       up++;
678       } /* c */
679     #endif
680
681     dn->bits=bits;
682     dn->exponent=exponent;
683     dn->digits=d;
684
685     /* if not in number (too long) shorten into the number */
686     if (d>set->digits) {
687       residue=0;
688       decSetCoeff(dn, set, res, d, &residue, &status);
689       /* always check for overflow or subnormal and round as needed */
690       decFinalize(dn, set, &residue, &status);
691       }
692      else { /* no rounding, but may still have overflow or subnormal */
693       /* [these tests are just for performance; finalize repeats them] */
694       if ((dn->exponent-1<set->emin-dn->digits)
695        || (dn->exponent-1>set->emax-set->digits)) {
696         residue=0;
697         decFinalize(dn, set, &residue, &status);
698         }
699       }
700     /* decNumberShow(dn); */
701     } while(0);                         /* [for break] */
702
703   if (allocres!=NULL) free(allocres);   /* drop any storage used */
704   if (status!=0) decStatus(dn, status, set);
705   return dn;
706   } /* decNumberFromString */
707
708 /* ================================================================== */
709 /* Operators                                                          */
710 /* ================================================================== */
711
712 /* ------------------------------------------------------------------ */
713 /* decNumberAbs -- absolute value operator                            */
714 /*                                                                    */
715 /*   This computes C = abs(A)                                         */
716 /*                                                                    */
717 /*   res is C, the result.  C may be A                                */
718 /*   rhs is A                                                         */
719 /*   set is the context                                               */
720 /*                                                                    */
721 /* See also decNumberCopyAbs for a quiet bitwise version of this.     */
722 /* C must have space for set->digits digits.                          */
723 /* ------------------------------------------------------------------ */
724 /* This has the same effect as decNumberPlus unless A is negative,    */
725 /* in which case it has the same effect as decNumberMinus.            */
726 /* ------------------------------------------------------------------ */
727 decNumber * decNumberAbs(decNumber *res, const decNumber *rhs,
728                          decContext *set) {
729   decNumber dzero;                      /* for 0 */
730   uInt status=0;                        /* accumulator */
731
732   #if DECCHECK
733   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
734   #endif
735
736   decNumberZero(&dzero);                /* set 0 */
737   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
738   decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
739   if (status!=0) decStatus(res, status, set);
740   #if DECCHECK
741   decCheckInexact(res, set);
742   #endif
743   return res;
744   } /* decNumberAbs */
745
746 /* ------------------------------------------------------------------ */
747 /* decNumberAdd -- add two Numbers                                    */
748 /*                                                                    */
749 /*   This computes C = A + B                                          */
750 /*                                                                    */
751 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
752 /*   lhs is A                                                         */
753 /*   rhs is B                                                         */
754 /*   set is the context                                               */
755 /*                                                                    */
756 /* C must have space for set->digits digits.                          */
757 /* ------------------------------------------------------------------ */
758 /* This just calls the routine shared with Subtract                   */
759 decNumber * decNumberAdd(decNumber *res, const decNumber *lhs,
760                          const decNumber *rhs, decContext *set) {
761   uInt status=0;                        /* accumulator */
762   decAddOp(res, lhs, rhs, set, 0, &status);
763   if (status!=0) decStatus(res, status, set);
764   #if DECCHECK
765   decCheckInexact(res, set);
766   #endif
767   return res;
768   } /* decNumberAdd */
769
770 /* ------------------------------------------------------------------ */
771 /* decNumberAnd -- AND two Numbers, digitwise                         */
772 /*                                                                    */
773 /*   This computes C = A & B                                          */
774 /*                                                                    */
775 /*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
776 /*   lhs is A                                                         */
777 /*   rhs is B                                                         */
778 /*   set is the context (used for result length and error report)     */
779 /*                                                                    */
780 /* C must have space for set->digits digits.                          */
781 /*                                                                    */
782 /* Logical function restrictions apply (see above); a NaN is          */
783 /* returned with Invalid_operation if a restriction is violated.      */
784 /* ------------------------------------------------------------------ */
785 decNumber * decNumberAnd(decNumber *res, const decNumber *lhs,
786                          const decNumber *rhs, decContext *set) {
787   const Unit *ua, *ub;                  /* -> operands */
788   const Unit *msua, *msub;              /* -> operand msus */
789   Unit *uc,  *msuc;                     /* -> result and its msu */
790   Int   msudigs;                        /* digits in res msu */
791   #if DECCHECK
792   if (decCheckOperands(res, lhs, rhs, set)) return res;
793   #endif
794
795   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
796    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
797     decStatus(res, DEC_Invalid_operation, set);
798     return res;
799     }
800
801   /* operands are valid */
802   ua=lhs->lsu;                          /* bottom-up */
803   ub=rhs->lsu;                          /* .. */
804   uc=res->lsu;                          /* .. */
805   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
806   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
807   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
808   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
809   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
810     Unit a, b;                          /* extract units */
811     if (ua>msua) a=0;
812      else a=*ua;
813     if (ub>msub) b=0;
814      else b=*ub;
815     *uc=0;                              /* can now write back */
816     if (a|b) {                          /* maybe 1 bits to examine */
817       Int i, j;
818       *uc=0;                            /* can now write back */
819       /* This loop could be unrolled and/or use BIN2BCD tables */
820       for (i=0; i<DECDPUN; i++) {
821         if (a&b&1) *uc=*uc+(Unit)powers[i];  /* effect AND */
822         j=a%10;
823         a=a/10;
824         j|=b%10;
825         b=b/10;
826         if (j>1) {
827           decStatus(res, DEC_Invalid_operation, set);
828           return res;
829           }
830         if (uc==msuc && i==msudigs-1) break; /* just did final digit */
831         } /* each digit */
832       } /* both OK */
833     } /* each unit */
834   /* [here uc-1 is the msu of the result] */
835   res->digits=decGetDigits(res->lsu, uc-res->lsu);
836   res->exponent=0;                      /* integer */
837   res->bits=0;                          /* sign=0 */
838   return res;  /* [no status to set] */
839   } /* decNumberAnd */
840
841 /* ------------------------------------------------------------------ */
842 /* decNumberCompare -- compare two Numbers                            */
843 /*                                                                    */
844 /*   This computes C = A ? B                                          */
845 /*                                                                    */
846 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
847 /*   lhs is A                                                         */
848 /*   rhs is B                                                         */
849 /*   set is the context                                               */
850 /*                                                                    */
851 /* C must have space for one digit (or NaN).                          */
852 /* ------------------------------------------------------------------ */
853 decNumber * decNumberCompare(decNumber *res, const decNumber *lhs,
854                              const decNumber *rhs, decContext *set) {
855   uInt status=0;                        /* accumulator */
856   decCompareOp(res, lhs, rhs, set, COMPARE, &status);
857   if (status!=0) decStatus(res, status, set);
858   return res;
859   } /* decNumberCompare */
860
861 /* ------------------------------------------------------------------ */
862 /* decNumberCompareSignal -- compare, signalling on all NaNs          */
863 /*                                                                    */
864 /*   This computes C = A ? B                                          */
865 /*                                                                    */
866 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
867 /*   lhs is A                                                         */
868 /*   rhs is B                                                         */
869 /*   set is the context                                               */
870 /*                                                                    */
871 /* C must have space for one digit (or NaN).                          */
872 /* ------------------------------------------------------------------ */
873 decNumber * decNumberCompareSignal(decNumber *res, const decNumber *lhs,
874                                    const decNumber *rhs, decContext *set) {
875   uInt status=0;                        /* accumulator */
876   decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
877   if (status!=0) decStatus(res, status, set);
878   return res;
879   } /* decNumberCompareSignal */
880
881 /* ------------------------------------------------------------------ */
882 /* decNumberCompareTotal -- compare two Numbers, using total ordering */
883 /*                                                                    */
884 /*   This computes C = A ? B, under total ordering                    */
885 /*                                                                    */
886 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
887 /*   lhs is A                                                         */
888 /*   rhs is B                                                         */
889 /*   set is the context                                               */
890 /*                                                                    */
891 /* C must have space for one digit; the result will always be one of  */
892 /* -1, 0, or 1.                                                       */
893 /* ------------------------------------------------------------------ */
894 decNumber * decNumberCompareTotal(decNumber *res, const decNumber *lhs,
895                                   const decNumber *rhs, decContext *set) {
896   uInt status=0;                        /* accumulator */
897   decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
898   if (status!=0) decStatus(res, status, set);
899   return res;
900   } /* decNumberCompareTotal */
901
902 /* ------------------------------------------------------------------ */
903 /* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
904 /*                                                                    */
905 /*   This computes C = |A| ? |B|, under total ordering                */
906 /*                                                                    */
907 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
908 /*   lhs is A                                                         */
909 /*   rhs is B                                                         */
910 /*   set is the context                                               */
911 /*                                                                    */
912 /* C must have space for one digit; the result will always be one of  */
913 /* -1, 0, or 1.                                                       */
914 /* ------------------------------------------------------------------ */
915 decNumber * decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
916                                      const decNumber *rhs, decContext *set) {
917   uInt status=0;                   /* accumulator */
918   uInt needbytes;                  /* for space calculations */
919   decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0 */
920   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
921   decNumber bufb[D2N(DECBUFFER+1)];
922   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
923   decNumber *a, *b;                /* temporary pointers */
924
925   #if DECCHECK
926   if (decCheckOperands(res, lhs, rhs, set)) return res;
927   #endif
928
929   do {                                  /* protect allocated storage */
930     /* if either is negative, take a copy and absolute */
931     if (decNumberIsNegative(lhs)) {     /* lhs<0 */
932       a=bufa;
933       needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
934       if (needbytes>sizeof(bufa)) {     /* need malloc space */
935         allocbufa=(decNumber *)malloc(needbytes);
936         if (allocbufa==NULL) {          /* hopeless -- abandon */
937           status|=DEC_Insufficient_storage;
938           break;}
939         a=allocbufa;                    /* use the allocated space */
940         }
941       decNumberCopy(a, lhs);            /* copy content */
942       a->bits&=~DECNEG;                 /* .. and clear the sign */
943       lhs=a;                            /* use copy from here on */
944       }
945     if (decNumberIsNegative(rhs)) {     /* rhs<0 */
946       b=bufb;
947       needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
948       if (needbytes>sizeof(bufb)) {     /* need malloc space */
949         allocbufb=(decNumber *)malloc(needbytes);
950         if (allocbufb==NULL) {          /* hopeless -- abandon */
951           status|=DEC_Insufficient_storage;
952           break;}
953         b=allocbufb;                    /* use the allocated space */
954         }
955       decNumberCopy(b, rhs);            /* copy content */
956       b->bits&=~DECNEG;                 /* .. and clear the sign */
957       rhs=b;                            /* use copy from here on */
958       }
959     decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
960     } while(0);                         /* end protected */
961
962   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
963   if (allocbufb!=NULL) free(allocbufb); /* .. */
964   if (status!=0) decStatus(res, status, set);
965   return res;
966   } /* decNumberCompareTotalMag */
967
968 /* ------------------------------------------------------------------ */
969 /* decNumberDivide -- divide one number by another                    */
970 /*                                                                    */
971 /*   This computes C = A / B                                          */
972 /*                                                                    */
973 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
974 /*   lhs is A                                                         */
975 /*   rhs is B                                                         */
976 /*   set is the context                                               */
977 /*                                                                    */
978 /* C must have space for set->digits digits.                          */
979 /* ------------------------------------------------------------------ */
980 decNumber * decNumberDivide(decNumber *res, const decNumber *lhs,
981                             const decNumber *rhs, decContext *set) {
982   uInt status=0;                        /* accumulator */
983   decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
984   if (status!=0) decStatus(res, status, set);
985   #if DECCHECK
986   decCheckInexact(res, set);
987   #endif
988   return res;
989   } /* decNumberDivide */
990
991 /* ------------------------------------------------------------------ */
992 /* decNumberDivideInteger -- divide and return integer quotient       */
993 /*                                                                    */
994 /*   This computes C = A # B, where # is the integer divide operator  */
995 /*                                                                    */
996 /*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
997 /*   lhs is A                                                         */
998 /*   rhs is B                                                         */
999 /*   set is the context                                               */
1000 /*                                                                    */
1001 /* C must have space for set->digits digits.                          */
1002 /* ------------------------------------------------------------------ */
1003 decNumber * decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1004                                    const decNumber *rhs, decContext *set) {
1005   uInt status=0;                        /* accumulator */
1006   decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1007   if (status!=0) decStatus(res, status, set);
1008   return res;
1009   } /* decNumberDivideInteger */
1010
1011 /* ------------------------------------------------------------------ */
1012 /* decNumberExp -- exponentiation                                     */
1013 /*                                                                    */
1014 /*   This computes C = exp(A)                                         */
1015 /*                                                                    */
1016 /*   res is C, the result.  C may be A                                */
1017 /*   rhs is A                                                         */
1018 /*   set is the context; note that rounding mode has no effect        */
1019 /*                                                                    */
1020 /* C must have space for set->digits digits.                          */
1021 /*                                                                    */
1022 /* Mathematical function restrictions apply (see above); a NaN is     */
1023 /* returned with Invalid_operation if a restriction is violated.      */
1024 /*                                                                    */
1025 /* Finite results will always be full precision and Inexact, except   */
1026 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1027 /*                                                                    */
1028 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1029 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1030 /* error in rare cases.                                               */
1031 /* ------------------------------------------------------------------ */
1032 /* This is a wrapper for decExpOp which can handle the slightly wider */
1033 /* (double) range needed by Ln (which has to be able to calculate     */
1034 /* exp(-a) where a can be the tiniest number (Ntiny).                 */
1035 /* ------------------------------------------------------------------ */
1036 decNumber * decNumberExp(decNumber *res, const decNumber *rhs,
1037                          decContext *set) {
1038   uInt status=0;                        /* accumulator */
1039   #if DECSUBSET
1040   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1041   #endif
1042
1043   #if DECCHECK
1044   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1045   #endif
1046
1047   /* Check restrictions; these restrictions ensure that if h=8 (see */
1048   /* decExpOp) then the result will either overflow or underflow to 0. */
1049   /* Other math functions restrict the input range, too, for inverses. */
1050   /* If not violated then carry out the operation. */
1051   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1052     #if DECSUBSET
1053     if (!set->extended) {
1054       /* reduce operand and set lostDigits status, as needed */
1055       if (rhs->digits>set->digits) {
1056         allocrhs=decRoundOperand(rhs, set, &status);
1057         if (allocrhs==NULL) break;
1058         rhs=allocrhs;
1059         }
1060       }
1061     #endif
1062     decExpOp(res, rhs, set, &status);
1063     } while(0);                         /* end protected */
1064
1065   #if DECSUBSET
1066   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
1067   #endif
1068   /* apply significant status */
1069   if (status!=0) decStatus(res, status, set);
1070   #if DECCHECK
1071   decCheckInexact(res, set);
1072   #endif
1073   return res;
1074   } /* decNumberExp */
1075
1076 /* ------------------------------------------------------------------ */
1077 /* decNumberFMA -- fused multiply add                                 */
1078 /*                                                                    */
1079 /*   This computes D = (A * B) + C with only one rounding             */
1080 /*                                                                    */
1081 /*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1082 /*   lhs is A                                                         */
1083 /*   rhs is B                                                         */
1084 /*   fhs is C [far hand side]                                         */
1085 /*   set is the context                                               */
1086 /*                                                                    */
1087 /* Mathematical function restrictions apply (see above); a NaN is     */
1088 /* returned with Invalid_operation if a restriction is violated.      */
1089 /*                                                                    */
1090 /* C must have space for set->digits digits.                          */
1091 /* ------------------------------------------------------------------ */
1092 decNumber * decNumberFMA(decNumber *res, const decNumber *lhs,
1093                          const decNumber *rhs, const decNumber *fhs,
1094                          decContext *set) {
1095   uInt status=0;                   /* accumulator */
1096   decContext dcmul;                /* context for the multiplication */
1097   uInt needbytes;                  /* for space calculations */
1098   decNumber bufa[D2N(DECBUFFER*2+1)];
1099   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
1100   decNumber *acc;                  /* accumulator pointer */
1101   decNumber dzero;                 /* work */
1102
1103   #if DECCHECK
1104   if (decCheckOperands(res, lhs, rhs, set)) return res;
1105   if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1106   #endif
1107
1108   do {                                  /* protect allocated storage */
1109     #if DECSUBSET
1110     if (!set->extended) {               /* [undefined if subset] */
1111       status|=DEC_Invalid_operation;
1112       break;}
1113     #endif
1114     /* Check math restrictions [these ensure no overflow or underflow] */
1115     if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1116      || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1117      || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1118     /* set up context for multiply */
1119     dcmul=*set;
1120     dcmul.digits=lhs->digits+rhs->digits; /* just enough */
1121     /* [The above may be an over-estimate for subset arithmetic, but that's OK] */
1122     dcmul.emax=DEC_MAX_EMAX;            /* effectively unbounded .. */
1123     dcmul.emin=DEC_MIN_EMIN;            /* [thanks to Math restrictions] */
1124     /* set up decNumber space to receive the result of the multiply */
1125     acc=bufa;                           /* may fit */
1126     needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1127     if (needbytes>sizeof(bufa)) {       /* need malloc space */
1128       allocbufa=(decNumber *)malloc(needbytes);
1129       if (allocbufa==NULL) {            /* hopeless -- abandon */
1130         status|=DEC_Insufficient_storage;
1131         break;}
1132       acc=allocbufa;                    /* use the allocated space */
1133       }
1134     /* multiply with extended range and necessary precision */
1135     /*printf("emin=%ld\n", dcmul.emin); */
1136     decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1137     /* Only Invalid operation (from sNaN or Inf * 0) is possible in */
1138     /* status; if either is seen than ignore fhs (in case it is */
1139     /* another sNaN) and set acc to NaN unless we had an sNaN */
1140     /* [decMultiplyOp leaves that to caller] */
1141     /* Note sNaN has to go through addOp to shorten payload if */
1142     /* necessary */
1143     if ((status&DEC_Invalid_operation)!=0) {
1144       if (!(status&DEC_sNaN)) {         /* but be true invalid */
1145         decNumberZero(res);             /* acc not yet set */
1146         res->bits=DECNAN;
1147         break;
1148         }
1149       decNumberZero(&dzero);            /* make 0 (any non-NaN would do) */
1150       fhs=&dzero;                       /* use that */
1151       }
1152     #if DECCHECK
1153      else { /* multiply was OK */
1154       if (status!=0) printf("Status=%08lx after FMA multiply\n", status);
1155       }
1156     #endif
1157     /* add the third operand and result -> res, and all is done */
1158     decAddOp(res, acc, fhs, set, 0, &status);
1159     } while(0);                         /* end protected */
1160
1161   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1162   if (status!=0) decStatus(res, status, set);
1163   #if DECCHECK
1164   decCheckInexact(res, set);
1165   #endif
1166   return res;
1167   } /* decNumberFMA */
1168
1169 /* ------------------------------------------------------------------ */
1170 /* decNumberInvert -- invert a Number, digitwise                      */
1171 /*                                                                    */
1172 /*   This computes C = ~A                                             */
1173 /*                                                                    */
1174 /*   res is C, the result.  C may be A (e.g., X=~X)                   */
1175 /*   rhs is A                                                         */
1176 /*   set is the context (used for result length and error report)     */
1177 /*                                                                    */
1178 /* C must have space for set->digits digits.                          */
1179 /*                                                                    */
1180 /* Logical function restrictions apply (see above); a NaN is          */
1181 /* returned with Invalid_operation if a restriction is violated.      */
1182 /* ------------------------------------------------------------------ */
1183 decNumber * decNumberInvert(decNumber *res, const decNumber *rhs,
1184                             decContext *set) {
1185   const Unit *ua, *msua;                /* -> operand and its msu */
1186   Unit  *uc, *msuc;                     /* -> result and its msu */
1187   Int   msudigs;                        /* digits in res msu */
1188   #if DECCHECK
1189   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1190   #endif
1191
1192   if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1193     decStatus(res, DEC_Invalid_operation, set);
1194     return res;
1195     }
1196   /* operand is valid */
1197   ua=rhs->lsu;                          /* bottom-up */
1198   uc=res->lsu;                          /* .. */
1199   msua=ua+D2U(rhs->digits)-1;           /* -> msu of rhs */
1200   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
1201   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
1202   for (; uc<=msuc; ua++, uc++) {        /* Unit loop */
1203     Unit a;                             /* extract unit */
1204     Int  i, j;                          /* work */
1205     if (ua>msua) a=0;
1206      else a=*ua;
1207     *uc=0;                              /* can now write back */
1208     /* always need to examine all bits in rhs */
1209     /* This loop could be unrolled and/or use BIN2BCD tables */
1210     for (i=0; i<DECDPUN; i++) {
1211       if ((~a)&1) *uc=*uc+(Unit)powers[i];   /* effect INVERT */
1212       j=a%10;
1213       a=a/10;
1214       if (j>1) {
1215         decStatus(res, DEC_Invalid_operation, set);
1216         return res;
1217         }
1218       if (uc==msuc && i==msudigs-1) break;   /* just did final digit */
1219       } /* each digit */
1220     } /* each unit */
1221   /* [here uc-1 is the msu of the result] */
1222   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1223   res->exponent=0;                      /* integer */
1224   res->bits=0;                          /* sign=0 */
1225   return res;  /* [no status to set] */
1226   } /* decNumberInvert */
1227
1228 /* ------------------------------------------------------------------ */
1229 /* decNumberLn -- natural logarithm                                   */
1230 /*                                                                    */
1231 /*   This computes C = ln(A)                                          */
1232 /*                                                                    */
1233 /*   res is C, the result.  C may be A                                */
1234 /*   rhs is A                                                         */
1235 /*   set is the context; note that rounding mode has no effect        */
1236 /*                                                                    */
1237 /* C must have space for set->digits digits.                          */
1238 /*                                                                    */
1239 /* Notable cases:                                                     */
1240 /*   A<0 -> Invalid                                                   */
1241 /*   A=0 -> -Infinity (Exact)                                         */
1242 /*   A=+Infinity -> +Infinity (Exact)                                 */
1243 /*   A=1 exactly -> 0 (Exact)                                         */
1244 /*                                                                    */
1245 /* Mathematical function restrictions apply (see above); a NaN is     */
1246 /* returned with Invalid_operation if a restriction is violated.      */
1247 /*                                                                    */
1248 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1249 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1250 /* error in rare cases.                                               */
1251 /* ------------------------------------------------------------------ */
1252 /* This is a wrapper for decLnOp which can handle the slightly wider  */
1253 /* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1254 /* to calculate at p+e+2).                                            */
1255 /* ------------------------------------------------------------------ */
1256 decNumber * decNumberLn(decNumber *res, const decNumber *rhs,
1257                         decContext *set) {
1258   uInt status=0;                   /* accumulator */
1259   #if DECSUBSET
1260   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1261   #endif
1262
1263   #if DECCHECK
1264   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1265   #endif
1266
1267   /* Check restrictions; this is a math function; if not violated */
1268   /* then carry out the operation. */
1269   if (!decCheckMath(rhs, set, &status)) do { /* protect allocation */
1270     #if DECSUBSET
1271     if (!set->extended) {
1272       /* reduce operand and set lostDigits status, as needed */
1273       if (rhs->digits>set->digits) {
1274         allocrhs=decRoundOperand(rhs, set, &status);
1275         if (allocrhs==NULL) break;
1276         rhs=allocrhs;
1277         }
1278       /* special check in subset for rhs=0 */
1279       if (ISZERO(rhs)) {                /* +/- zeros -> error */
1280         status|=DEC_Invalid_operation;
1281         break;}
1282       } /* extended=0 */
1283     #endif
1284     decLnOp(res, rhs, set, &status);
1285     } while(0);                         /* end protected */
1286
1287   #if DECSUBSET
1288   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
1289   #endif
1290   /* apply significant status */
1291   if (status!=0) decStatus(res, status, set);
1292   #if DECCHECK
1293   decCheckInexact(res, set);
1294   #endif
1295   return res;
1296   } /* decNumberLn */
1297
1298 /* ------------------------------------------------------------------ */
1299 /* decNumberLogB - get adjusted exponent, by 754r rules               */
1300 /*                                                                    */
1301 /*   This computes C = adjustedexponent(A)                            */
1302 /*                                                                    */
1303 /*   res is C, the result.  C may be A                                */
1304 /*   rhs is A                                                         */
1305 /*   set is the context, used only for digits and status              */
1306 /*                                                                    */
1307 /* C must have space for 10 digits (A might have 10**9 digits and     */
1308 /* an exponent of +999999999, or one digit and an exponent of         */
1309 /* -1999999999).                                                      */
1310 /*                                                                    */
1311 /* This returns the adjusted exponent of A after (in theory) padding  */
1312 /* with zeros on the right to set->digits digits while keeping the    */
1313 /* same value.  The exponent is not limited by emin/emax.             */
1314 /*                                                                    */
1315 /* Notable cases:                                                     */
1316 /*   A<0 -> Use |A|                                                   */
1317 /*   A=0 -> -Infinity (Division by zero)                              */
1318 /*   A=Infinite -> +Infinity (Exact)                                  */
1319 /*   A=1 exactly -> 0 (Exact)                                         */
1320 /*   NaNs are propagated as usual                                     */
1321 /* ------------------------------------------------------------------ */
1322 decNumber * decNumberLogB(decNumber *res, const decNumber *rhs,
1323                           decContext *set) {
1324   uInt status=0;                   /* accumulator */
1325
1326   #if DECCHECK
1327   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1328   #endif
1329
1330   /* NaNs as usual; Infinities return +Infinity; 0->oops */
1331   if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1332    else if (decNumberIsInfinite(rhs)) decNumberCopyAbs(res, rhs);
1333    else if (decNumberIsZero(rhs)) {
1334     decNumberZero(res);                 /* prepare for Infinity */
1335     res->bits=DECNEG|DECINF;            /* -Infinity */
1336     status|=DEC_Division_by_zero;       /* as per 754r */
1337     }
1338    else { /* finite non-zero */
1339     Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent */
1340     decNumberFromInt32(res, ae);        /* lay it out */
1341     }
1342
1343   if (status!=0) decStatus(res, status, set);
1344   return res;
1345   } /* decNumberLogB */
1346
1347 /* ------------------------------------------------------------------ */
1348 /* decNumberLog10 -- logarithm in base 10                             */
1349 /*                                                                    */
1350 /*   This computes C = log10(A)                                       */
1351 /*                                                                    */
1352 /*   res is C, the result.  C may be A                                */
1353 /*   rhs is A                                                         */
1354 /*   set is the context; note that rounding mode has no effect        */
1355 /*                                                                    */
1356 /* C must have space for set->digits digits.                          */
1357 /*                                                                    */
1358 /* Notable cases:                                                     */
1359 /*   A<0 -> Invalid                                                   */
1360 /*   A=0 -> -Infinity (Exact)                                         */
1361 /*   A=+Infinity -> +Infinity (Exact)                                 */
1362 /*   A=10**n (if n is an integer) -> n (Exact)                        */
1363 /*                                                                    */
1364 /* Mathematical function restrictions apply (see above); a NaN is     */
1365 /* returned with Invalid_operation if a restriction is violated.      */
1366 /*                                                                    */
1367 /* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1368 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1369 /* error in rare cases.                                               */
1370 /* ------------------------------------------------------------------ */
1371 /* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1372 /* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1373 /* requested digits and t is the number of digits in the exponent     */
1374 /* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1375 /* fastpath in decLnOp.  The final division is done to the requested  */
1376 /* precision.                                                         */
1377 /* ------------------------------------------------------------------ */
1378 decNumber * decNumberLog10(decNumber *res, const decNumber *rhs,
1379                           decContext *set) {
1380   uInt status=0, ignore=0;         /* status accumulators */
1381   uInt needbytes;                  /* for space calculations */
1382   Int p;                           /* working precision */
1383   Int t;                           /* digits in exponent of A */
1384
1385   /* buffers for a and b working decimals */
1386   /* (adjustment calculator, same size) */
1387   decNumber bufa[D2N(DECBUFFER+2)];
1388   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
1389   decNumber *a=bufa;               /* temporary a */
1390   decNumber bufb[D2N(DECBUFFER+2)];
1391   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
1392   decNumber *b=bufb;               /* temporary b */
1393   decNumber bufw[D2N(10)];         /* working 2-10 digit number */
1394   decNumber *w=bufw;               /* .. */
1395   #if DECSUBSET
1396   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
1397   #endif
1398
1399   decContext aset;                 /* working context */
1400
1401   #if DECCHECK
1402   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1403   #endif
1404
1405   /* Check restrictions; this is a math function; if not violated */
1406   /* then carry out the operation. */
1407   if (!decCheckMath(rhs, set, &status)) do { /* protect malloc */
1408     #if DECSUBSET
1409     if (!set->extended) {
1410       /* reduce operand and set lostDigits status, as needed */
1411       if (rhs->digits>set->digits) {
1412         allocrhs=decRoundOperand(rhs, set, &status);
1413         if (allocrhs==NULL) break;
1414         rhs=allocrhs;
1415         }
1416       /* special check in subset for rhs=0 */
1417       if (ISZERO(rhs)) {                /* +/- zeros -> error */
1418         status|=DEC_Invalid_operation;
1419         break;}
1420       } /* extended=0 */
1421     #endif
1422
1423     decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
1424
1425     /* handle exact powers of 10; only check if +ve finite */
1426     if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1427       Int residue=0;               /* (no residue) */
1428       uInt copystat=0;             /* clean status */
1429
1430       /* round to a single digit... */
1431       aset.digits=1;
1432       decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten */
1433       /* if exact and the digit is 1, rhs is a power of 10 */
1434       if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1435         /* the exponent, conveniently, is the power of 10; making */
1436         /* this the result needs a little care as it might not fit, */
1437         /* so first convert it into the working number, and then move */
1438         /* to res */
1439         decNumberFromInt32(w, w->exponent);
1440         residue=0;
1441         decCopyFit(res, w, set, &residue, &status); /* copy & round */
1442         decFinish(res, set, &residue, &status);     /* cleanup/set flags */
1443         break;
1444         } /* not a power of 10 */
1445       } /* not a candidate for exact */
1446
1447     /* simplify the information-content calculation to use 'total */
1448     /* number of digits in a, including exponent' as compared to the */
1449     /* requested digits, as increasing this will only rarely cost an */
1450     /* iteration in ln(a) anyway */
1451     t=6;                                /* it can never be >6 */
1452
1453     /* allocate space when needed... */
1454     p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1455     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1456     if (needbytes>sizeof(bufa)) {       /* need malloc space */
1457       allocbufa=(decNumber *)malloc(needbytes);
1458       if (allocbufa==NULL) {            /* hopeless -- abandon */
1459         status|=DEC_Insufficient_storage;
1460         break;}
1461       a=allocbufa;                      /* use the allocated space */
1462       }
1463     aset.digits=p;                      /* as calculated */
1464     aset.emax=DEC_MAX_MATH;             /* usual bounds */
1465     aset.emin=-DEC_MAX_MATH;            /* .. */
1466     aset.clamp=0;                       /* and no concrete format */
1467     decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs) */
1468
1469     /* skip the division if the result so far is infinite, NaN, or */
1470     /* zero, or there was an error; note NaN from sNaN needs copy */
1471     if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1472     if (a->bits&DECSPECIAL || ISZERO(a)) {
1473       decNumberCopy(res, a);            /* [will fit] */
1474       break;}
1475
1476     /* for ln(10) an extra 3 digits of precision are needed */
1477     p=set->digits+3;
1478     needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1479     if (needbytes>sizeof(bufb)) {       /* need malloc space */
1480       allocbufb=(decNumber *)malloc(needbytes);
1481       if (allocbufb==NULL) {            /* hopeless -- abandon */
1482         status|=DEC_Insufficient_storage;
1483         break;}
1484       b=allocbufb;                      /* use the allocated space */
1485       }
1486     decNumberZero(w);                   /* set up 10... */
1487     #if DECDPUN==1
1488     w->lsu[1]=1; w->lsu[0]=0;           /* .. */
1489     #else
1490     w->lsu[0]=10;                       /* .. */
1491     #endif
1492     w->digits=2;                        /* .. */
1493
1494     aset.digits=p;
1495     decLnOp(b, w, &aset, &ignore);      /* b=ln(10) */
1496
1497     aset.digits=set->digits;            /* for final divide */
1498     decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result */
1499     } while(0);                         /* [for break] */
1500
1501   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
1502   if (allocbufb!=NULL) free(allocbufb); /* .. */
1503   #if DECSUBSET
1504   if (allocrhs !=NULL) free(allocrhs);  /* .. */
1505   #endif
1506   /* apply significant status */
1507   if (status!=0) decStatus(res, status, set);
1508   #if DECCHECK
1509   decCheckInexact(res, set);
1510   #endif
1511   return res;
1512   } /* decNumberLog10 */
1513
1514 /* ------------------------------------------------------------------ */
1515 /* decNumberMax -- compare two Numbers and return the maximum         */
1516 /*                                                                    */
1517 /*   This computes C = A ? B, returning the maximum by 754R rules     */
1518 /*                                                                    */
1519 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1520 /*   lhs is A                                                         */
1521 /*   rhs is B                                                         */
1522 /*   set is the context                                               */
1523 /*                                                                    */
1524 /* C must have space for set->digits digits.                          */
1525 /* ------------------------------------------------------------------ */
1526 decNumber * decNumberMax(decNumber *res, const decNumber *lhs,
1527                          const decNumber *rhs, decContext *set) {
1528   uInt status=0;                        /* accumulator */
1529   decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1530   if (status!=0) decStatus(res, status, set);
1531   #if DECCHECK
1532   decCheckInexact(res, set);
1533   #endif
1534   return res;
1535   } /* decNumberMax */
1536
1537 /* ------------------------------------------------------------------ */
1538 /* decNumberMaxMag -- compare and return the maximum by magnitude     */
1539 /*                                                                    */
1540 /*   This computes C = A ? B, returning the maximum by 754R rules     */
1541 /*                                                                    */
1542 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1543 /*   lhs is A                                                         */
1544 /*   rhs is B                                                         */
1545 /*   set is the context                                               */
1546 /*                                                                    */
1547 /* C must have space for set->digits digits.                          */
1548 /* ------------------------------------------------------------------ */
1549 decNumber * decNumberMaxMag(decNumber *res, const decNumber *lhs,
1550                          const decNumber *rhs, decContext *set) {
1551   uInt status=0;                        /* accumulator */
1552   decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1553   if (status!=0) decStatus(res, status, set);
1554   #if DECCHECK
1555   decCheckInexact(res, set);
1556   #endif
1557   return res;
1558   } /* decNumberMaxMag */
1559
1560 /* ------------------------------------------------------------------ */
1561 /* decNumberMin -- compare two Numbers and return the minimum         */
1562 /*                                                                    */
1563 /*   This computes C = A ? B, returning the minimum by 754R rules     */
1564 /*                                                                    */
1565 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1566 /*   lhs is A                                                         */
1567 /*   rhs is B                                                         */
1568 /*   set is the context                                               */
1569 /*                                                                    */
1570 /* C must have space for set->digits digits.                          */
1571 /* ------------------------------------------------------------------ */
1572 decNumber * decNumberMin(decNumber *res, const decNumber *lhs,
1573                          const decNumber *rhs, decContext *set) {
1574   uInt status=0;                        /* accumulator */
1575   decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1576   if (status!=0) decStatus(res, status, set);
1577   #if DECCHECK
1578   decCheckInexact(res, set);
1579   #endif
1580   return res;
1581   } /* decNumberMin */
1582
1583 /* ------------------------------------------------------------------ */
1584 /* decNumberMinMag -- compare and return the minimum by magnitude     */
1585 /*                                                                    */
1586 /*   This computes C = A ? B, returning the minimum by 754R rules     */
1587 /*                                                                    */
1588 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1589 /*   lhs is A                                                         */
1590 /*   rhs is B                                                         */
1591 /*   set is the context                                               */
1592 /*                                                                    */
1593 /* C must have space for set->digits digits.                          */
1594 /* ------------------------------------------------------------------ */
1595 decNumber * decNumberMinMag(decNumber *res, const decNumber *lhs,
1596                          const decNumber *rhs, decContext *set) {
1597   uInt status=0;                        /* accumulator */
1598   decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1599   if (status!=0) decStatus(res, status, set);
1600   #if DECCHECK
1601   decCheckInexact(res, set);
1602   #endif
1603   return res;
1604   } /* decNumberMinMag */
1605
1606 /* ------------------------------------------------------------------ */
1607 /* decNumberMinus -- prefix minus operator                            */
1608 /*                                                                    */
1609 /*   This computes C = 0 - A                                          */
1610 /*                                                                    */
1611 /*   res is C, the result.  C may be A                                */
1612 /*   rhs is A                                                         */
1613 /*   set is the context                                               */
1614 /*                                                                    */
1615 /* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1616 /* C must have space for set->digits digits.                          */
1617 /* ------------------------------------------------------------------ */
1618 /* Simply use AddOp for the subtract, which will do the necessary.    */
1619 /* ------------------------------------------------------------------ */
1620 decNumber * decNumberMinus(decNumber *res, const decNumber *rhs,
1621                            decContext *set) {
1622   decNumber dzero;
1623   uInt status=0;                        /* accumulator */
1624
1625   #if DECCHECK
1626   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1627   #endif
1628
1629   decNumberZero(&dzero);                /* make 0 */
1630   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
1631   decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1632   if (status!=0) decStatus(res, status, set);
1633   #if DECCHECK
1634   decCheckInexact(res, set);
1635   #endif
1636   return res;
1637   } /* decNumberMinus */
1638
1639 /* ------------------------------------------------------------------ */
1640 /* decNumberNextMinus -- next towards -Infinity                       */
1641 /*                                                                    */
1642 /*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1643 /*                                                                    */
1644 /*   res is C, the result.  C may be A                                */
1645 /*   rhs is A                                                         */
1646 /*   set is the context                                               */
1647 /*                                                                    */
1648 /* This is a generalization of 754r NextDown.                         */
1649 /* ------------------------------------------------------------------ */
1650 decNumber * decNumberNextMinus(decNumber *res, const decNumber *rhs,
1651                                decContext *set) {
1652   decNumber dtiny;                           /* constant */
1653   decContext workset=*set;                   /* work */
1654   uInt status=0;                             /* accumulator */
1655   #if DECCHECK
1656   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1657   #endif
1658
1659   /* +Infinity is the special case */
1660   if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1661     decSetMaxValue(res, set);                /* is +ve */
1662     /* there is no status to set */
1663     return res;
1664     }
1665   decNumberZero(&dtiny);                     /* start with 0 */
1666   dtiny.lsu[0]=1;                            /* make number that is .. */
1667   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest */
1668   workset.round=DEC_ROUND_FLOOR;
1669   decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1670   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please */
1671   if (status!=0) decStatus(res, status, set);
1672   return res;
1673   } /* decNumberNextMinus */
1674
1675 /* ------------------------------------------------------------------ */
1676 /* decNumberNextPlus -- next towards +Infinity                        */
1677 /*                                                                    */
1678 /*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1679 /*                                                                    */
1680 /*   res is C, the result.  C may be A                                */
1681 /*   rhs is A                                                         */
1682 /*   set is the context                                               */
1683 /*                                                                    */
1684 /* This is a generalization of 754r NextUp.                           */
1685 /* ------------------------------------------------------------------ */
1686 decNumber * decNumberNextPlus(decNumber *res, const decNumber *rhs,
1687                               decContext *set) {
1688   decNumber dtiny;                           /* constant */
1689   decContext workset=*set;                   /* work */
1690   uInt status=0;                             /* accumulator */
1691   #if DECCHECK
1692   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1693   #endif
1694
1695   /* -Infinity is the special case */
1696   if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1697     decSetMaxValue(res, set);
1698     res->bits=DECNEG;                        /* negative */
1699     /* there is no status to set */
1700     return res;
1701     }
1702   decNumberZero(&dtiny);                     /* start with 0 */
1703   dtiny.lsu[0]=1;                            /* make number that is .. */
1704   dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest */
1705   workset.round=DEC_ROUND_CEILING;
1706   decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1707   status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please */
1708   if (status!=0) decStatus(res, status, set);
1709   return res;
1710   } /* decNumberNextPlus */
1711
1712 /* ------------------------------------------------------------------ */
1713 /* decNumberNextToward -- next towards rhs                            */
1714 /*                                                                    */
1715 /*   This computes C = A +/- infinitesimal, rounded towards           */
1716 /*   +/-Infinity in the direction of B, as per 754r nextafter rules   */
1717 /*                                                                    */
1718 /*   res is C, the result.  C may be A or B.                          */
1719 /*   lhs is A                                                         */
1720 /*   rhs is B                                                         */
1721 /*   set is the context                                               */
1722 /*                                                                    */
1723 /* This is a generalization of 754r NextAfter.                        */
1724 /* ------------------------------------------------------------------ */
1725 decNumber * decNumberNextToward(decNumber *res, const decNumber *lhs,
1726                                 const decNumber *rhs, decContext *set) {
1727   decNumber dtiny;                           /* constant */
1728   decContext workset=*set;                   /* work */
1729   Int result;                                /* .. */
1730   uInt status=0;                             /* accumulator */
1731   #if DECCHECK
1732   if (decCheckOperands(res, lhs, rhs, set)) return res;
1733   #endif
1734
1735   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1736     decNaNs(res, lhs, rhs, set, &status);
1737     }
1738    else { /* Is numeric, so no chance of sNaN Invalid, etc. */
1739     result=decCompare(lhs, rhs, 0);     /* sign matters */
1740     if (result==BADINT) status|=DEC_Insufficient_storage; /* rare */
1741      else { /* valid compare */
1742       if (result==0) decNumberCopySign(res, lhs, rhs); /* easy */
1743        else { /* differ: need NextPlus or NextMinus */
1744         uByte sub;                      /* add or subtract */
1745         if (result<0) {                 /* lhs<rhs, do nextplus */
1746           /* -Infinity is the special case */
1747           if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1748             decSetMaxValue(res, set);
1749             res->bits=DECNEG;           /* negative */
1750             return res;                 /* there is no status to set */
1751             }
1752           workset.round=DEC_ROUND_CEILING;
1753           sub=0;                        /* add, please */
1754           } /* plus */
1755          else {                         /* lhs>rhs, do nextminus */
1756           /* +Infinity is the special case */
1757           if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1758             decSetMaxValue(res, set);
1759             return res;                 /* there is no status to set */
1760             }
1761           workset.round=DEC_ROUND_FLOOR;
1762           sub=DECNEG;                   /* subtract, please */
1763           } /* minus */
1764         decNumberZero(&dtiny);          /* start with 0 */
1765         dtiny.lsu[0]=1;                 /* make number that is .. */
1766         dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest */
1767         decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or - */
1768         /* turn off exceptions if the result is a normal number */
1769         /* (including Nmin), otherwise let all status through */
1770         if (decNumberIsNormal(res, set)) status=0;
1771         } /* unequal */
1772       } /* compare OK */
1773     } /* numeric */
1774   if (status!=0) decStatus(res, status, set);
1775   return res;
1776   } /* decNumberNextToward */
1777
1778 /* ------------------------------------------------------------------ */
1779 /* decNumberOr -- OR two Numbers, digitwise                           */
1780 /*                                                                    */
1781 /*   This computes C = A | B                                          */
1782 /*                                                                    */
1783 /*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1784 /*   lhs is A                                                         */
1785 /*   rhs is B                                                         */
1786 /*   set is the context (used for result length and error report)     */
1787 /*                                                                    */
1788 /* C must have space for set->digits digits.                          */
1789 /*                                                                    */
1790 /* Logical function restrictions apply (see above); a NaN is          */
1791 /* returned with Invalid_operation if a restriction is violated.      */
1792 /* ------------------------------------------------------------------ */
1793 decNumber * decNumberOr(decNumber *res, const decNumber *lhs,
1794                         const decNumber *rhs, decContext *set) {
1795   const Unit *ua, *ub;                  /* -> operands */
1796   const Unit *msua, *msub;              /* -> operand msus */
1797   Unit  *uc, *msuc;                     /* -> result and its msu */
1798   Int   msudigs;                        /* digits in res msu */
1799   #if DECCHECK
1800   if (decCheckOperands(res, lhs, rhs, set)) return res;
1801   #endif
1802
1803   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1804    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1805     decStatus(res, DEC_Invalid_operation, set);
1806     return res;
1807     }
1808   /* operands are valid */
1809   ua=lhs->lsu;                          /* bottom-up */
1810   ub=rhs->lsu;                          /* .. */
1811   uc=res->lsu;                          /* .. */
1812   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
1813   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
1814   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
1815   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
1816   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
1817     Unit a, b;                          /* extract units */
1818     if (ua>msua) a=0;
1819      else a=*ua;
1820     if (ub>msub) b=0;
1821      else b=*ub;
1822     *uc=0;                              /* can now write back */
1823     if (a|b) {                          /* maybe 1 bits to examine */
1824       Int i, j;
1825       /* This loop could be unrolled and/or use BIN2BCD tables */
1826       for (i=0; i<DECDPUN; i++) {
1827         if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR */
1828         j=a%10;
1829         a=a/10;
1830         j|=b%10;
1831         b=b/10;
1832         if (j>1) {
1833           decStatus(res, DEC_Invalid_operation, set);
1834           return res;
1835           }
1836         if (uc==msuc && i==msudigs-1) break;      /* just did final digit */
1837         } /* each digit */
1838       } /* non-zero */
1839     } /* each unit */
1840   /* [here uc-1 is the msu of the result] */
1841   res->digits=decGetDigits(res->lsu, uc-res->lsu);
1842   res->exponent=0;                      /* integer */
1843   res->bits=0;                          /* sign=0 */
1844   return res;  /* [no status to set] */
1845   } /* decNumberOr */
1846
1847 /* ------------------------------------------------------------------ */
1848 /* decNumberPlus -- prefix plus operator                              */
1849 /*                                                                    */
1850 /*   This computes C = 0 + A                                          */
1851 /*                                                                    */
1852 /*   res is C, the result.  C may be A                                */
1853 /*   rhs is A                                                         */
1854 /*   set is the context                                               */
1855 /*                                                                    */
1856 /* See also decNumberCopy for a quiet bitwise version of this.        */
1857 /* C must have space for set->digits digits.                          */
1858 /* ------------------------------------------------------------------ */
1859 /* This simply uses AddOp; Add will take fast path after preparing A. */
1860 /* Performance is a concern here, as this routine is often used to    */
1861 /* check operands and apply rounding and overflow/underflow testing.  */
1862 /* ------------------------------------------------------------------ */
1863 decNumber * decNumberPlus(decNumber *res, const decNumber *rhs,
1864                           decContext *set) {
1865   decNumber dzero;
1866   uInt status=0;                        /* accumulator */
1867   #if DECCHECK
1868   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1869   #endif
1870
1871   decNumberZero(&dzero);                /* make 0 */
1872   dzero.exponent=rhs->exponent;         /* [no coefficient expansion] */
1873   decAddOp(res, &dzero, rhs, set, 0, &status);
1874   if (status!=0) decStatus(res, status, set);
1875   #if DECCHECK
1876   decCheckInexact(res, set);
1877   #endif
1878   return res;
1879   } /* decNumberPlus */
1880
1881 /* ------------------------------------------------------------------ */
1882 /* decNumberMultiply -- multiply two Numbers                          */
1883 /*                                                                    */
1884 /*   This computes C = A x B                                          */
1885 /*                                                                    */
1886 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1887 /*   lhs is A                                                         */
1888 /*   rhs is B                                                         */
1889 /*   set is the context                                               */
1890 /*                                                                    */
1891 /* C must have space for set->digits digits.                          */
1892 /* ------------------------------------------------------------------ */
1893 decNumber * decNumberMultiply(decNumber *res, const decNumber *lhs,
1894                               const decNumber *rhs, decContext *set) {
1895   uInt status=0;                   /* accumulator */
1896   decMultiplyOp(res, lhs, rhs, set, &status);
1897   if (status!=0) decStatus(res, status, set);
1898   #if DECCHECK
1899   decCheckInexact(res, set);
1900   #endif
1901   return res;
1902   } /* decNumberMultiply */
1903
1904 /* ------------------------------------------------------------------ */
1905 /* decNumberPower -- raise a number to a power                        */
1906 /*                                                                    */
1907 /*   This computes C = A ** B                                         */
1908 /*                                                                    */
1909 /*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1910 /*   lhs is A                                                         */
1911 /*   rhs is B                                                         */
1912 /*   set is the context                                               */
1913 /*                                                                    */
1914 /* C must have space for set->digits digits.                          */
1915 /*                                                                    */
1916 /* Mathematical function restrictions apply (see above); a NaN is     */
1917 /* returned with Invalid_operation if a restriction is violated.      */
1918 /*                                                                    */
1919 /* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1920 /* restrictions on A and the context are relaxed to the usual bounds, */
1921 /* for compatibility with the earlier (integer power only) version    */
1922 /* of this function.                                                  */
1923 /*                                                                    */
1924 /* When B is an integer, the result may be exact, even if rounded.    */
1925 /*                                                                    */
1926 /* The final result is rounded according to the context; it will      */
1927 /* almost always be correctly rounded, but may be up to 1 ulp in      */
1928 /* error in rare cases.                                               */
1929 /* ------------------------------------------------------------------ */
1930 decNumber * decNumberPower(decNumber *res, const decNumber *lhs,
1931                            const decNumber *rhs, decContext *set) {
1932   #if DECSUBSET
1933   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
1934   decNumber *allocrhs=NULL;        /* .., rhs */
1935   #endif
1936   decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used */
1937   decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used */
1938   Int   reqdigits=set->digits;     /* requested DIGITS */
1939   Int   n;                         /* rhs in binary */
1940   Flag  rhsint=0;                  /* 1 if rhs is an integer */
1941   Flag  useint=0;                  /* 1 if can use integer calculation */
1942   Flag  isoddint=0;                /* 1 if rhs is an integer and odd */
1943   Int   i;                         /* work */
1944   #if DECSUBSET
1945   Int   dropped;                   /* .. */
1946   #endif
1947   uInt  needbytes;                 /* buffer size needed */
1948   Flag  seenbit;                   /* seen a bit while powering */
1949   Int   residue=0;                 /* rounding residue */
1950   uInt  status=0;                  /* accumulators */
1951   uByte bits=0;                    /* result sign if errors */
1952   decContext aset;                 /* working context */
1953   decNumber dnOne;                 /* work value 1... */
1954   /* local accumulator buffer [a decNumber, with digits+elength+1 digits] */
1955   decNumber dacbuff[D2N(DECBUFFER+9)];
1956   decNumber *dac=dacbuff;          /* -> result accumulator */
1957   /* same again for possible 1/lhs calculation */
1958   decNumber invbuff[D2N(DECBUFFER+9)];
1959
1960   #if DECCHECK
1961   if (decCheckOperands(res, lhs, rhs, set)) return res;
1962   #endif
1963
1964   do {                             /* protect allocated storage */
1965     #if DECSUBSET
1966     if (!set->extended) { /* reduce operands and set status, as needed */
1967       if (lhs->digits>reqdigits) {
1968         alloclhs=decRoundOperand(lhs, set, &status);
1969         if (alloclhs==NULL) break;
1970         lhs=alloclhs;
1971         }
1972       if (rhs->digits>reqdigits) {
1973         allocrhs=decRoundOperand(rhs, set, &status);
1974         if (allocrhs==NULL) break;
1975         rhs=allocrhs;
1976         }
1977       }
1978     #endif
1979     /* [following code does not require input rounding] */
1980
1981     /* handle NaNs and rhs Infinity (lhs infinity is harder) */
1982     if (SPECIALARGS) {
1983       if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs */
1984         decNaNs(res, lhs, rhs, set, &status);
1985         break;}
1986       if (decNumberIsInfinite(rhs)) {   /* rhs Infinity */
1987         Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign */
1988         if (decNumberIsNegative(lhs)    /* lhs<0 */
1989          && !decNumberIsZero(lhs))      /* .. */
1990           status|=DEC_Invalid_operation;
1991          else {                         /* lhs >=0 */
1992           decNumberZero(&dnOne);        /* set up 1 */
1993           dnOne.lsu[0]=1;
1994           decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1 */
1995           decNumberZero(res);           /* prepare for 0/1/Infinity */
1996           if (decNumberIsNegative(dac)) {    /* lhs<1 */
1997             if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0] */
1998             }
1999            else if (dac->lsu[0]==0) {        /* lhs=1 */
2000             /* 1**Infinity is inexact, so return fully-padded 1.0000 */
2001             Int shift=set->digits-1;
2002             *res->lsu=1;                     /* was 0, make int 1 */
2003             res->digits=decShiftToMost(res->lsu, 1, shift);
2004             res->exponent=-shift;            /* make 1.0000... */
2005             status|=DEC_Inexact|DEC_Rounded; /* deemed inexact */
2006             }
2007            else {                            /* lhs>1 */
2008             if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0] */
2009             }
2010           } /* lhs>=0 */
2011         break;}
2012       /* [lhs infinity drops through] */
2013       } /* specials */
2014
2015     /* Original rhs may be an integer that fits and is in range */
2016     n=decGetInt(rhs);
2017     if (n!=BADINT) {                    /* it is an integer */
2018       rhsint=1;                         /* record the fact for 1**n */
2019       isoddint=(Flag)n&1;               /* [works even if big] */
2020       if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path? */
2021         useint=1;                       /* looks good */
2022       }
2023
2024     if (decNumberIsNegative(lhs)        /* -x .. */
2025       && isoddint) bits=DECNEG;         /* .. to an odd power */
2026
2027     /* handle LHS infinity */
2028     if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled] */
2029       uByte rbits=rhs->bits;            /* save */
2030       decNumberZero(res);               /* prepare */
2031       if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1 */
2032        else {
2033         /* -Inf**nonint -> error */
2034         if (!rhsint && decNumberIsNegative(lhs)) {
2035           status|=DEC_Invalid_operation;     /* -Inf**nonint is error */
2036           break;}
2037         if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n */
2038         /* [otherwise will be 0 or -0] */
2039         res->bits=bits;
2040         }
2041       break;}
2042
2043     /* similarly handle LHS zero */
2044     if (decNumberIsZero(lhs)) {
2045       if (n==0) {                            /* 0**0 => Error */
2046         #if DECSUBSET
2047         if (!set->extended) {                /* [unless subset] */
2048           decNumberZero(res);
2049           *res->lsu=1;                       /* return 1 */
2050           break;}
2051         #endif
2052         status|=DEC_Invalid_operation;
2053         }
2054        else {                                /* 0**x */
2055         uByte rbits=rhs->bits;               /* save */
2056         if (rbits & DECNEG) {                /* was a 0**(-n) */
2057           #if DECSUBSET
2058           if (!set->extended) {              /* [bad if subset] */
2059             status|=DEC_Invalid_operation;
2060             break;}
2061           #endif
2062           bits|=DECINF;
2063           }
2064         decNumberZero(res);                  /* prepare */
2065         /* [otherwise will be 0 or -0] */
2066         res->bits=bits;
2067         }
2068       break;}
2069
2070     /* here both lhs and rhs are finite; rhs==0 is handled in the */
2071     /* integer path.  Next handle the non-integer cases */
2072     if (!useint) {                      /* non-integral rhs */
2073       /* any -ve lhs is bad, as is either operand or context out of */
2074       /* bounds */
2075       if (decNumberIsNegative(lhs)) {
2076         status|=DEC_Invalid_operation;
2077         break;}
2078       if (decCheckMath(lhs, set, &status)
2079        || decCheckMath(rhs, set, &status)) break; /* variable status */
2080
2081       decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context */
2082       aset.emax=DEC_MAX_MATH;           /* usual bounds */
2083       aset.emin=-DEC_MAX_MATH;          /* .. */
2084       aset.clamp=0;                     /* and no concrete format */
2085
2086       /* calculate the result using exp(ln(lhs)*rhs), which can */
2087       /* all be done into the accumulator, dac.  The precision needed */
2088       /* is enough to contain the full information in the lhs (which */
2089       /* is the total digits, including exponent), or the requested */
2090       /* precision, if larger, + 4; 6 is used for the exponent */
2091       /* maximum length, and this is also used when it is shorter */
2092       /* than the requested digits as it greatly reduces the >0.5 ulp */
2093       /* cases at little cost (because Ln doubles digits each */
2094       /* iteration so a few extra digits rarely causes an extra */
2095       /* iteration) */
2096       aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2097       } /* non-integer rhs */
2098
2099      else { /* rhs is in-range integer */
2100       if (n==0) {                       /* x**0 = 1 */
2101         /* (0**0 was handled above) */
2102         decNumberZero(res);             /* result=1 */
2103         *res->lsu=1;                    /* .. */
2104         break;}
2105       /* rhs is a non-zero integer */
2106       if (n<0) n=-n;                    /* use abs(n) */
2107
2108       aset=*set;                        /* clone the context */
2109       aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced */
2110       /* calculate the working DIGITS */
2111       aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2112       #if DECSUBSET
2113       if (!set->extended) aset.digits--;     /* use classic precision */
2114       #endif
2115       /* it's an error if this is more than can be handled */
2116       if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2117       } /* integer path */
2118
2119     /* aset.digits is the count of digits for the accumulator needed */
2120     /* if accumulator is too long for local storage, then allocate */
2121     needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2122     /* [needbytes also used below if 1/lhs needed] */
2123     if (needbytes>sizeof(dacbuff)) {
2124       allocdac=(decNumber *)malloc(needbytes);
2125       if (allocdac==NULL) {   /* hopeless -- abandon */
2126         status|=DEC_Insufficient_storage;
2127         break;}
2128       dac=allocdac;           /* use the allocated space */
2129       }
2130     /* here, aset is set up and accumulator is ready for use */
2131
2132     if (!useint) {                           /* non-integral rhs */
2133       /* x ** y; special-case x=1 here as it will otherwise always */
2134       /* reduce to integer 1; decLnOp has a fastpath which detects */
2135       /* the case of x=1 */
2136       decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs) */
2137       /* [no error possible, as lhs 0 already handled] */
2138       if (ISZERO(dac)) {                     /* x==1, 1.0, etc. */
2139         /* need to return fully-padded 1.0000 etc., but rhsint->1 */
2140         *dac->lsu=1;                         /* was 0, make int 1 */
2141         if (!rhsint) {                       /* add padding */
2142           Int shift=set->digits-1;
2143           dac->digits=decShiftToMost(dac->lsu, 1, shift);
2144           dac->exponent=-shift;              /* make 1.0000... */
2145           status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact */
2146           }
2147         }
2148        else {
2149         decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs */
2150         decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac) */
2151         }
2152       /* and drop through for final rounding */
2153       } /* non-integer rhs */
2154
2155      else {                             /* carry on with integer */
2156       decNumberZero(dac);               /* acc=1 */
2157       *dac->lsu=1;                      /* .. */
2158
2159       /* if a negative power the constant 1 is needed, and if not subset */
2160       /* invert the lhs now rather than inverting the result later */
2161       if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0] */
2162         decNumber *inv=invbuff;         /* asssume use fixed buffer */
2163         decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later] */
2164         #if DECSUBSET
2165         if (set->extended) {            /* need to calculate 1/lhs */
2166         #endif
2167           /* divide lhs into 1, putting result in dac [dac=1/dac] */
2168           decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2169           /* now locate or allocate space for the inverted lhs */
2170           if (needbytes>sizeof(invbuff)) {
2171             allocinv=(decNumber *)malloc(needbytes);
2172             if (allocinv==NULL) {       /* hopeless -- abandon */
2173               status|=DEC_Insufficient_storage;
2174               break;}
2175             inv=allocinv;               /* use the allocated space */
2176             }
2177           /* [inv now points to big-enough buffer or allocated storage] */
2178           decNumberCopy(inv, dac);      /* copy the 1/lhs */
2179           decNumberCopy(dac, &dnOne);   /* restore acc=1 */
2180           lhs=inv;                      /* .. and go forward with new lhs */
2181         #if DECSUBSET
2182           }
2183         #endif
2184         }
2185
2186       /* Raise-to-the-power loop... */
2187       seenbit=0;                   /* set once a 1-bit is encountered */
2188       for (i=1;;i++){              /* for each bit [top bit ignored] */
2189         /* abandon if had overflow or terminal underflow */
2190         if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
2191           if (status&DEC_Overflow || ISZERO(dac)) break;
2192           }
2193         /* [the following two lines revealed an optimizer bug in a C++ */
2194         /* compiler, with symptom: 5**3 -> 25, when n=n+n was used] */
2195         n=n<<1;                    /* move next bit to testable position */
2196         if (n<0) {                 /* top bit is set */
2197           seenbit=1;               /* OK, significant bit seen */
2198           decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x */
2199           }
2200         if (i==31) break;          /* that was the last bit */
2201         if (!seenbit) continue;    /* no need to square 1 */
2202         decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square] */
2203         } /*i*/ /* 32 bits */
2204
2205       /* complete internal overflow or underflow processing */
2206       if (status & (DEC_Overflow|DEC_Underflow)) {
2207         #if DECSUBSET
2208         /* If subset, and power was negative, reverse the kind of -erflow */
2209         /* [1/x not yet done] */
2210         if (!set->extended && decNumberIsNegative(rhs)) {
2211           if (status & DEC_Overflow)
2212             status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2213            else { /* trickier -- Underflow may or may not be set */
2214             status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both] */
2215             status|=DEC_Overflow;
2216             }
2217           }
2218         #endif
2219         dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign */
2220         /* round subnormals [to set.digits rather than aset.digits] */
2221         /* or set overflow result similarly as required */
2222         decFinalize(dac, set, &residue, &status);
2223         decNumberCopy(res, dac);   /* copy to result (is now OK length) */
2224         break;
2225         }
2226
2227       #if DECSUBSET
2228       if (!set->extended &&                  /* subset math */
2229           decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0] */
2230         /* so divide result into 1 [dac=1/dac] */
2231         decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2232         }
2233       #endif
2234       } /* rhs integer path */
2235
2236     /* reduce result to the requested length and copy to result */
2237     decCopyFit(res, dac, set, &residue, &status);
2238     decFinish(res, set, &residue, &status);  /* final cleanup */
2239     #if DECSUBSET
2240     if (!set->extended) decTrim(res, set, 0, &dropped); /* trailing zeros */
2241     #endif
2242     } while(0);                         /* end protected */
2243
2244   if (allocdac!=NULL) free(allocdac);   /* drop any storage used */
2245   if (allocinv!=NULL) free(allocinv);   /* .. */
2246   #if DECSUBSET
2247   if (alloclhs!=NULL) free(alloclhs);   /* .. */
2248   if (allocrhs!=NULL) free(allocrhs);   /* .. */
2249   #endif
2250   if (status!=0) decStatus(res, status, set);
2251   #if DECCHECK
2252   decCheckInexact(res, set);
2253   #endif
2254   return res;
2255   } /* decNumberPower */
2256
2257 /* ------------------------------------------------------------------ */
2258 /* decNumberQuantize -- force exponent to requested value             */
2259 /*                                                                    */
2260 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2261 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2262 /*   of C has exponent of B.  The numerical value of C will equal A,  */
2263 /*   except for the effects of any rounding that occurred.            */
2264 /*                                                                    */
2265 /*   res is C, the result.  C may be A or B                           */
2266 /*   lhs is A, the number to adjust                                   */
2267 /*   rhs is B, the number with exponent to match                      */
2268 /*   set is the context                                               */
2269 /*                                                                    */
2270 /* C must have space for set->digits digits.                          */
2271 /*                                                                    */
2272 /* Unless there is an error or the result is infinite, the exponent   */
2273 /* after the operation is guaranteed to be equal to that of B.        */
2274 /* ------------------------------------------------------------------ */
2275 decNumber * decNumberQuantize(decNumber *res, const decNumber *lhs,
2276                               const decNumber *rhs, decContext *set) {
2277   uInt status=0;                        /* accumulator */
2278   decQuantizeOp(res, lhs, rhs, set, 1, &status);
2279   if (status!=0) decStatus(res, status, set);
2280   return res;
2281   } /* decNumberQuantize */
2282
2283 /* ------------------------------------------------------------------ */
2284 /* decNumberReduce -- remove trailing zeros                           */
2285 /*                                                                    */
2286 /*   This computes C = 0 + A, and normalizes the result               */
2287 /*                                                                    */
2288 /*   res is C, the result.  C may be A                                */
2289 /*   rhs is A                                                         */
2290 /*   set is the context                                               */
2291 /*                                                                    */
2292 /* C must have space for set->digits digits.                          */
2293 /* ------------------------------------------------------------------ */
2294 /* Previously known as Normalize */
2295 decNumber * decNumberNormalize(decNumber *res, const decNumber *rhs,
2296                                decContext *set) {
2297   return decNumberReduce(res, rhs, set);
2298   } /* decNumberNormalize */
2299
2300 decNumber * decNumberReduce(decNumber *res, const decNumber *rhs,
2301                             decContext *set) {
2302   #if DECSUBSET
2303   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
2304   #endif
2305   uInt status=0;                   /* as usual */
2306   Int  residue=0;                  /* as usual */
2307   Int  dropped;                    /* work */
2308
2309   #if DECCHECK
2310   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2311   #endif
2312
2313   do {                             /* protect allocated storage */
2314     #if DECSUBSET
2315     if (!set->extended) {
2316       /* reduce operand and set lostDigits status, as needed */
2317       if (rhs->digits>set->digits) {
2318         allocrhs=decRoundOperand(rhs, set, &status);
2319         if (allocrhs==NULL) break;
2320         rhs=allocrhs;
2321         }
2322       }
2323     #endif
2324     /* [following code does not require input rounding] */
2325
2326     /* Infinities copy through; NaNs need usual treatment */
2327     if (decNumberIsNaN(rhs)) {
2328       decNaNs(res, rhs, NULL, set, &status);
2329       break;
2330       }
2331
2332     /* reduce result to the requested length and copy to result */
2333     decCopyFit(res, rhs, set, &residue, &status); /* copy & round */
2334     decFinish(res, set, &residue, &status);       /* cleanup/set flags */
2335     decTrim(res, set, 1, &dropped);               /* normalize in place */
2336     } while(0);                              /* end protected */
2337
2338   #if DECSUBSET
2339   if (allocrhs !=NULL) free(allocrhs);       /* .. */
2340   #endif
2341   if (status!=0) decStatus(res, status, set);/* then report status */
2342   return res;
2343   } /* decNumberReduce */
2344
2345 /* ------------------------------------------------------------------ */
2346 /* decNumberRescale -- force exponent to requested value              */
2347 /*                                                                    */
2348 /*   This computes C = op(A, B), where op adjusts the coefficient     */
2349 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
2350 /*   of C has the value B.  The numerical value of C will equal A,    */
2351 /*   except for the effects of any rounding that occurred.            */
2352 /*                                                                    */
2353 /*   res is C, the result.  C may be A or B                           */
2354 /*   lhs is A, the number to adjust                                   */
2355 /*   rhs is B, the requested exponent                                 */
2356 /*   set is the context                                               */
2357 /*                                                                    */
2358 /* C must have space for set->digits digits.                          */
2359 /*                                                                    */
2360 /* Unless there is an error or the result is infinite, the exponent   */
2361 /* after the operation is guaranteed to be equal to B.                */
2362 /* ------------------------------------------------------------------ */
2363 decNumber * decNumberRescale(decNumber *res, const decNumber *lhs,
2364                              const decNumber *rhs, decContext *set) {
2365   uInt status=0;                        /* accumulator */
2366   decQuantizeOp(res, lhs, rhs, set, 0, &status);
2367   if (status!=0) decStatus(res, status, set);
2368   return res;
2369   } /* decNumberRescale */
2370
2371 /* ------------------------------------------------------------------ */
2372 /* decNumberRemainder -- divide and return remainder                  */
2373 /*                                                                    */
2374 /*   This computes C = A % B                                          */
2375 /*                                                                    */
2376 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2377 /*   lhs is A                                                         */
2378 /*   rhs is B                                                         */
2379 /*   set is the context                                               */
2380 /*                                                                    */
2381 /* C must have space for set->digits digits.                          */
2382 /* ------------------------------------------------------------------ */
2383 decNumber * decNumberRemainder(decNumber *res, const decNumber *lhs,
2384                                const decNumber *rhs, decContext *set) {
2385   uInt status=0;                        /* accumulator */
2386   decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2387   if (status!=0) decStatus(res, status, set);
2388   #if DECCHECK
2389   decCheckInexact(res, set);
2390   #endif
2391   return res;
2392   } /* decNumberRemainder */
2393
2394 /* ------------------------------------------------------------------ */
2395 /* decNumberRemainderNear -- divide and return remainder from nearest */
2396 /*                                                                    */
2397 /*   This computes C = A % B, where % is the IEEE remainder operator  */
2398 /*                                                                    */
2399 /*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2400 /*   lhs is A                                                         */
2401 /*   rhs is B                                                         */
2402 /*   set is the context                                               */
2403 /*                                                                    */
2404 /* C must have space for set->digits digits.                          */
2405 /* ------------------------------------------------------------------ */
2406 decNumber * decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2407                                    const decNumber *rhs, decContext *set) {
2408   uInt status=0;                        /* accumulator */
2409   decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2410   if (status!=0) decStatus(res, status, set);
2411   #if DECCHECK
2412   decCheckInexact(res, set);
2413   #endif
2414   return res;
2415   } /* decNumberRemainderNear */
2416
2417 /* ------------------------------------------------------------------ */
2418 /* decNumberRotate -- rotate the coefficient of a Number left/right   */
2419 /*                                                                    */
2420 /*   This computes C = A rot B  (in base ten and rotating set->digits */
2421 /*   digits).                                                         */
2422 /*                                                                    */
2423 /*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2424 /*   lhs is A                                                         */
2425 /*   rhs is B, the number of digits to rotate (-ve to right)          */
2426 /*   set is the context                                               */
2427 /*                                                                    */
2428 /* The digits of the coefficient of A are rotated to the left (if B   */
2429 /* is positive) or to the right (if B is negative) without adjusting  */
2430 /* the exponent or the sign of A.  If lhs->digits is less than        */
2431 /* set->digits the coefficient is padded with zeros on the left       */
2432 /* before the rotate.  Any leading zeros in the result are removed    */
2433 /* as usual.                                                          */
2434 /*                                                                    */
2435 /* B must be an integer (q=0) and in the range -set->digits through   */
2436 /* +set->digits.                                                      */
2437 /* C must have space for set->digits digits.                          */
2438 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2439 /* B must be valid).  No status is set unless B is invalid or an      */
2440 /* operand is an sNaN.                                                */
2441 /* ------------------------------------------------------------------ */
2442 decNumber * decNumberRotate(decNumber *res, const decNumber *lhs,
2443                            const decNumber *rhs, decContext *set) {
2444   uInt status=0;              /* accumulator */
2445   Int  rotate;                /* rhs as an Int */
2446
2447   #if DECCHECK
2448   if (decCheckOperands(res, lhs, rhs, set)) return res;
2449   #endif
2450
2451   /* NaNs propagate as normal */
2452   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2453     decNaNs(res, lhs, rhs, set, &status);
2454    /* rhs must be an integer */
2455    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2456     status=DEC_Invalid_operation;
2457    else { /* both numeric, rhs is an integer */
2458     rotate=decGetInt(rhs);                   /* [cannot fail] */
2459     if (rotate==BADINT                       /* something bad .. */
2460      || rotate==BIGODD || rotate==BIGEVEN    /* .. very big .. */
2461      || abs(rotate)>set->digits)             /* .. or out of range */
2462       status=DEC_Invalid_operation;
2463      else {                                  /* rhs is OK */
2464       decNumberCopy(res, lhs);
2465       /* convert -ve rotate to equivalent positive rotation */
2466       if (rotate<0) rotate=set->digits+rotate;
2467       if (rotate!=0 && rotate!=set->digits   /* zero or full rotation */
2468        && !decNumberIsInfinite(res)) {       /* lhs was infinite */
2469         /* left-rotate to do; 0 < rotate < set->digits */
2470         uInt units, shift;                   /* work */
2471         uInt msudigits;                      /* digits in result msu */
2472         Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu */
2473         Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu */
2474         for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0 */
2475         res->digits=set->digits;                  /* now full-length */
2476         msudigits=MSUDIGITS(res->digits);         /* actual digits in msu */
2477
2478         /* rotation here is done in-place, in three steps */
2479         /* 1. shift all to least up to one unit to unit-align final */
2480         /*    lsd [any digits shifted out are rotated to the left, */
2481         /*    abutted to the original msd (which may require split)] */
2482         /* */
2483         /*    [if there are no whole units left to rotate, the */
2484         /*    rotation is now complete] */
2485         /* */
2486         /* 2. shift to least, from below the split point only, so that */
2487         /*    the final msd is in the right place in its Unit [any */
2488         /*    digits shifted out will fit exactly in the current msu, */
2489         /*    left aligned, no split required] */
2490         /* */
2491         /* 3. rotate all the units by reversing left part, right */
2492         /*    part, and then whole */
2493         /* */
2494         /* example: rotate right 8 digits (2 units + 2), DECDPUN=3. */
2495         /* */
2496         /*   start: 00a bcd efg hij klm npq */
2497         /* */
2498         /*      1a  000 0ab cde fgh|ijk lmn [pq saved] */
2499         /*      1b  00p qab cde fgh|ijk lmn */
2500         /* */
2501         /*      2a  00p qab cde fgh|00i jkl [mn saved] */
2502         /*      2b  mnp qab cde fgh|00i jkl */
2503         /* */
2504         /*      3a  fgh cde qab mnp|00i jkl */
2505         /*      3b  fgh cde qab mnp|jkl 00i */
2506         /*      3c  00i jkl mnp qab cde fgh */
2507
2508         /* Step 1: amount to shift is the partial right-rotate count */
2509         rotate=set->digits-rotate;      /* make it right-rotate */
2510         units=rotate/DECDPUN;           /* whole units to rotate */
2511         shift=rotate%DECDPUN;           /* left-over digits count */
2512         if (shift>0) {                  /* not an exact number of units */
2513           uInt save=res->lsu[0]%powers[shift];    /* save low digit(s) */
2514           decShiftToLeast(res->lsu, D2U(res->digits), shift);
2515           if (shift>msudigits) {        /* msumax-1 needs >0 digits */
2516             uInt rem=save%powers[shift-msudigits];/* split save */
2517             *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert */
2518             *(msumax-1)=*(msumax-1)
2519                        +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* .. */
2520             }
2521            else { /* all fits in msumax */
2522             *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1] */
2523             }
2524           } /* digits shift needed */
2525
2526         /* If whole units to rotate... */
2527         if (units>0) {                  /* some to do */
2528           /* Step 2: the units to touch are the whole ones in rotate, */
2529           /*   if any, and the shift is DECDPUN-msudigits (which may be */
2530           /*   0, again) */
2531           shift=DECDPUN-msudigits;
2532           if (shift>0) {                /* not an exact number of units */
2533             uInt save=res->lsu[0]%powers[shift];  /* save low digit(s) */
2534             decShiftToLeast(res->lsu, units, shift);
2535             *msumax=*msumax+(Unit)(save*powers[msudigits]);
2536             } /* partial shift needed */
2537
2538           /* Step 3: rotate the units array using triple reverse */
2539           /* (reversing is easy and fast) */
2540           decReverse(res->lsu+units, msumax);     /* left part */
2541           decReverse(res->lsu, res->lsu+units-1); /* right part */
2542           decReverse(res->lsu, msumax);           /* whole */
2543           } /* whole units to rotate */
2544         /* the rotation may have left an undetermined number of zeros */
2545         /* on the left, so true length needs to be calculated */
2546         res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2547         } /* rotate needed */
2548       } /* rhs OK */
2549     } /* numerics */
2550   if (status!=0) decStatus(res, status, set);
2551   return res;
2552   } /* decNumberRotate */
2553
2554 /* ------------------------------------------------------------------ */
2555 /* decNumberSameQuantum -- test for equal exponents                   */
2556 /*                                                                    */
2557 /*   res is the result number, which will contain either 0 or 1       */
2558 /*   lhs is a number to test                                          */
2559 /*   rhs is the second (usually a pattern)                            */
2560 /*                                                                    */
2561 /* No errors are possible and no context is needed.                   */
2562 /* ------------------------------------------------------------------ */
2563 decNumber * decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2564                                  const decNumber *rhs) {
2565   Unit ret=0;                      /* return value */
2566
2567   #if DECCHECK
2568   if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2569   #endif
2570
2571   if (SPECIALARGS) {
2572     if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2573      else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2574      /* [anything else with a special gives 0] */
2575     }
2576    else if (lhs->exponent==rhs->exponent) ret=1;
2577
2578   decNumberZero(res);              /* OK to overwrite an operand now */
2579   *res->lsu=ret;
2580   return res;
2581   } /* decNumberSameQuantum */
2582
2583 /* ------------------------------------------------------------------ */
2584 /* decNumberScaleB -- multiply by a power of 10                       */
2585 /*                                                                    */
2586 /* This computes C = A x 10**B where B is an integer (q=0) with       */
2587 /* maximum magnitude 2*(emax+digits)                                  */
2588 /*                                                                    */
2589 /*   res is C, the result.  C may be A or B                           */
2590 /*   lhs is A, the number to adjust                                   */
2591 /*   rhs is B, the requested power of ten to use                      */
2592 /*   set is the context                                               */
2593 /*                                                                    */
2594 /* C must have space for set->digits digits.                          */
2595 /*                                                                    */
2596 /* The result may underflow or overflow.                              */
2597 /* ------------------------------------------------------------------ */
2598 decNumber * decNumberScaleB(decNumber *res, const decNumber *lhs,
2599                             const decNumber *rhs, decContext *set) {
2600   Int  reqexp;                /* requested exponent change [B] */
2601   uInt status=0;              /* accumulator */
2602   Int  residue;               /* work */
2603
2604   #if DECCHECK
2605   if (decCheckOperands(res, lhs, rhs, set)) return res;
2606   #endif
2607
2608   /* Handle special values except lhs infinite */
2609   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2610     decNaNs(res, lhs, rhs, set, &status);
2611     /* rhs must be an integer */
2612    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2613     status=DEC_Invalid_operation;
2614    else {
2615     /* lhs is a number; rhs is a finite with q==0 */
2616     reqexp=decGetInt(rhs);                   /* [cannot fail] */
2617     if (reqexp==BADINT                       /* something bad .. */
2618      || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big .. */
2619      || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range */
2620       status=DEC_Invalid_operation;
2621      else {                                  /* rhs is OK */
2622       decNumberCopy(res, lhs);               /* all done if infinite lhs */
2623       if (!decNumberIsInfinite(res)) {       /* prepare to scale */
2624         res->exponent+=reqexp;               /* adjust the exponent */
2625         residue=0;
2626         decFinalize(res, set, &residue, &status); /* .. and check */
2627         } /* finite LHS */
2628       } /* rhs OK */
2629     } /* rhs finite */
2630   if (status!=0) decStatus(res, status, set);
2631   return res;
2632   } /* decNumberScaleB */
2633
2634 /* ------------------------------------------------------------------ */
2635 /* decNumberShift -- shift the coefficient of a Number left or right  */
2636 /*                                                                    */
2637 /*   This computes C = A << B or C = A >> -B  (in base ten).          */
2638 /*                                                                    */
2639 /*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2640 /*   lhs is A                                                         */
2641 /*   rhs is B, the number of digits to shift (-ve to right)           */
2642 /*   set is the context                                               */
2643 /*                                                                    */
2644 /* The digits of the coefficient of A are shifted to the left (if B   */
2645 /* is positive) or to the right (if B is negative) without adjusting  */
2646 /* the exponent or the sign of A.                                     */
2647 /*                                                                    */
2648 /* B must be an integer (q=0) and in the range -set->digits through   */
2649 /* +set->digits.                                                      */
2650 /* C must have space for set->digits digits.                          */
2651 /* NaNs are propagated as usual.  Infinities are unaffected (but      */
2652 /* B must be valid).  No status is set unless B is invalid or an      */
2653 /* operand is an sNaN.                                                */
2654 /* ------------------------------------------------------------------ */
2655 decNumber * decNumberShift(decNumber *res, const decNumber *lhs,
2656                            const decNumber *rhs, decContext *set) {
2657   uInt status=0;              /* accumulator */
2658   Int  shift;                 /* rhs as an Int */
2659
2660   #if DECCHECK
2661   if (decCheckOperands(res, lhs, rhs, set)) return res;
2662   #endif
2663
2664   /* NaNs propagate as normal */
2665   if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2666     decNaNs(res, lhs, rhs, set, &status);
2667    /* rhs must be an integer */
2668    else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2669     status=DEC_Invalid_operation;
2670    else { /* both numeric, rhs is an integer */
2671     shift=decGetInt(rhs);                    /* [cannot fail] */
2672     if (shift==BADINT                        /* something bad .. */
2673      || shift==BIGODD || shift==BIGEVEN      /* .. very big .. */
2674      || abs(shift)>set->digits)              /* .. or out of range */
2675       status=DEC_Invalid_operation;
2676      else {                                  /* rhs is OK */
2677       decNumberCopy(res, lhs);
2678       if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do */
2679         if (shift>0) {                       /* to left */
2680           if (shift==set->digits) {          /* removing all */
2681             *res->lsu=0;                     /* so place 0 */
2682             res->digits=1;                   /* .. */
2683             }
2684            else {                            /* */
2685             /* first remove leading digits if necessary */
2686             if (res->digits+shift>set->digits) {
2687               decDecap(res, res->digits+shift-set->digits);
2688               /* that updated res->digits; may have gone to 1 (for a */
2689               /* single digit or for zero */
2690               }
2691             if (res->digits>1 || *res->lsu)  /* if non-zero.. */
2692               res->digits=decShiftToMost(res->lsu, res->digits, shift);
2693             } /* partial left */
2694           } /* left */
2695          else { /* to right */
2696           if (-shift>=res->digits) {         /* discarding all */
2697             *res->lsu=0;                     /* so place 0 */
2698             res->digits=1;                   /* .. */
2699             }
2700            else {
2701             decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2702             res->digits-=(-shift);
2703             }
2704           } /* to right */
2705         } /* non-0 non-Inf shift */
2706       } /* rhs OK */
2707     } /* numerics */
2708   if (status!=0) decStatus(res, status, set);
2709   return res;
2710   } /* decNumberShift */
2711
2712 /* ------------------------------------------------------------------ */
2713 /* decNumberSquareRoot -- square root operator                        */
2714 /*                                                                    */
2715 /*   This computes C = squareroot(A)                                  */
2716 /*                                                                    */
2717 /*   res is C, the result.  C may be A                                */
2718 /*   rhs is A                                                         */
2719 /*   set is the context; note that rounding mode has no effect        */
2720 /*                                                                    */
2721 /* C must have space for set->digits digits.                          */
2722 /* ------------------------------------------------------------------ */
2723 /* This uses the following varying-precision algorithm in:            */
2724 /*                                                                    */
2725 /*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2726 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2727 /*   pp229-237, ACM, September 1985.                                  */
2728 /*                                                                    */
2729 /* The square-root is calculated using Newton's method, after which   */
2730 /* a check is made to ensure the result is correctly rounded.         */
2731 /*                                                                    */
2732 /* % [Reformatted original Numerical Turing source code follows.]     */
2733 /* function sqrt(x : real) : real                                     */
2734 /* % sqrt(x) returns the properly rounded approximation to the square */
2735 /* % root of x, in the precision of the calling environment, or it    */
2736 /* % fails if x < 0.                                                  */
2737 /* % t e hull and a abrham, august, 1984                              */
2738 /* if x <= 0 then                                                     */
2739 /*   if x < 0 then                                                    */
2740 /*     assert false                                                   */
2741 /*   else                                                             */
2742 /*     result 0                                                       */
2743 /*   end if                                                           */
2744 /* end if                                                             */
2745 /* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2746 /* var e := getexp(x)     % exponent part of x                        */
2747 /* var approx : real                                                  */
2748 /* if e mod 2 = 0  then                                               */
2749 /*   approx := .259 + .819 * f   % approx to root of f                */
2750 /* else                                                               */
2751 /*   f := f/l0                   % adjustments                        */
2752 /*   e := e + 1                  %   for odd                          */
2753 /*   approx := .0819 + 2.59 * f  %   exponent                         */
2754 /* end if                                                             */
2755 /*                                                                    */
2756 /* var p:= 3                                                          */
2757 /* const maxp := currentprecision + 2                                 */
2758 /* loop                                                               */
2759 /*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2760 /*   precision p                                                      */
2761 /*   approx := .5 * (approx + f/approx)                               */
2762 /*   exit when p = maxp                                               */
2763 /* end loop                                                           */
2764 /*                                                                    */
2765 /* % approx is now within 1 ulp of the properly rounded square root   */
2766 /* % of f; to ensure proper rounding, compare squares of (approx -    */
2767 /* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2768 /* p := currentprecision                                              */
2769 /* begin                                                              */
2770 /*   precision p + 2                                                  */
2771 /*   const approxsubhalf := approx - setexp(.5, -p)                   */
2772 /*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2773 /*     approx := approx - setexp(.l, -p + 1)                          */
2774 /*   else                                                             */
2775 /*     const approxaddhalf := approx + setexp(.5, -p)                 */
2776 /*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2777 /*       approx := approx + setexp(.l, -p + 1)                        */
2778 /*     end if                                                         */
2779 /*   end if                                                           */
2780 /* end                                                                */
2781 /* result setexp(approx, e div 2)  % fix exponent                     */
2782 /* end sqrt                                                           */
2783 /* ------------------------------------------------------------------ */
2784 decNumber * decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2785                                 decContext *set) {
2786   decContext workset, approxset;   /* work contexts */
2787   decNumber dzero;                 /* used for constant zero */
2788   Int  maxp;                       /* largest working precision */
2789   Int  workp;                      /* working precision */
2790   Int  residue=0;                  /* rounding residue */
2791   uInt status=0, ignore=0;         /* status accumulators */
2792   uInt rstatus;                    /* .. */
2793   Int  exp;                        /* working exponent */
2794   Int  ideal;                      /* ideal (preferred) exponent */
2795   Int  needbytes;                  /* work */
2796   Int  dropped;                    /* .. */
2797
2798   #if DECSUBSET
2799   decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated */
2800   #endif
2801   /* buffer for f [needs +1 in case DECBUFFER 0] */
2802   decNumber buff[D2N(DECBUFFER+1)];
2803   /* buffer for a [needs +2 to match likely maxp] */
2804   decNumber bufa[D2N(DECBUFFER+2)];
2805   /* buffer for temporary, b [must be same size as a] */
2806   decNumber bufb[D2N(DECBUFFER+2)];
2807   decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated */
2808   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
2809   decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated */
2810   decNumber *f=buff;               /* reduced fraction */
2811   decNumber *a=bufa;               /* approximation to result */
2812   decNumber *b=bufb;               /* intermediate result */
2813   /* buffer for temporary variable, up to 3 digits */
2814   decNumber buft[D2N(3)];
2815   decNumber *t=buft;               /* up-to-3-digit constant or work */
2816
2817   #if DECCHECK
2818   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2819   #endif
2820
2821   do {                             /* protect allocated storage */
2822     #if DECSUBSET
2823     if (!set->extended) {
2824       /* reduce operand and set lostDigits status, as needed */
2825       if (rhs->digits>set->digits) {
2826         allocrhs=decRoundOperand(rhs, set, &status);
2827         if (allocrhs==NULL) break;
2828         /* [Note: 'f' allocation below could reuse this buffer if */
2829         /* used, but as this is rare they are kept separate for clarity.] */
2830         rhs=allocrhs;
2831         }
2832       }
2833     #endif
2834     /* [following code does not require input rounding] */
2835
2836     /* handle infinities and NaNs */
2837     if (SPECIALARG) {
2838       if (decNumberIsInfinite(rhs)) {         /* an infinity */
2839         if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2840          else decNumberCopy(res, rhs);        /* +Infinity */
2841         }
2842        else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
2843       break;
2844       }
2845
2846     /* calculate the ideal (preferred) exponent [floor(exp/2)] */
2847     /* [We would like to write: ideal=rhs->exponent>>1, but this */
2848     /* generates a compiler warning.  Generated code is the same.] */
2849     ideal=(rhs->exponent&~1)/2;         /* target */
2850
2851     /* handle zeros */
2852     if (ISZERO(rhs)) {
2853       decNumberCopy(res, rhs);          /* could be 0 or -0 */
2854       res->exponent=ideal;              /* use the ideal [safe] */
2855       /* use decFinish to clamp any out-of-range exponent, etc. */
2856       decFinish(res, set, &residue, &status);
2857       break;
2858       }
2859
2860     /* any other -x is an oops */
2861     if (decNumberIsNegative(rhs)) {
2862       status|=DEC_Invalid_operation;
2863       break;
2864       }
2865
2866     /* space is needed for three working variables */
2867     /*   f -- the same precision as the RHS, reduced to 0.01->0.99... */
2868     /*   a -- Hull's approximation -- precision, when assigned, is */
2869     /*        currentprecision+1 or the input argument precision, */
2870     /*        whichever is larger (+2 for use as temporary) */
2871     /*   b -- intermediate temporary result (same size as a) */
2872     /* if any is too long for local storage, then allocate */
2873     workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision */
2874     maxp=workp+2;                            /* largest working precision */
2875
2876     needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2877     if (needbytes>(Int)sizeof(buff)) {
2878       allocbuff=(decNumber *)malloc(needbytes);
2879       if (allocbuff==NULL) {  /* hopeless -- abandon */
2880         status|=DEC_Insufficient_storage;
2881         break;}
2882       f=allocbuff;            /* use the allocated space */
2883       }
2884     /* a and b both need to be able to hold a maxp-length number */
2885     needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2886     if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b] */
2887       allocbufa=(decNumber *)malloc(needbytes);
2888       allocbufb=(decNumber *)malloc(needbytes);
2889       if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless */
2890         status|=DEC_Insufficient_storage;
2891         break;}
2892       a=allocbufa;            /* use the allocated spaces */
2893       b=allocbufb;            /* .. */
2894       }
2895
2896     /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1 */
2897     decNumberCopy(f, rhs);
2898     exp=f->exponent+f->digits;               /* adjusted to Hull rules */
2899     f->exponent=-(f->digits);                /* to range */
2900
2901     /* set up working context */
2902     decContextDefault(&workset, DEC_INIT_DECIMAL64);
2903
2904     /* [Until further notice, no error is possible and status bits */
2905     /* (Rounded, etc.) should be ignored, not accumulated.] */
2906
2907     /* Calculate initial approximation, and allow for odd exponent */
2908     workset.digits=workp;                    /* p for initial calculation */
2909     t->bits=0; t->digits=3;
2910     a->bits=0; a->digits=3;
2911     if ((exp & 1)==0) {                      /* even exponent */
2912       /* Set t=0.259, a=0.819 */
2913       t->exponent=-3;
2914       a->exponent=-3;
2915       #if DECDPUN>=3
2916         t->lsu[0]=259;
2917         a->lsu[0]=819;
2918       #elif DECDPUN==2
2919         t->lsu[0]=59; t->lsu[1]=2;
2920         a->lsu[0]=19; a->lsu[1]=8;
2921       #else
2922         t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2923         a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2924       #endif
2925       }
2926      else {                                  /* odd exponent */
2927       /* Set t=0.0819, a=2.59 */
2928       f->exponent--;                         /* f=f/10 */
2929       exp++;                                 /* e=e+1 */
2930       t->exponent=-4;
2931       a->exponent=-2;
2932       #if DECDPUN>=3
2933         t->lsu[0]=819;
2934         a->lsu[0]=259;
2935       #elif DECDPUN==2
2936         t->lsu[0]=19; t->lsu[1]=8;
2937         a->lsu[0]=59; a->lsu[1]=2;
2938       #else
2939         t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2940         a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2941       #endif
2942       }
2943     decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f */
2944     decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t */
2945     /* [a is now the initial approximation for sqrt(f), calculated with */
2946     /* currentprecision, which is also a's precision.] */
2947
2948     /* the main calculation loop */
2949     decNumberZero(&dzero);                   /* make 0 */
2950     decNumberZero(t);                        /* set t = 0.5 */
2951     t->lsu[0]=5;                             /* .. */
2952     t->exponent=-1;                          /* .. */
2953     workset.digits=3;                        /* initial p */
2954     for (;;) {
2955       /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp] */
2956       workset.digits=workset.digits*2-2;
2957       if (workset.digits>maxp) workset.digits=maxp;
2958       /* a = 0.5 * (a + f/a) */
2959       /* [calculated at p then rounded to currentprecision] */
2960       decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a */
2961       decAddOp(b, b, a, &workset, 0, &ignore);    /* b=b+a */
2962       decMultiplyOp(a, b, t, &workset, &ignore);  /* a=b*0.5 */
2963       if (a->digits==maxp) break;            /* have required digits */
2964       } /* loop */
2965
2966     /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits */
2967     /* now reduce to length, etc.; this needs to be done with a */
2968     /* having the correct exponent so as to handle subnormals */
2969     /* correctly */
2970     approxset=*set;                          /* get emin, emax, etc. */
2971     approxset.round=DEC_ROUND_HALF_EVEN;
2972     a->exponent+=exp/2;                      /* set correct exponent */
2973
2974     rstatus=0;                               /* clear status */
2975     residue=0;                               /* .. and accumulator */
2976     decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed) */
2977     decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize */
2978
2979     /* Overflow was possible if the input exponent was out-of-range, */
2980     /* in which case quit */
2981     if (rstatus&DEC_Overflow) {
2982       status=rstatus;                        /* use the status as-is */
2983       decNumberCopy(res, a);                 /* copy to result */
2984       break;
2985       }
2986
2987     /* Preserve status except Inexact/Rounded */
2988     status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
2989
2990     /* Carry out the Hull correction */
2991     a->exponent-=exp/2;                      /* back to 0.1->1 */
2992
2993     /* a is now at final precision and within 1 ulp of the properly */
2994     /* rounded square root of f; to ensure proper rounding, compare */
2995     /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f. */
2996     /* Here workset.digits=maxp and t=0.5, and a->digits determines */
2997     /* the ulp */
2998     workset.digits--;                             /* maxp-1 is OK now */
2999     t->exponent=-a->digits-1;                     /* make 0.5 ulp */
3000     decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp */
3001     workset.round=DEC_ROUND_UP;
3002     decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b) */
3003     decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed */
3004     if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f] */
3005       /* this is the more common adjustment, though both are rare */
3006       t->exponent++;                              /* make 1.0 ulp */
3007       t->lsu[0]=1;                                /* .. */
3008       decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp */
3009       /* assign to approx [round to length] */
3010       approxset.emin-=exp/2;                      /* adjust to match a */
3011       approxset.emax-=exp/2;
3012       decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3013       }
3014      else {
3015       decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp */
3016       workset.round=DEC_ROUND_DOWN;
3017       decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b) */
3018       decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f */
3019       if (decNumberIsNegative(b)) {               /* b < f */
3020         t->exponent++;                            /* make 1.0 ulp */
3021         t->lsu[0]=1;                              /* .. */
3022         decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp */
3023         /* assign to approx [round to length] */
3024         approxset.emin-=exp/2;                    /* adjust to match a */
3025         approxset.emax-=exp/2;
3026         decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3027         }
3028       }
3029     /* [no errors are possible in the above, and rounding/inexact during */
3030     /* estimation are irrelevant, so status was not accumulated] */
3031
3032     /* Here, 0.1 <= a < 1  (still), so adjust back */
3033     a->exponent+=exp/2;                      /* set correct exponent */
3034
3035     /* count droppable zeros [after any subnormal rounding] by */
3036     /* trimming a copy */
3037     decNumberCopy(b, a);
3038     decTrim(b, set, 1, &dropped);            /* [drops trailing zeros] */
3039
3040     /* Set Inexact and Rounded.  The answer can only be exact if */
3041     /* it is short enough so that squaring it could fit in workp digits, */
3042     /* and it cannot have trailing zeros due to clamping, so these are */
3043     /* the only (relatively rare) conditions a careful check is needed */
3044     if (b->digits*2-1 > workp && !set->clamp) { /* cannot fit */
3045       status|=DEC_Inexact|DEC_Rounded;
3046       }
3047      else {                                  /* could be exact/unrounded */
3048       uInt mstatus=0;                        /* local status */
3049       decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply */
3050       if (mstatus&DEC_Overflow) {            /* result just won't fit */
3051         status|=DEC_Inexact|DEC_Rounded;
3052         }
3053        else {                                /* plausible */
3054         decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs */
3055         if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal */
3056          else {                              /* is Exact */
3057           /* here, dropped is the count of trailing zeros in 'a' */
3058           /* use closest exponent to ideal... */
3059           Int todrop=ideal-a->exponent;      /* most that can be dropped */
3060           if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s */
3061            else {                            /* unrounded */
3062             if (dropped<todrop) {            /* clamp to those available */
3063               todrop=dropped;
3064               status|=DEC_Clamped;
3065               }
3066             if (todrop>0) {                  /* have some to drop */
3067               decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3068               a->exponent+=todrop;           /* maintain numerical value */
3069               a->digits-=todrop;             /* new length */
3070               }
3071             }
3072           }
3073         }
3074       }
3075
3076     /* double-check Underflow, as perhaps the result could not have */
3077     /* been subnormal (initial argument too big), or it is now Exact */
3078     if (status&DEC_Underflow) {
3079       Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent */
3080       /* check if truly subnormal */
3081       #if DECEXTFLAG                         /* DEC_Subnormal too */
3082         if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3083       #else
3084         if (ae>=set->emin*2) status&=~DEC_Underflow;
3085       #endif
3086       /* check if truly inexact */
3087       if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3088       }
3089
3090     decNumberCopy(res, a);                   /* a is now the result */
3091     } while(0);                              /* end protected */
3092
3093   if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used */
3094   if (allocbufa!=NULL) free(allocbufa);      /* .. */
3095   if (allocbufb!=NULL) free(allocbufb);      /* .. */
3096   #if DECSUBSET
3097   if (allocrhs !=NULL) free(allocrhs);       /* .. */
3098   #endif
3099   if (status!=0) decStatus(res, status, set);/* then report status */
3100   #if DECCHECK
3101   decCheckInexact(res, set);
3102   #endif
3103   return res;
3104   } /* decNumberSquareRoot */
3105
3106 /* ------------------------------------------------------------------ */
3107 /* decNumberSubtract -- subtract two Numbers                          */
3108 /*                                                                    */
3109 /*   This computes C = A - B                                          */
3110 /*                                                                    */
3111 /*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3112 /*   lhs is A                                                         */
3113 /*   rhs is B                                                         */
3114 /*   set is the context                                               */
3115 /*                                                                    */
3116 /* C must have space for set->digits digits.                          */
3117 /* ------------------------------------------------------------------ */
3118 decNumber * decNumberSubtract(decNumber *res, const decNumber *lhs,
3119                               const decNumber *rhs, decContext *set) {
3120   uInt status=0;                        /* accumulator */
3121
3122   decAddOp(res, lhs, rhs, set, DECNEG, &status);
3123   if (status!=0) decStatus(res, status, set);
3124   #if DECCHECK
3125   decCheckInexact(res, set);
3126   #endif
3127   return res;
3128   } /* decNumberSubtract */
3129
3130 /* ------------------------------------------------------------------ */
3131 /* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3132 /* decNumberToIntegralValue -- round-to-integral-value                */
3133 /*                                                                    */
3134 /*   res is the result                                                */
3135 /*   rhs is input number                                              */
3136 /*   set is the context                                               */
3137 /*                                                                    */
3138 /* res must have space for any value of rhs.                          */
3139 /*                                                                    */
3140 /* This implements the IEEE special operators and therefore treats    */
3141 /* special values as valid.  For finite numbers it returns            */
3142 /* rescale(rhs, 0) if rhs->exponent is <0.                            */
3143 /* Otherwise the result is rhs (so no error is possible, except for   */
3144 /* sNaN).                                                             */
3145 /*                                                                    */
3146 /* The context is used for rounding mode and status after sNaN, but   */
3147 /* the digits setting is ignored.  The Exact version will signal      */
3148 /* Inexact if the result differs numerically from rhs; the other      */
3149 /* never signals Inexact.                                             */
3150 /* ------------------------------------------------------------------ */
3151 decNumber * decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3152                                      decContext *set) {
3153   decNumber dn;
3154   decContext workset;              /* working context */
3155   uInt status=0;                   /* accumulator */
3156
3157   #if DECCHECK
3158   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3159   #endif
3160
3161   /* handle infinities and NaNs */
3162   if (SPECIALARG) {
3163     if (decNumberIsInfinite(rhs)) decNumberCopy(res, rhs); /* an Infinity */
3164      else decNaNs(res, rhs, NULL, set, &status); /* a NaN */
3165     }
3166    else { /* finite */
3167     /* have a finite number; no error possible (res must be big enough) */
3168     if (rhs->exponent>=0) return decNumberCopy(res, rhs);
3169     /* that was easy, but if negative exponent there is work to do... */
3170     workset=*set;                  /* clone rounding, etc. */
3171     workset.digits=rhs->digits;    /* no length rounding */
3172     workset.traps=0;               /* no traps */
3173     decNumberZero(&dn);            /* make a number with exponent 0 */
3174     decNumberQuantize(res, rhs, &dn, &workset);
3175     status|=workset.status;
3176     }
3177   if (status!=0) decStatus(res, status, set);
3178   return res;
3179   } /* decNumberToIntegralExact */
3180
3181 decNumber * decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3182                                      decContext *set) {
3183   decContext workset=*set;         /* working context */
3184   workset.traps=0;                 /* no traps */
3185   decNumberToIntegralExact(res, rhs, &workset);
3186   /* this never affects set, except for sNaNs; NaN will have been set */
3187   /* or propagated already, so no need to call decStatus */
3188   set->status|=workset.status&DEC_Invalid_operation;
3189   return res;
3190   } /* decNumberToIntegralValue */
3191
3192 /* ------------------------------------------------------------------ */
3193 /* decNumberXor -- XOR two Numbers, digitwise                         */
3194 /*                                                                    */
3195 /*   This computes C = A ^ B                                          */
3196 /*                                                                    */
3197 /*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3198 /*   lhs is A                                                         */
3199 /*   rhs is B                                                         */
3200 /*   set is the context (used for result length and error report)     */
3201 /*                                                                    */
3202 /* C must have space for set->digits digits.                          */
3203 /*                                                                    */
3204 /* Logical function restrictions apply (see above); a NaN is          */
3205 /* returned with Invalid_operation if a restriction is violated.      */
3206 /* ------------------------------------------------------------------ */
3207 decNumber * decNumberXor(decNumber *res, const decNumber *lhs,
3208                          const decNumber *rhs, decContext *set) {
3209   const Unit *ua, *ub;                  /* -> operands */
3210   const Unit *msua, *msub;              /* -> operand msus */
3211   Unit  *uc, *msuc;                     /* -> result and its msu */
3212   Int   msudigs;                        /* digits in res msu */
3213   #if DECCHECK
3214   if (decCheckOperands(res, lhs, rhs, set)) return res;
3215   #endif
3216
3217   if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3218    || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3219     decStatus(res, DEC_Invalid_operation, set);
3220     return res;
3221     }
3222   /* operands are valid */
3223   ua=lhs->lsu;                          /* bottom-up */
3224   ub=rhs->lsu;                          /* .. */
3225   uc=res->lsu;                          /* .. */
3226   msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs */
3227   msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs */
3228   msuc=uc+D2U(set->digits)-1;           /* -> msu of result */
3229   msudigs=MSUDIGITS(set->digits);       /* [faster than remainder] */
3230   for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop */
3231     Unit a, b;                          /* extract units */
3232     if (ua>msua) a=0;
3233      else a=*ua;
3234     if (ub>msub) b=0;
3235      else b=*ub;
3236     *uc=0;                              /* can now write back */
3237     if (a|b) {                          /* maybe 1 bits to examine */
3238       Int i, j;
3239       /* This loop could be unrolled and/or use BIN2BCD tables */
3240       for (i=0; i<DECDPUN; i++) {
3241         if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR */
3242         j=a%10;
3243         a=a/10;
3244         j|=b%10;
3245         b=b/10;
3246         if (j>1) {
3247           decStatus(res, DEC_Invalid_operation, set);
3248           return res;
3249           }
3250         if (uc==msuc && i==msudigs-1) break;      /* just did final digit */
3251         } /* each digit */
3252       } /* non-zero */
3253     } /* each unit */
3254   /* [here uc-1 is the msu of the result] */
3255   res->digits=decGetDigits(res->lsu, uc-res->lsu);
3256   res->exponent=0;                      /* integer */
3257   res->bits=0;                          /* sign=0 */
3258   return res;  /* [no status to set] */
3259   } /* decNumberXor */
3260
3261
3262 /* ================================================================== */
3263 /* Utility routines                                                   */
3264 /* ================================================================== */
3265
3266 /* ------------------------------------------------------------------ */
3267 /* decNumberClass -- return the decClass of a decNumber               */
3268 /*   dn -- the decNumber to test                                      */
3269 /*   set -- the context to use for Emin                               */
3270 /*   returns the decClass enum                                        */
3271 /* ------------------------------------------------------------------ */
3272 enum decClass decNumberClass(const decNumber *dn, decContext *set) {
3273   if (decNumberIsSpecial(dn)) {
3274     if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3275     if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3276     /* must be an infinity */
3277     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3278     return DEC_CLASS_POS_INF;
3279     }
3280   /* is finite */
3281   if (decNumberIsNormal(dn, set)) { /* most common */
3282     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3283     return DEC_CLASS_POS_NORMAL;
3284     }
3285   /* is subnormal or zero */
3286   if (decNumberIsZero(dn)) {    /* most common */
3287     if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3288     return DEC_CLASS_POS_ZERO;
3289     }
3290   if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3291   return DEC_CLASS_POS_SUBNORMAL;
3292   } /* decNumberClass */
3293
3294 /* ------------------------------------------------------------------ */
3295 /* decNumberClassToString -- convert decClass to a string             */
3296 /*                                                                    */
3297 /*  eclass is a valid decClass                                        */
3298 /*  returns a constant string describing the class (max 13+1 chars)   */
3299 /* ------------------------------------------------------------------ */
3300 const char *decNumberClassToString(enum decClass eclass) {
3301   if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3302   if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3303   if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3304   if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3305   if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3306   if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3307   if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3308   if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3309   if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3310   if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3311   return DEC_ClassString_UN;           /* Unknown */
3312   } /* decNumberClassToString */
3313
3314 /* ------------------------------------------------------------------ */
3315 /* decNumberCopy -- copy a number                                     */
3316 /*                                                                    */
3317 /*   dest is the target decNumber                                     */
3318 /*   src  is the source decNumber                                     */
3319 /*   returns dest                                                     */
3320 /*                                                                    */
3321 /* (dest==src is allowed and is a no-op)                              */
3322 /* All fields are updated as required.  This is a utility operation,  */
3323 /* so special values are unchanged and no error is possible.          */
3324 /* ------------------------------------------------------------------ */
3325 decNumber * decNumberCopy(decNumber *dest, const decNumber *src) {
3326
3327   #if DECCHECK
3328   if (src==NULL) return decNumberZero(dest);
3329   #endif
3330
3331   if (dest==src) return dest;                /* no copy required */
3332
3333   /* Use explicit assignments here as structure assignment could copy */
3334   /* more than just the lsu (for small DECDPUN).  This would not affect */
3335   /* the value of the results, but could disturb test harness spill */
3336   /* checking. */
3337   dest->bits=src->bits;
3338   dest->exponent=src->exponent;
3339   dest->digits=src->digits;
3340   dest->lsu[0]=src->lsu[0];
3341   if (src->digits>DECDPUN) {                 /* more Units to come */
3342     const Unit *smsup, *s;                   /* work */
3343     Unit  *d;                                /* .. */
3344     /* memcpy for the remaining Units would be safe as they cannot */
3345     /* overlap.  However, this explicit loop is faster in short cases. */
3346     d=dest->lsu+1;                           /* -> first destination */
3347     smsup=src->lsu+D2U(src->digits);         /* -> source msu+1 */
3348     for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3349     }
3350   return dest;
3351   } /* decNumberCopy */
3352
3353 /* ------------------------------------------------------------------ */
3354 /* decNumberCopyAbs -- quiet absolute value operator                  */
3355 /*                                                                    */
3356 /*   This sets C = abs(A)                                             */
3357 /*                                                                    */
3358 /*   res is C, the result.  C may be A                                */
3359 /*   rhs is A                                                         */
3360 /*                                                                    */
3361 /* C must have space for set->digits digits.                          */
3362 /* No exception or error can occur; this is a quiet bitwise operation.*/
3363 /* See also decNumberAbs for a checking version of this.              */
3364 /* ------------------------------------------------------------------ */
3365 decNumber * decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3366   #if DECCHECK
3367   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3368   #endif
3369   decNumberCopy(res, rhs);
3370   res->bits&=~DECNEG;                   /* turn off sign */
3371   return res;
3372   } /* decNumberCopyAbs */
3373
3374 /* ------------------------------------------------------------------ */
3375 /* decNumberCopyNegate -- quiet negate value operator                 */
3376 /*                                                                    */
3377 /*   This sets C = negate(A)                                          */
3378 /*                                                                    */
3379 /*   res is C, the result.  C may be A                                */
3380 /*   rhs is A                                                         */
3381 /*                                                                    */
3382 /* C must have space for set->digits digits.                          */
3383 /* No exception or error can occur; this is a quiet bitwise operation.*/
3384 /* See also decNumberMinus for a checking version of this.            */
3385 /* ------------------------------------------------------------------ */
3386 decNumber * decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3387   #if DECCHECK
3388   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3389   #endif
3390   decNumberCopy(res, rhs);
3391   res->bits^=DECNEG;                    /* invert the sign */
3392   return res;
3393   } /* decNumberCopyNegate */
3394
3395 /* ------------------------------------------------------------------ */
3396 /* decNumberCopySign -- quiet copy and set sign operator              */
3397 /*                                                                    */
3398 /*   This sets C = A with the sign of B                               */
3399 /*                                                                    */
3400 /*   res is C, the result.  C may be A                                */
3401 /*   lhs is A                                                         */
3402 /*   rhs is B                                                         */
3403 /*                                                                    */
3404 /* C must have space for set->digits digits.                          */
3405 /* No exception or error can occur; this is a quiet bitwise operation.*/
3406 /* ------------------------------------------------------------------ */
3407 decNumber * decNumberCopySign(decNumber *res, const decNumber *lhs,
3408                               const decNumber *rhs) {
3409   uByte sign;                           /* rhs sign */
3410   #if DECCHECK
3411   if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3412   #endif
3413   sign=rhs->bits & DECNEG;              /* save sign bit */
3414   decNumberCopy(res, lhs);
3415   res->bits&=~DECNEG;                   /* clear the sign */
3416   res->bits|=sign;                      /* set from rhs */
3417   return res;
3418   } /* decNumberCopySign */
3419
3420 /* ------------------------------------------------------------------ */
3421 /* decNumberGetBCD -- get the coefficient in BCD8                     */
3422 /*   dn is the source decNumber                                       */
3423 /*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3424 /*     most-significant at offset 0                                   */
3425 /*   returns bcd                                                      */
3426 /*                                                                    */
3427 /* bcd must have at least dn->digits bytes.  No error is possible; if */
3428 /* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3429 /* ------------------------------------------------------------------ */
3430 uByte * decNumberGetBCD(const decNumber *dn, uint8_t *bcd) {
3431   uByte *ub=bcd+dn->digits-1;      /* -> lsd */
3432   const Unit *up=dn->lsu;          /* Unit pointer, -> lsu */
3433
3434   #if DECDPUN==1                   /* trivial simple copy */
3435     for (; ub>=bcd; ub--, up++) *ub=*up;
3436   #else                            /* chopping needed */
3437     uInt u=*up;                    /* work */
3438     uInt cut=DECDPUN;              /* downcounter through unit */
3439     for (; ub>=bcd; ub--) {
3440       *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here] */
3441       u=u/10;
3442       cut--;
3443       if (cut>0) continue;         /* more in this unit */
3444       up++;
3445       u=*up;
3446       cut=DECDPUN;
3447       }
3448   #endif
3449   return bcd;
3450   } /* decNumberGetBCD */
3451
3452 /* ------------------------------------------------------------------ */
3453 /* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3454 /*   dn is the target decNumber                                       */
3455 /*   bcd is the uInt array that will source n BCD bytes, most-        */
3456 /*     significant at offset 0                                        */
3457 /*   n is the number of digits in the source BCD array (bcd)          */
3458 /*   returns dn                                                       */
3459 /*                                                                    */
3460 /* dn must have space for at least n digits.  No error is possible;   */
3461 /* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3462 /* and bcd[0] zero.                                                   */
3463 /* ------------------------------------------------------------------ */
3464 decNumber * decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3465   Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer] */
3466   const uByte *ub=bcd;                  /* -> source msd */
3467
3468   #if DECDPUN==1                        /* trivial simple copy */
3469     for (; ub<bcd+n; ub++, up--) *up=*ub;
3470   #else                                 /* some assembly needed */
3471     /* calculate how many digits in msu, and hence first cut */
3472     Int cut=MSUDIGITS(n);               /* [faster than remainder] */
3473     for (;up>=dn->lsu; up--) {          /* each Unit from msu */
3474       *up=0;                            /* will take <=DECDPUN digits */
3475       for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3476       cut=DECDPUN;                      /* next Unit has all digits */
3477       }
3478   #endif
3479   dn->digits=n;                         /* set digit count */
3480   return dn;
3481   } /* decNumberSetBCD */
3482
3483 /* ------------------------------------------------------------------ */
3484 /* decNumberIsNormal -- test normality of a decNumber                 */
3485 /*   dn is the decNumber to test                                      */
3486 /*   set is the context to use for Emin                               */
3487 /*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3488 /* ------------------------------------------------------------------ */
3489 Int decNumberIsNormal(const decNumber *dn, decContext *set) {
3490   Int ae;                               /* adjusted exponent */
3491   #if DECCHECK
3492   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3493   #endif
3494
3495   if (decNumberIsSpecial(dn)) return 0; /* not finite */
3496   if (decNumberIsZero(dn)) return 0;    /* not non-zero */
3497
3498   ae=dn->exponent+dn->digits-1;         /* adjusted exponent */
3499   if (ae<set->emin) return 0;           /* is subnormal */
3500   return 1;
3501   } /* decNumberIsNormal */
3502
3503 /* ------------------------------------------------------------------ */
3504 /* decNumberIsSubnormal -- test subnormality of a decNumber           */
3505 /*   dn is the decNumber to test                                      */
3506 /*   set is the context to use for Emin                               */
3507 /*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3508 /* ------------------------------------------------------------------ */
3509 Int decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3510   Int ae;                               /* adjusted exponent */
3511   #if DECCHECK
3512   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3513   #endif
3514
3515   if (decNumberIsSpecial(dn)) return 0; /* not finite */
3516   if (decNumberIsZero(dn)) return 0;    /* not non-zero */
3517
3518   ae=dn->exponent+dn->digits-1;         /* adjusted exponent */
3519   if (ae<set->emin) return 1;           /* is subnormal */
3520   return 0;
3521   } /* decNumberIsSubnormal */
3522
3523 /* ------------------------------------------------------------------ */
3524 /* decNumberTrim -- remove insignificant zeros                        */
3525 /*                                                                    */
3526 /*   dn is the number to trim                                         */
3527 /*   returns dn                                                       */
3528 /*                                                                    */
3529 /* All fields are updated as required.  This is a utility operation,  */
3530 /* so special values are unchanged and no error is possible.          */
3531 /* ------------------------------------------------------------------ */
3532 decNumber * decNumberTrim(decNumber *dn) {
3533   Int  dropped;                    /* work */
3534   decContext set;                  /* .. */
3535   #if DECCHECK
3536   if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3537   #endif
3538   decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0 */
3539   return decTrim(dn, &set, 0, &dropped);
3540   } /* decNumberTrim */
3541
3542 /* ------------------------------------------------------------------ */
3543 /* decNumberVersion -- return the name and version of this module     */
3544 /*                                                                    */
3545 /* No error is possible.                                              */
3546 /* ------------------------------------------------------------------ */
3547 const char * decNumberVersion(void) {
3548   return DECVERSION;
3549   } /* decNumberVersion */
3550
3551 /* ------------------------------------------------------------------ */
3552 /* decNumberZero -- set a number to 0                                 */
3553 /*                                                                    */
3554 /*   dn is the number to set, with space for one digit                */
3555 /*   returns dn                                                       */
3556 /*                                                                    */
3557 /* No error is possible.                                              */
3558 /* ------------------------------------------------------------------ */
3559 /* Memset is not used as it is much slower in some environments. */
3560 decNumber * decNumberZero(decNumber *dn) {
3561
3562   #if DECCHECK
3563   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3564   #endif
3565
3566   dn->bits=0;
3567   dn->exponent=0;
3568   dn->digits=1;
3569   dn->lsu[0]=0;
3570   return dn;
3571   } /* decNumberZero */
3572
3573 /* ================================================================== */
3574 /* Local routines                                                     */
3575 /* ================================================================== */
3576
3577 /* ------------------------------------------------------------------ */
3578 /* decToString -- lay out a number into a string                      */
3579 /*                                                                    */
3580 /*   dn     is the number to lay out                                  */
3581 /*   string is where to lay out the number                            */
3582 /*   eng    is 1 if Engineering, 0 if Scientific                      */
3583 /*                                                                    */
3584 /* string must be at least dn->digits+14 characters long              */
3585 /* No error is possible.                                              */
3586 /*                                                                    */
3587 /* Note that this routine can generate a -0 or 0.000.  These are      */
3588 /* never generated in subset to-number or arithmetic, but can occur   */
3589 /* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3590 /* ------------------------------------------------------------------ */
3591 /* If DECCHECK is enabled the string "?" is returned if a number is */
3592 /* invalid. */
3593 static void decToString(const decNumber *dn, char *string, Flag eng) {
3594   Int exp=dn->exponent;       /* local copy */
3595   Int e;                      /* E-part value */
3596   Int pre;                    /* digits before the '.' */
3597   Int cut;                    /* for counting digits in a Unit */
3598   char *c=string;             /* work [output pointer] */
3599   const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer] */
3600   uInt u, pow;                /* work */
3601
3602   #if DECCHECK
3603   if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3604     strcpy(string, "?");
3605     return;}
3606   #endif
3607
3608   if (decNumberIsNegative(dn)) {   /* Negatives get a minus */
3609     *c='-';
3610     c++;
3611     }
3612   if (dn->bits&DECSPECIAL) {       /* Is a special value */
3613     if (decNumberIsInfinite(dn)) {
3614       strcpy(c,   "Inf");
3615       strcpy(c+3, "inity");
3616       return;}
3617     /* a NaN */
3618     if (dn->bits&DECSNAN) {        /* signalling NaN */
3619       *c='s';
3620       c++;
3621       }
3622     strcpy(c, "NaN");
3623     c+=3;                          /* step past */
3624     /* if not a clean non-zero coefficient, that's all there is in a */
3625     /* NaN string */
3626     if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3627     /* [drop through to add integer] */
3628     }
3629
3630   /* calculate how many digits in msu, and hence first cut */
3631   cut=MSUDIGITS(dn->digits);       /* [faster than remainder] */
3632   cut--;                           /* power of ten for digit */
3633
3634   if (exp==0) {                    /* simple integer [common fastpath] */
3635     for (;up>=dn->lsu; up--) {     /* each Unit from msu */
3636       u=*up;                       /* contains DECDPUN digits to lay out */
3637       for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3638       cut=DECDPUN-1;               /* next Unit has all digits */
3639       }
3640     *c='\0';                       /* terminate the string */
3641     return;}
3642
3643   /* non-0 exponent -- assume plain form */
3644   pre=dn->digits+exp;              /* digits before '.' */
3645   e=0;                             /* no E */
3646   if ((exp>0) || (pre<-5)) {       /* need exponential form */
3647     e=exp+dn->digits-1;            /* calculate E value */
3648     pre=1;                         /* assume one digit before '.' */
3649     if (eng && (e!=0)) {           /* engineering: may need to adjust */
3650       Int adj;                     /* adjustment */
3651       /* The C remainder operator is undefined for negative numbers, so */
3652       /* a positive remainder calculation must be used here */
3653       if (e<0) {
3654         adj=(-e)%3;
3655         if (adj!=0) adj=3-adj;
3656         }
3657        else { /* e>0 */
3658         adj=e%3;
3659         }
3660       e=e-adj;
3661       /* if dealing with zero still produce an exponent which is a */
3662       /* multiple of three, as expected, but there will only be the */
3663       /* one zero before the E, still.  Otherwise note the padding. */
3664       if (!ISZERO(dn)) pre+=adj;
3665        else {  /* is zero */
3666         if (adj!=0) {              /* 0.00Esnn needed */
3667           e=e+3;
3668           pre=-(2-adj);
3669           }
3670         } /* zero */
3671       } /* eng */
3672     } /* need exponent */
3673
3674   /* lay out the digits of the coefficient, adding 0s and . as needed */
3675   u=*up;
3676   if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form */
3677     Int n=pre;
3678     for (; pre>0; pre--, c++, cut--) {
3679       if (cut<0) {                 /* need new Unit */
3680         if (up==dn->lsu) break;    /* out of input digits (pre>digits) */
3681         up--;
3682         cut=DECDPUN-1;
3683         u=*up;
3684         }
3685       TODIGIT(u, cut, c, pow);
3686       }
3687     if (n<dn->digits) {            /* more to come, after '.' */
3688       *c='.'; c++;
3689       for (;; c++, cut--) {
3690         if (cut<0) {               /* need new Unit */
3691           if (up==dn->lsu) break;  /* out of input digits */
3692           up--;
3693           cut=DECDPUN-1;
3694           u=*up;
3695           }
3696         TODIGIT(u, cut, c, pow);
3697         }
3698       }
3699      else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed */
3700     }
3701    else {                          /* 0.xxx or 0.000xxx form */
3702     *c='0'; c++;
3703     *c='.'; c++;
3704     for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.' */
3705     for (; ; c++, cut--) {
3706       if (cut<0) {                 /* need new Unit */
3707         if (up==dn->lsu) break;    /* out of input digits */
3708         up--;
3709         cut=DECDPUN-1;
3710         u=*up;
3711         }
3712       TODIGIT(u, cut, c, pow);
3713       }
3714     }
3715
3716   /* Finally add the E-part, if needed.  It will never be 0, has a
3717      base maximum and minimum of +999999999 through -999999999, but
3718      could range down to -1999999998 for anormal numbers */
3719   if (e!=0) {
3720     Flag had=0;               /* 1=had non-zero */
3721     *c='E'; c++;
3722     *c='+'; c++;              /* assume positive */
3723     u=e;                      /* .. */
3724     if (e<0) {
3725       *(c-1)='-';             /* oops, need - */
3726       u=-e;                   /* uInt, please */
3727       }
3728     /* lay out the exponent [_itoa or equivalent is not ANSI C] */
3729     for (cut=9; cut>=0; cut--) {
3730       TODIGIT(u, cut, c, pow);
3731       if (*c=='0' && !had) continue;    /* skip leading zeros */
3732       had=1;                            /* had non-0 */
3733       c++;                              /* step for next */
3734       } /* cut */
3735     }
3736   *c='\0';          /* terminate the string (all paths) */
3737   return;
3738   } /* decToString */
3739
3740 /* ------------------------------------------------------------------ */
3741 /* decAddOp -- add/subtract operation                                 */
3742 /*                                                                    */
3743 /*   This computes C = A + B                                          */
3744 /*                                                                    */
3745 /*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3746 /*   lhs is A                                                         */
3747 /*   rhs is B                                                         */
3748 /*   set is the context                                               */
3749 /*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3750 /*   status accumulates status for the caller                         */
3751 /*                                                                    */
3752 /* C must have space for set->digits digits.                          */
3753 /* Inexact in status must be 0 for correct Exact zero sign in result  */
3754 /* ------------------------------------------------------------------ */
3755 /* If possible, the coefficient is calculated directly into C.        */
3756 /* However, if:                                                       */
3757 /*   -- a digits+1 calculation is needed because the numbers are      */
3758 /*      unaligned and span more than set->digits digits               */
3759 /*   -- a carry to digits+1 digits looks possible                     */
3760 /*   -- C is the same as A or B, and the result would destructively   */
3761 /*      overlap the A or B coefficient                                */
3762 /* then the result must be calculated into a temporary buffer.  In    */
3763 /* this case a local (stack) buffer is used if possible, and only if  */
3764 /* too long for that does malloc become the final resort.             */
3765 /*                                                                    */
3766 /* Misalignment is handled as follows:                                */
3767 /*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3768 /*   BPad: Apply the padding by a combination of shifting (whole      */
3769 /*         units) and multiplication (part units).                    */
3770 /*                                                                    */
3771 /* Addition, especially x=x+1, is speed-critical.                     */
3772 /* The static buffer is larger than might be expected to allow for    */
3773 /* calls from higher-level funtions (notable exp).                    */
3774 /* ------------------------------------------------------------------ */
3775 static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3776                             const decNumber *rhs, decContext *set,
3777                             uByte negate, uInt *status) {
3778   #if DECSUBSET
3779   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
3780   decNumber *allocrhs=NULL;        /* .., rhs */
3781   #endif
3782   Int   rhsshift;                  /* working shift (in Units) */
3783   Int   maxdigits;                 /* longest logical length */
3784   Int   mult;                      /* multiplier */
3785   Int   residue;                   /* rounding accumulator */
3786   uByte bits;                      /* result bits */
3787   Flag  diffsign;                  /* non-0 if arguments have different sign */
3788   Unit  *acc;                      /* accumulator for result */
3789   Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many */
3790                                    /* allocations when called from */
3791                                    /* other operations, notable exp] */
3792   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated */
3793   Int   reqdigits=set->digits;     /* local copy; requested DIGITS */
3794   Int   padding;                   /* work */
3795
3796   #if DECCHECK
3797   if (decCheckOperands(res, lhs, rhs, set)) return res;
3798   #endif
3799
3800   do {                             /* protect allocated storage */
3801     #if DECSUBSET
3802     if (!set->extended) {
3803       /* reduce operands and set lostDigits status, as needed */
3804       if (lhs->digits>reqdigits) {
3805         alloclhs=decRoundOperand(lhs, set, status);
3806         if (alloclhs==NULL) break;
3807         lhs=alloclhs;
3808         }
3809       if (rhs->digits>reqdigits) {
3810         allocrhs=decRoundOperand(rhs, set, status);
3811         if (allocrhs==NULL) break;
3812         rhs=allocrhs;
3813         }
3814       }
3815     #endif
3816     /* [following code does not require input rounding] */
3817
3818     /* note whether signs differ [used all paths] */
3819     diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3820
3821     /* handle infinities and NaNs */
3822     if (SPECIALARGS) {                  /* a special bit set */
3823       if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN */
3824         decNaNs(res, lhs, rhs, set, status);
3825        else { /* one or two infinities */
3826         if (decNumberIsInfinite(lhs)) { /* LHS is infinity */
3827           /* two infinities with different signs is invalid */
3828           if (decNumberIsInfinite(rhs) && diffsign) {
3829             *status|=DEC_Invalid_operation;
3830             break;
3831             }
3832           bits=lhs->bits & DECNEG;      /* get sign from LHS */
3833           }
3834          else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity */
3835         bits|=DECINF;
3836         decNumberZero(res);
3837         res->bits=bits;                 /* set +/- infinity */
3838         } /* an infinity */
3839       break;
3840       }
3841
3842     /* Quick exit for add 0s; return the non-0, modified as need be */
3843     if (ISZERO(lhs)) {
3844       Int adjust;                       /* work */
3845       Int lexp=lhs->exponent;           /* save in case LHS==RES */
3846       bits=lhs->bits;                   /* .. */
3847       residue=0;                        /* clear accumulator */
3848       decCopyFit(res, rhs, set, &residue, status); /* copy (as needed) */
3849       res->bits^=negate;                /* flip if rhs was negated */
3850       #if DECSUBSET
3851       if (set->extended) {              /* exponents on zeros count */
3852       #endif
3853         /* exponent will be the lower of the two */
3854         adjust=lexp-res->exponent;      /* adjustment needed [if -ve] */
3855         if (ISZERO(res)) {              /* both 0: special IEEE 854 rules */
3856           if (adjust<0) res->exponent=lexp;  /* set exponent */
3857           /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0 */
3858           if (diffsign) {
3859             if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3860              else res->bits=DECNEG;     /* preserve 0 sign */
3861             }
3862           }
3863          else { /* non-0 res */
3864           if (adjust<0) {     /* 0-padding needed */
3865             if ((res->digits-adjust)>set->digits) {
3866               adjust=res->digits-set->digits;     /* to fit exactly */
3867               *status|=DEC_Rounded;               /* [but exact] */
3868               }
3869             res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3870             res->exponent+=adjust;                /* set the exponent. */
3871             }
3872           } /* non-0 res */
3873       #if DECSUBSET
3874         } /* extended */
3875       #endif
3876       decFinish(res, set, &residue, status);      /* clean and finalize */
3877       break;}
3878
3879     if (ISZERO(rhs)) {                  /* [lhs is non-zero] */
3880       Int adjust;                       /* work */
3881       Int rexp=rhs->exponent;           /* save in case RHS==RES */
3882       bits=rhs->bits;                   /* be clean */
3883       residue=0;                        /* clear accumulator */
3884       decCopyFit(res, lhs, set, &residue, status); /* copy (as needed) */
3885       #if DECSUBSET
3886       if (set->extended) {              /* exponents on zeros count */
3887       #endif
3888         /* exponent will be the lower of the two */
3889         /* [0-0 case handled above] */
3890         adjust=rexp-res->exponent;      /* adjustment needed [if -ve] */
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       #if DECSUBSET
3900         } /* extended */
3901       #endif
3902       decFinish(res, set, &residue, status);      /* clean and finalize */
3903       break;}
3904
3905     /* [NB: both fastpath and mainpath code below assume these cases */
3906     /* (notably 0-0) have already been handled] */
3907
3908     /* calculate the padding needed to align the operands */
3909     padding=rhs->exponent-lhs->exponent;
3910
3911     /* Fastpath cases where the numbers are aligned and normal, the RHS */
3912     /* is all in one unit, no operand rounding is needed, and no carry, */
3913     /* lengthening, or borrow is needed */
3914     if (padding==0
3915         && rhs->digits<=DECDPUN
3916         && rhs->exponent>=set->emin     /* [some normals drop through] */
3917         && rhs->exponent<=set->emax-set->digits+1 /* [could clamp] */
3918         && rhs->digits<=reqdigits
3919         && lhs->digits<=reqdigits) {
3920       Int partial=*lhs->lsu;
3921       if (!diffsign) {                  /* adding */
3922         partial+=*rhs->lsu;
3923         if ((partial<=DECDPUNMAX)       /* result fits in unit */
3924          && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change */
3925              partial<(Int)powers[lhs->digits])) { /* .. */
3926           if (res!=lhs) decNumberCopy(res, lhs);  /* not in place */
3927           *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS] */
3928           break;
3929           }
3930         /* else drop out for careful add */
3931         }
3932        else {                           /* signs differ */
3933         partial-=*rhs->lsu;
3934         if (partial>0) { /* no borrow needed, and non-0 result */
3935           if (res!=lhs) decNumberCopy(res, lhs);  /* not in place */
3936           *res->lsu=(Unit)partial;
3937           /* this could have reduced digits [but result>0] */
3938           res->digits=decGetDigits(res->lsu, D2U(res->digits));
3939           break;
3940           }
3941         /* else drop out for careful subtract */
3942         }
3943       }
3944
3945     /* Now align (pad) the lhs or rhs so they can be added or */
3946     /* subtracted, as necessary.  If one number is much larger than */
3947     /* the other (that is, if in plain form there is a least one */
3948     /* digit between the lowest digit of one and the highest of the */
3949     /* other) padding with up to DIGITS-1 trailing zeros may be */
3950     /* needed; then apply rounding (as exotic rounding modes may be */
3951     /* affected by the residue). */
3952     rhsshift=0;               /* rhs shift to left (padding) in Units */
3953     bits=lhs->bits;           /* assume sign is that of LHS */
3954     mult=1;                   /* likely multiplier */
3955
3956     /* [if padding==0 the operands are aligned; no padding is needed] */
3957     if (padding!=0) {
3958       /* some padding needed; always pad the RHS, as any required */
3959       /* padding can then be effected by a simple combination of */
3960       /* shifts and a multiply */
3961       Flag swapped=0;
3962       if (padding<0) {                  /* LHS needs the padding */
3963         const decNumber *t;
3964         padding=-padding;               /* will be +ve */
3965         bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS */
3966         t=lhs; lhs=rhs; rhs=t;
3967         swapped=1;
3968         }
3969
3970       /* If, after pad, rhs would be longer than lhs by digits+1 or */
3971       /* more then lhs cannot affect the answer, except as a residue, */
3972       /* so only need to pad up to a length of DIGITS+1. */
3973       if (rhs->digits+padding > lhs->digits+reqdigits+1) {
3974         /* The RHS is sufficient */
3975         /* for residue use the relative sign indication... */
3976         Int shift=reqdigits-rhs->digits;     /* left shift needed */
3977         residue=1;                           /* residue for rounding */
3978         if (diffsign) residue=-residue;      /* signs differ */
3979         /* copy, shortening if necessary */
3980         decCopyFit(res, rhs, set, &residue, status);
3981         /* if it was already shorter, then need to pad with zeros */
3982         if (shift>0) {
3983           res->digits=decShiftToMost(res->lsu, res->digits, shift);
3984           res->exponent-=shift;              /* adjust the exponent. */
3985           }
3986         /* flip the result sign if unswapped and rhs was negated */
3987         if (!swapped) res->bits^=negate;
3988         decFinish(res, set, &residue, status);    /* done */
3989         break;}
3990
3991       /* LHS digits may affect result */
3992       rhsshift=D2U(padding+1)-1;        /* this much by Unit shift .. */
3993       mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication */
3994       } /* padding needed */
3995
3996     if (diffsign) mult=-mult;           /* signs differ */
3997
3998     /* determine the longer operand */
3999     maxdigits=rhs->digits+padding;      /* virtual length of RHS */
4000     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4001
4002     /* Decide on the result buffer to use; if possible place directly */
4003     /* into result. */
4004     acc=res->lsu;                       /* assume add direct to result */
4005     /* If destructive overlap, or the number is too long, or a carry or */
4006     /* borrow to DIGITS+1 might be possible, a buffer must be used. */
4007     /* [Might be worth more sophisticated tests when maxdigits==reqdigits] */
4008     if ((maxdigits>=reqdigits)          /* is, or could be, too large */
4009      || (res==rhs && rhsshift>0)) {     /* destructive overlap */
4010       /* buffer needed, choose it; units for maxdigits digits will be */
4011       /* needed, +1 Unit for carry or borrow */
4012       Int need=D2U(maxdigits)+1;
4013       acc=accbuff;                      /* assume use local buffer */
4014       if (need*sizeof(Unit)>sizeof(accbuff)) {
4015         /* printf("malloc add %ld %ld\n", need, sizeof(accbuff)); */
4016         allocacc=(Unit *)malloc(need*sizeof(Unit));
4017         if (allocacc==NULL) {           /* hopeless -- abandon */
4018           *status|=DEC_Insufficient_storage;
4019           break;}
4020         acc=allocacc;
4021         }
4022       }
4023
4024     res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite.. */
4025     res->exponent=lhs->exponent;        /* .. operands (even if aliased) */
4026
4027     #if DECTRACE
4028       decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4029       decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4030       printf("  :h: %ld %ld\n", rhsshift, mult);
4031     #endif
4032
4033     /* add [A+B*m] or subtract [A+B*(-m)] */
4034     res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4035                               rhs->lsu, D2U(rhs->digits),
4036                               rhsshift, acc, mult)
4037                *DECDPUN;           /* [units -> digits] */
4038     if (res->digits<0) {           /* borrowed... */
4039       res->digits=-res->digits;
4040       res->bits^=DECNEG;           /* flip the sign */
4041       }
4042     #if DECTRACE
4043       decDumpAr('+', acc, D2U(res->digits));
4044     #endif
4045
4046     /* If a buffer was used the result must be copied back, possibly */
4047     /* shortening.  (If no buffer was used then the result must have */
4048     /* fit, so can't need rounding and residue must be 0.) */
4049     residue=0;                     /* clear accumulator */
4050     if (acc!=res->lsu) {
4051       #if DECSUBSET
4052       if (set->extended) {         /* round from first significant digit */
4053       #endif
4054         /* remove leading zeros that were added due to rounding up to */
4055         /* integral Units -- before the test for rounding. */
4056         if (res->digits>reqdigits)
4057           res->digits=decGetDigits(acc, D2U(res->digits));
4058         decSetCoeff(res, set, acc, res->digits, &residue, status);
4059       #if DECSUBSET
4060         }
4061        else { /* subset arithmetic rounds from original significant digit */
4062         /* May have an underestimate.  This only occurs when both */
4063         /* numbers fit in DECDPUN digits and are padding with a */
4064         /* negative multiple (-10, -100...) and the top digit(s) become */
4065         /* 0.  (This only matters when using X3.274 rules where the */
4066         /* leading zero could be included in the rounding.) */
4067         if (res->digits<maxdigits) {
4068           *(acc+D2U(res->digits))=0; /* ensure leading 0 is there */
4069           res->digits=maxdigits;
4070           }
4071          else {
4072           /* remove leading zeros that added due to rounding up to */
4073           /* integral Units (but only those in excess of the original */
4074           /* maxdigits length, unless extended) before test for rounding. */
4075           if (res->digits>reqdigits) {
4076             res->digits=decGetDigits(acc, D2U(res->digits));
4077             if (res->digits<maxdigits) res->digits=maxdigits;
4078             }
4079           }
4080         decSetCoeff(res, set, acc, res->digits, &residue, status);
4081         /* Now apply rounding if needed before removing leading zeros. */
4082         /* This is safe because subnormals are not a possibility */
4083         if (residue!=0) {
4084           decApplyRound(res, set, residue, status);
4085           residue=0;                 /* did what needed to be done */
4086           }
4087         } /* subset */
4088       #endif
4089       } /* used buffer */
4090
4091     /* strip leading zeros [these were left on in case of subset subtract] */
4092     res->digits=decGetDigits(res->lsu, D2U(res->digits));
4093
4094     /* apply checks and rounding */
4095     decFinish(res, set, &residue, status);
4096
4097     /* "When the sum of two operands with opposite signs is exactly */
4098     /* zero, the sign of that sum shall be '+' in all rounding modes */
4099     /* except round toward -Infinity, in which mode that sign shall be */
4100     /* '-'."  [Subset zeros also never have '-', set by decFinish.] */
4101     if (ISZERO(res) && diffsign
4102      #if DECSUBSET
4103      && set->extended
4104      #endif
4105      && (*status&DEC_Inexact)==0) {
4106       if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign - */
4107                                   else res->bits&=~DECNEG;  /* sign + */
4108       }
4109     } while(0);                              /* end protected */
4110
4111   if (allocacc!=NULL) free(allocacc);        /* drop any storage used */
4112   #if DECSUBSET
4113   if (allocrhs!=NULL) free(allocrhs);        /* .. */
4114   if (alloclhs!=NULL) free(alloclhs);        /* .. */
4115   #endif
4116   return res;
4117   } /* decAddOp */
4118
4119 /* ------------------------------------------------------------------ */
4120 /* decDivideOp -- division operation                                  */
4121 /*                                                                    */
4122 /*  This routine performs the calculations for all four division      */
4123 /*  operators (divide, divideInteger, remainder, remainderNear).      */
4124 /*                                                                    */
4125 /*  C=A op B                                                          */
4126 /*                                                                    */
4127 /*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4128 /*   lhs is A                                                         */
4129 /*   rhs is B                                                         */
4130 /*   set is the context                                               */
4131 /*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4132 /*   status is the usual accumulator                                  */
4133 /*                                                                    */
4134 /* C must have space for set->digits digits.                          */
4135 /*                                                                    */
4136 /* ------------------------------------------------------------------ */
4137 /*   The underlying algorithm of this routine is the same as in the   */
4138 /*   1981 S/370 implementation, that is, non-restoring long division  */
4139 /*   with bi-unit (rather than bi-digit) estimation for each unit     */
4140 /*   multiplier.  In this pseudocode overview, complications for the  */
4141 /*   Remainder operators and division residues for exact rounding are */
4142 /*   omitted for clarity.                                             */
4143 /*                                                                    */
4144 /*     Prepare operands and handle special values                     */
4145 /*     Test for x/0 and then 0/x                                      */
4146 /*     Exp =Exp1 - Exp2                                               */
4147 /*     Exp =Exp +len(var1) -len(var2)                                 */
4148 /*     Sign=Sign1 * Sign2                                             */
4149 /*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4150 /*     Pad Var2 to same length as Var1                                */
4151 /*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4152 /*     have=0                                                         */
4153 /*     Do until (have=digits+1 OR residue=0)                          */
4154 /*       if exp<0 then if integer divide/residue then leave           */
4155 /*       this_unit=0                                                  */
4156 /*       Do forever                                                   */
4157 /*          compare numbers                                           */
4158 /*          if <0 then leave inner_loop                               */
4159 /*          if =0 then (* quick exit without subtract *) do           */
4160 /*             this_unit=this_unit+1; output this_unit                */
4161 /*             leave outer_loop; end                                  */
4162 /*          Compare lengths of numbers (mantissae):                   */
4163 /*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4164 /*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4165 /*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4166 /*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4167 /*          if mult=0 then mult=1                                     */
4168 /*          this_unit=this_unit+mult                                  */
4169 /*          subtract                                                  */
4170 /*          end inner_loop                                            */
4171 /*        if have\=0 | this_unit\=0 then do                           */
4172 /*          output this_unit                                          */
4173 /*          have=have+1; end                                          */
4174 /*        var2=var2/10                                                */
4175 /*        exp=exp-1                                                   */
4176 /*        end outer_loop                                              */
4177 /*     exp=exp+1   -- set the proper exponent                         */
4178 /*     if have=0 then generate answer=0                               */
4179 /*     Return (Result is defined by Var1)                             */
4180 /*                                                                    */
4181 /* ------------------------------------------------------------------ */
4182 /* Two working buffers are needed during the division; one (digits+   */
4183 /* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4184 /* long subtractions.  These are acc and var1 respectively.           */
4185 /* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4186 /* The static buffers may be larger than might be expected to allow   */
4187 /* for calls from higher-level funtions (notable exp).                */
4188 /* ------------------------------------------------------------------ */
4189 static decNumber * decDivideOp(decNumber *res,
4190                                const decNumber *lhs, const decNumber *rhs,
4191                                decContext *set, Flag op, uInt *status) {
4192   #if DECSUBSET
4193   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
4194   decNumber *allocrhs=NULL;        /* .., rhs */
4195   #endif
4196   Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer */
4197   Unit  *acc=accbuff;              /* -> accumulator array for result */
4198   Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated */
4199   Unit  *accnext;                  /* -> where next digit will go */
4200   Int   acclength;                 /* length of acc needed [Units] */
4201   Int   accunits;                  /* count of units accumulated */
4202   Int   accdigits;                 /* count of digits accumulated */
4203
4204   Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)*sizeof(Unit)]; /* buffer for var1 */
4205   Unit  *var1=varbuff;             /* -> var1 array for long subtraction */
4206   Unit  *varalloc=NULL;            /* -> allocated buffer, iff used */
4207   Unit  *msu1;                     /* -> msu of var1 */
4208
4209   const Unit *var2;                /* -> var2 array */
4210   const Unit *msu2;                /* -> msu of var2 */
4211   Int   msu2plus;                  /* msu2 plus one [does not vary] */
4212   eInt  msu2pair;                  /* msu2 pair plus one [does not vary] */
4213
4214   Int   var1units, var2units;      /* actual lengths */
4215   Int   var2ulen;                  /* logical length (units) */
4216   Int   var1initpad=0;             /* var1 initial padding (digits) */
4217   Int   maxdigits;                 /* longest LHS or required acc length */
4218   Int   mult;                      /* multiplier for subtraction */
4219   Unit  thisunit;                  /* current unit being accumulated */
4220   Int   residue;                   /* for rounding */
4221   Int   reqdigits=set->digits;     /* requested DIGITS */
4222   Int   exponent;                  /* working exponent */
4223   Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded */
4224   uByte bits;                      /* working sign */
4225   Unit  *target;                   /* work */
4226   const Unit *source;              /* .. */
4227   uInt  const *pow;                /* .. */
4228   Int   shift, cut;                /* .. */
4229   #if DECSUBSET
4230   Int   dropped;                   /* work */
4231   #endif
4232
4233   #if DECCHECK
4234   if (decCheckOperands(res, lhs, rhs, set)) return res;
4235   #endif
4236
4237   do {                             /* protect allocated storage */
4238     #if DECSUBSET
4239     if (!set->extended) {
4240       /* reduce operands and set lostDigits status, as needed */
4241       if (lhs->digits>reqdigits) {
4242         alloclhs=decRoundOperand(lhs, set, status);
4243         if (alloclhs==NULL) break;
4244         lhs=alloclhs;
4245         }
4246       if (rhs->digits>reqdigits) {
4247         allocrhs=decRoundOperand(rhs, set, status);
4248         if (allocrhs==NULL) break;
4249         rhs=allocrhs;
4250         }
4251       }
4252     #endif
4253     /* [following code does not require input rounding] */
4254
4255     bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions */
4256
4257     /* handle infinities and NaNs */
4258     if (SPECIALARGS) {                  /* a special bit set */
4259       if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4260         decNaNs(res, lhs, rhs, set, status);
4261         break;
4262         }
4263       /* one or two infinities */
4264       if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite */
4265         if (decNumberIsInfinite(rhs) || /* two infinities are invalid .. */
4266             op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity */
4267           *status|=DEC_Invalid_operation;
4268           break;
4269           }
4270         /* [Note that infinity/0 raises no exceptions] */
4271         decNumberZero(res);
4272         res->bits=bits|DECINF;          /* set +/- infinity */
4273         break;
4274         }
4275        else {                           /* RHS (divisor) is infinite */
4276         residue=0;
4277         if (op&(REMAINDER|REMNEAR)) {
4278           /* result is [finished clone of] lhs */
4279           decCopyFit(res, lhs, set, &residue, status);
4280           }
4281          else {  /* a division */
4282           decNumberZero(res);
4283           res->bits=bits;               /* set +/- zero */
4284           /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result */
4285           /* is a 0 with infinitely negative exponent, clamped to minimum */
4286           if (op&DIVIDE) {
4287             res->exponent=set->emin-set->digits+1;
4288             *status|=DEC_Clamped;
4289             }
4290           }
4291         decFinish(res, set, &residue, status);
4292         break;
4293         }
4294       }
4295
4296     /* handle 0 rhs (x/0) */
4297     if (ISZERO(rhs)) {                  /* x/0 is always exceptional */
4298       if (ISZERO(lhs)) {
4299         decNumberZero(res);             /* [after lhs test] */
4300         *status|=DEC_Division_undefined;/* 0/0 will become NaN */
4301         }
4302        else {
4303         decNumberZero(res);
4304         if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4305          else {
4306           *status|=DEC_Division_by_zero; /* x/0 */
4307           res->bits=bits|DECINF;         /* .. is +/- Infinity */
4308           }
4309         }
4310       break;}
4311
4312     /* handle 0 lhs (0/x) */
4313     if (ISZERO(lhs)) {                  /* 0/x [x!=0] */
4314       #if DECSUBSET
4315       if (!set->extended) decNumberZero(res);
4316        else {
4317       #endif
4318         if (op&DIVIDE) {
4319           residue=0;
4320           exponent=lhs->exponent-rhs->exponent; /* ideal exponent */
4321           decNumberCopy(res, lhs);      /* [zeros always fit] */
4322           res->bits=bits;               /* sign as computed */
4323           res->exponent=exponent;       /* exponent, too */
4324           decFinalize(res, set, &residue, status);   /* check exponent */
4325           }
4326          else if (op&DIVIDEINT) {
4327           decNumberZero(res);           /* integer 0 */
4328           res->bits=bits;               /* sign as computed */
4329           }
4330          else {                         /* a remainder */
4331           exponent=rhs->exponent;       /* [save in case overwrite] */
4332           decNumberCopy(res, lhs);      /* [zeros always fit] */
4333           if (exponent<res->exponent) res->exponent=exponent; /* use lower */
4334           }
4335       #if DECSUBSET
4336         }
4337       #endif
4338       break;}
4339
4340     /* Precalculate exponent.  This starts off adjusted (and hence fits */
4341     /* in 31 bits) and becomes the usual unadjusted exponent as the */
4342     /* division proceeds.  The order of evaluation is important, here, */
4343     /* to avoid wrap. */
4344     exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4345
4346     /* If the working exponent is -ve, then some quick exits are */
4347     /* possible because the quotient is known to be <1 */
4348     /* [for REMNEAR, it needs to be < -1, as -0.5 could need work] */
4349     if (exponent<0 && !(op==DIVIDE)) {
4350       if (op&DIVIDEINT) {
4351         decNumberZero(res);                  /* integer part is 0 */
4352         #if DECSUBSET
4353         if (set->extended)
4354         #endif
4355           res->bits=bits;                    /* set +/- zero */
4356         break;}
4357       /* fastpath remainders so long as the lhs has the smaller */
4358       /* (or equal) exponent */
4359       if (lhs->exponent<=rhs->exponent) {
4360         if (op&REMAINDER || exponent<-1) {
4361           /* It is REMAINDER or safe REMNEAR; result is [finished */
4362           /* clone of] lhs  (r = x - 0*y) */
4363           residue=0;
4364           decCopyFit(res, lhs, set, &residue, status);
4365           decFinish(res, set, &residue, status);
4366           break;
4367           }
4368         /* [unsafe REMNEAR drops through] */
4369         }
4370       } /* fastpaths */
4371
4372     /* Long (slow) division is needed; roll up the sleeves... */
4373
4374     /* The accumulator will hold the quotient of the division. */
4375     /* If it needs to be too long for stack storage, then allocate. */
4376     acclength=D2U(reqdigits+DECDPUN);   /* in Units */
4377     if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4378       /* printf("malloc dvacc %ld units\n", acclength); */
4379       allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4380       if (allocacc==NULL) {             /* hopeless -- abandon */
4381         *status|=DEC_Insufficient_storage;
4382         break;}
4383       acc=allocacc;                     /* use the allocated space */
4384       }
4385
4386     /* var1 is the padded LHS ready for subtractions. */
4387     /* If it needs to be too long for stack storage, then allocate. */
4388     /* The maximum units needed for var1 (long subtraction) is: */
4389     /* Enough for */
4390     /*     (rhs->digits+reqdigits-1) -- to allow full slide to right */
4391     /* or  (lhs->digits)             -- to allow for long lhs */
4392     /* whichever is larger */
4393     /*   +1                -- for rounding of slide to right */
4394     /*   +1                -- for leading 0s */
4395     /*   +1                -- for pre-adjust if a remainder or DIVIDEINT */
4396     /* [Note: unused units do not participate in decUnitAddSub data] */
4397     maxdigits=rhs->digits+reqdigits-1;
4398     if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4399     var1units=D2U(maxdigits)+2;
4400     /* allocate a guard unit above msu1 for REMAINDERNEAR */
4401     if (!(op&DIVIDE)) var1units++;
4402     if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4403       /* printf("malloc dvvar %ld units\n", var1units+1); */
4404       varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4405       if (varalloc==NULL) {             /* hopeless -- abandon */
4406         *status|=DEC_Insufficient_storage;
4407         break;}
4408       var1=varalloc;                    /* use the allocated space */
4409       }
4410
4411     /* Extend the lhs and rhs to full long subtraction length.  The lhs */
4412     /* is truly extended into the var1 buffer, with 0 padding, so a */
4413     /* subtract in place is always possible.  The rhs (var2) has */
4414     /* virtual padding (implemented by decUnitAddSub). */
4415     /* One guard unit was allocated above msu1 for rem=rem+rem in */
4416     /* REMAINDERNEAR. */
4417     msu1=var1+var1units-1;              /* msu of var1 */
4418     source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array */
4419     for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4420     for (; target>=var1; target--) *target=0;
4421
4422     /* rhs (var2) is left-aligned with var1 at the start */
4423     var2ulen=var1units;                 /* rhs logical length (units) */
4424     var2units=D2U(rhs->digits);         /* rhs actual length (units) */
4425     var2=rhs->lsu;                      /* -> rhs array */
4426     msu2=var2+var2units-1;              /* -> msu of var2 [never changes] */
4427     /* now set up the variables which will be used for estimating the */
4428     /* multiplication factor.  If these variables are not exact, add */
4429     /* 1 to make sure that the multiplier is never overestimated. */
4430     msu2plus=*msu2;                     /* it's value .. */
4431     if (var2units>1) msu2plus++;        /* .. +1 if any more */
4432     msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair .. */
4433     if (var2units>1) {                  /* .. [else treat 2nd as 0] */
4434       msu2pair+=*(msu2-1);              /* .. */
4435       if (var2units>2) msu2pair++;      /* .. +1 if any more */
4436       }
4437
4438     /* The calculation is working in units, which may have leading zeros, */
4439     /* but the exponent was calculated on the assumption that they are */
4440     /* both left-aligned.  Adjust the exponent to compensate: add the */
4441     /* number of leading zeros in var1 msu and subtract those in var2 msu. */
4442     /* [This is actually done by counting the digits and negating, as */
4443     /* lead1=DECDPUN-digits1, and similarly for lead2.] */
4444     for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4445     for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4446
4447     /* Now, if doing an integer divide or remainder, ensure that */
4448     /* the result will be Unit-aligned.  To do this, shift the var1 */
4449     /* accumulator towards least if need be.  (It's much easier to */
4450     /* do this now than to reassemble the residue afterwards, if */
4451     /* doing a remainder.)  Also ensure the exponent is not negative. */
4452     if (!(op&DIVIDE)) {
4453       Unit *u;                          /* work */
4454       /* save the initial 'false' padding of var1, in digits */
4455       var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4456       /* Determine the shift to do. */
4457       if (exponent<0) cut=-exponent;
4458        else cut=DECDPUN-exponent%DECDPUN;
4459       decShiftToLeast(var1, var1units, cut);
4460       exponent+=cut;                    /* maintain numerical value */
4461       var1initpad-=cut;                 /* .. and reduce padding */
4462       /* clean any most-significant units which were just emptied */
4463       for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4464       } /* align */
4465      else { /* is DIVIDE */
4466       maxexponent=lhs->exponent-rhs->exponent;    /* save */
4467       /* optimization: if the first iteration will just produce 0, */
4468       /* preadjust to skip it [valid for DIVIDE only] */
4469       if (*msu1<*msu2) {
4470         var2ulen--;                     /* shift down */
4471         exponent-=DECDPUN;              /* update the exponent */
4472         }
4473       }
4474
4475     /* ---- start the long-division loops ------------------------------ */
4476     accunits=0;                         /* no units accumulated yet */
4477     accdigits=0;                        /* .. or digits */
4478     accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1] */
4479     for (;;) {                          /* outer forever loop */
4480       thisunit=0;                       /* current unit assumed 0 */
4481       /* find the next unit */
4482       for (;;) {                        /* inner forever loop */
4483         /* strip leading zero units [from either pre-adjust or from */
4484         /* subtract last time around].  Leave at least one unit. */
4485         for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4486
4487         if (var1units<var2ulen) break;       /* var1 too low for subtract */
4488         if (var1units==var2ulen) {           /* unit-by-unit compare needed */
4489           /* compare the two numbers, from msu */
4490           const Unit *pv1, *pv2;
4491           Unit v2;                           /* units to compare */
4492           pv2=msu2;                          /* -> msu */
4493           for (pv1=msu1; ; pv1--, pv2--) {
4494             /* v1=*pv1 -- always OK */
4495             v2=0;                            /* assume in padding */
4496             if (pv2>=var2) v2=*pv2;          /* in range */
4497             if (*pv1!=v2) break;             /* no longer the same */
4498             if (pv1==var1) break;            /* done; leave pv1 as is */
4499             }
4500           /* here when all inspected or a difference seen */
4501           if (*pv1<v2) break;                /* var1 too low to subtract */
4502           if (*pv1==v2) {                    /* var1 == var2 */
4503             /* reach here if var1 and var2 are identical; subtraction */
4504             /* would increase digit by one, and the residue will be 0 so */
4505             /* the calculation is done; leave the loop with residue=0. */
4506             thisunit++;                      /* as though subtracted */
4507             *var1=0;                         /* set var1 to 0 */
4508             var1units=1;                     /* .. */
4509             break;  /* from inner */
4510             } /* var1 == var2 */
4511           /* *pv1>v2.  Prepare for real subtraction; the lengths are equal */
4512           /* Estimate the multiplier (there's always a msu1-1)... */
4513           /* Bring in two units of var2 to provide a good estimate. */
4514           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4515           } /* lengths the same */
4516          else { /* var1units > var2ulen, so subtraction is safe */
4517           /* The var2 msu is one unit towards the lsu of the var1 msu, */
4518           /* so only one unit for var2 can be used. */
4519           mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4520           }
4521         if (mult==0) mult=1;                 /* must always be at least 1 */
4522         /* subtraction needed; var1 is > var2 */
4523         thisunit=(Unit)(thisunit+mult);      /* accumulate */
4524         /* subtract var1-var2, into var1; only the overlap needs */
4525         /* processing, as this is an in-place calculation */
4526         shift=var2ulen-var2units;
4527         #if DECTRACE
4528           decDumpAr('1', &var1[shift], var1units-shift);
4529           decDumpAr('2', var2, var2units);
4530           printf("m=%ld\n", -mult);
4531         #endif
4532         decUnitAddSub(&var1[shift], var1units-shift,
4533                       var2, var2units, 0,
4534                       &var1[shift], -mult);
4535         #if DECTRACE
4536           decDumpAr('#', &var1[shift], var1units-shift);
4537         #endif
4538         /* var1 now probably has leading zeros; these are removed at the */
4539         /* top of the inner loop. */
4540         } /* inner loop */
4541
4542       /* The next unit has been calculated in full; unless it's a */
4543       /* leading zero, add to acc */
4544       if (accunits!=0 || thisunit!=0) {      /* is first or non-zero */
4545         *accnext=thisunit;                   /* store in accumulator */
4546         /* account exactly for the new digits */
4547         if (accunits==0) {
4548           accdigits++;                       /* at least one */
4549           for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4550           }
4551          else accdigits+=DECDPUN;
4552         accunits++;                          /* update count */
4553         accnext--;                           /* ready for next */
4554         if (accdigits>reqdigits) break;      /* have enough digits */
4555         }
4556
4557       /* if the residue is zero, the operation is done (unless divide */
4558       /* or divideInteger and still not enough digits yet) */
4559       if (*var1==0 && var1units==1) {        /* residue is 0 */
4560         if (op&(REMAINDER|REMNEAR)) break;
4561         if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4562         /* [drop through if divideInteger] */
4563         }
4564       /* also done enough if calculating remainder or integer */
4565       /* divide and just did the last ('units') unit */
4566       if (exponent==0 && !(op&DIVIDE)) break;
4567
4568       /* to get here, var1 is less than var2, so divide var2 by the per- */
4569       /* Unit power of ten and go for the next digit */
4570       var2ulen--;                            /* shift down */
4571       exponent-=DECDPUN;                     /* update the exponent */
4572       } /* outer loop */
4573
4574     /* ---- division is complete --------------------------------------- */
4575     /* here: acc      has at least reqdigits+1 of good results (or fewer */
4576     /*                if early stop), starting at accnext+1 (its lsu) */
4577     /*       var1     has any residue at the stopping point */
4578     /*       accunits is the number of digits collected in acc */
4579     if (accunits==0) {             /* acc is 0 */
4580       accunits=1;                  /* show have a unit .. */
4581       accdigits=1;                 /* .. */
4582       *accnext=0;                  /* .. whose value is 0 */
4583       }
4584      else accnext++;               /* back to last placed */
4585     /* accnext now -> lowest unit of result */
4586
4587     residue=0;                     /* assume no residue */
4588     if (op&DIVIDE) {
4589       /* record the presence of any residue, for rounding */
4590       if (*var1!=0 || var1units>1) residue=1;
4591        else { /* no residue */
4592         /* Had an exact division; clean up spurious trailing 0s. */
4593         /* There will be at most DECDPUN-1, from the final multiply, */
4594         /* and then only if the result is non-0 (and even) and the */
4595         /* exponent is 'loose'. */
4596         #if DECDPUN>1
4597         Unit lsu=*accnext;
4598         if (!(lsu&0x01) && (lsu!=0)) {
4599           /* count the trailing zeros */
4600           Int drop=0;
4601           for (;; drop++) {    /* [will terminate because lsu!=0] */
4602             if (exponent>=maxexponent) break;     /* don't chop real 0s */
4603             #if DECDPUN<=4
4604               if ((lsu-QUOT10(lsu, drop+1)
4605                   *powers[drop+1])!=0) break;     /* found non-0 digit */
4606             #else
4607               if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit */
4608             #endif
4609             exponent++;
4610             }
4611           if (drop>0) {
4612             accunits=decShiftToLeast(accnext, accunits, drop);
4613             accdigits=decGetDigits(accnext, accunits);
4614             accunits=D2U(accdigits);
4615             /* [exponent was adjusted in the loop] */
4616             }
4617           } /* neither odd nor 0 */
4618         #endif
4619         } /* exact divide */
4620       } /* divide */
4621      else /* op!=DIVIDE */ {
4622       /* check for coefficient overflow */
4623       if (accdigits+exponent>reqdigits) {
4624         *status|=DEC_Division_impossible;
4625         break;
4626         }
4627       if (op & (REMAINDER|REMNEAR)) {
4628         /* [Here, the exponent will be 0, because var1 was adjusted */
4629         /* appropriately.] */
4630         Int postshift;                       /* work */
4631         Flag wasodd=0;                       /* integer was odd */
4632         Unit *quotlsu;                       /* for save */
4633         Int  quotdigits;                     /* .. */
4634
4635         bits=lhs->bits;                      /* remainder sign is always as lhs */
4636
4637         /* Fastpath when residue is truly 0 is worthwhile [and */
4638         /* simplifies the code below] */
4639         if (*var1==0 && var1units==1) {      /* residue is 0 */
4640           Int exp=lhs->exponent;             /* save min(exponents) */
4641           if (rhs->exponent<exp) exp=rhs->exponent;
4642           decNumberZero(res);                /* 0 coefficient */
4643           #if DECSUBSET
4644           if (set->extended)
4645           #endif
4646           res->exponent=exp;                 /* .. with proper exponent */
4647           res->bits=(uByte)(bits&DECNEG);          /* [cleaned] */
4648           decFinish(res, set, &residue, status);   /* might clamp */
4649           break;
4650           }
4651         /* note if the quotient was odd */
4652         if (*accnext & 0x01) wasodd=1;       /* acc is odd */
4653         quotlsu=accnext;                     /* save in case need to reinspect */
4654         quotdigits=accdigits;                /* .. */
4655
4656         /* treat the residue, in var1, as the value to return, via acc */
4657         /* calculate the unused zero digits.  This is the smaller of: */
4658         /*   var1 initial padding (saved above) */
4659         /*   var2 residual padding, which happens to be given by: */
4660         postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4661         /* [the 'exponent' term accounts for the shifts during divide] */
4662         if (var1initpad<postshift) postshift=var1initpad;
4663
4664         /* shift var1 the requested amount, and adjust its digits */
4665         var1units=decShiftToLeast(var1, var1units, postshift);
4666         accnext=var1;
4667         accdigits=decGetDigits(var1, var1units);
4668         accunits=D2U(accdigits);
4669
4670         exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs */
4671         if (rhs->exponent<exponent) exponent=rhs->exponent;
4672
4673         /* Now correct the result if doing remainderNear; if it */
4674         /* (looking just at coefficients) is > rhs/2, or == rhs/2 and */
4675         /* the integer was odd then the result should be rem-rhs. */
4676         if (op&REMNEAR) {
4677           Int compare, tarunits;        /* work */
4678           Unit *up;                     /* .. */
4679           /* calculate remainder*2 into the var1 buffer (which has */
4680           /* 'headroom' of an extra unit and hence enough space) */
4681           /* [a dedicated 'double' loop would be faster, here] */
4682           tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4683                                  0, accnext, 1);
4684           /* decDumpAr('r', accnext, tarunits); */
4685
4686           /* Here, accnext (var1) holds tarunits Units with twice the */
4687           /* remainder's coefficient, which must now be compared to the */
4688           /* RHS.  The remainder's exponent may be smaller than the RHS's. */
4689           compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4690                                  rhs->exponent-exponent);
4691           if (compare==BADINT) {             /* deep trouble */
4692             *status|=DEC_Insufficient_storage;
4693             break;}
4694
4695           /* now restore the remainder by dividing by two; the lsu */
4696           /* is known to be even. */
4697           for (up=accnext; up<accnext+tarunits; up++) {
4698             Int half;              /* half to add to lower unit */
4699             half=*up & 0x01;
4700             *up/=2;                /* [shift] */
4701             if (!half) continue;
4702             *(up-1)+=(DECDPUNMAX+1)/2;
4703             }
4704           /* [accunits still describes the original remainder length] */
4705
4706           if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed */
4707             Int exp, expunits, exprem;       /* work */
4708             /* This is effectively causing round-up of the quotient, */
4709             /* so if it was the rare case where it was full and all */
4710             /* nines, it would overflow and hence division-impossible */
4711             /* should be raised */
4712             Flag allnines=0;                 /* 1 if quotient all nines */
4713             if (quotdigits==reqdigits) {     /* could be borderline */
4714               for (up=quotlsu; ; up++) {
4715                 if (quotdigits>DECDPUN) {
4716                   if (*up!=DECDPUNMAX) break;/* non-nines */
4717                   }
4718                  else {                      /* this is the last Unit */
4719                   if (*up==powers[quotdigits]-1) allnines=1;
4720                   break;
4721                   }
4722                 quotdigits-=DECDPUN;         /* checked those digits */
4723                 } /* up */
4724               } /* borderline check */
4725             if (allnines) {
4726               *status|=DEC_Division_impossible;
4727               break;}
4728
4729             /* rem-rhs is needed; the sign will invert.  Again, var1 */
4730             /* can safely be used for the working Units array. */
4731             exp=rhs->exponent-exponent;      /* RHS padding needed */
4732             /* Calculate units and remainder from exponent. */
4733             expunits=exp/DECDPUN;
4734             exprem=exp%DECDPUN;
4735             /* subtract [A+B*(-m)]; the result will always be negative */
4736             accunits=-decUnitAddSub(accnext, accunits,
4737                                     rhs->lsu, D2U(rhs->digits),
4738                                     expunits, accnext, -(Int)powers[exprem]);
4739             accdigits=decGetDigits(accnext, accunits); /* count digits exactly */
4740             accunits=D2U(accdigits);    /* and recalculate the units for copy */
4741             /* [exponent is as for original remainder] */
4742             bits^=DECNEG;               /* flip the sign */
4743             }
4744           } /* REMNEAR */
4745         } /* REMAINDER or REMNEAR */
4746       } /* not DIVIDE */
4747
4748     /* Set exponent and bits */
4749     res->exponent=exponent;
4750     res->bits=(uByte)(bits&DECNEG);          /* [cleaned] */
4751
4752     /* Now the coefficient. */
4753     decSetCoeff(res, set, accnext, accdigits, &residue, status);
4754
4755     decFinish(res, set, &residue, status);   /* final cleanup */
4756
4757     #if DECSUBSET
4758     /* If a divide then strip trailing zeros if subset [after round] */
4759     if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, &dropped);
4760     #endif
4761     } while(0);                              /* end protected */
4762
4763   if (varalloc!=NULL) free(varalloc);   /* drop any storage used */
4764   if (allocacc!=NULL) free(allocacc);   /* .. */
4765   #if DECSUBSET
4766   if (allocrhs!=NULL) free(allocrhs);   /* .. */
4767   if (alloclhs!=NULL) free(alloclhs);   /* .. */
4768   #endif
4769   return res;
4770   } /* decDivideOp */
4771
4772 /* ------------------------------------------------------------------ */
4773 /* decMultiplyOp -- multiplication operation                          */
4774 /*                                                                    */
4775 /*  This routine performs the multiplication C=A x B.                 */
4776 /*                                                                    */
4777 /*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4778 /*   lhs is A                                                         */
4779 /*   rhs is B                                                         */
4780 /*   set is the context                                               */
4781 /*   status is the usual accumulator                                  */
4782 /*                                                                    */
4783 /* C must have space for set->digits digits.                          */
4784 /*                                                                    */
4785 /* ------------------------------------------------------------------ */
4786 /* 'Classic' multiplication is used rather than Karatsuba, as the     */
4787 /* latter would give only a minor improvement for the short numbers   */
4788 /* expected to be handled most (and uses much more memory).           */
4789 /*                                                                    */
4790 /* There are two major paths here: the general-purpose ('old code')   */
4791 /* path which handles all DECDPUN values, and a fastpath version      */
4792 /* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4793 /* than two calls to decUnitAddSub would be made.                     */
4794 /*                                                                    */
4795 /* The fastpath version lumps units together into 8-digit or 9-digit  */
4796 /* chunks, and also uses a lazy carry strategy to minimise expensive  */
4797 /* 64-bit divisions.  The chunks are then broken apart again into     */
4798 /* units for continuing processing.  Despite this overhead, the       */
4799 /* fastpath can speed up some 16-digit operations by 10x (and much    */
4800 /* more for higher-precision calculations).                           */
4801 /*                                                                    */
4802 /* A buffer always has to be used for the accumulator; in the         */
4803 /* fastpath, buffers are also always needed for the chunked copies of */
4804 /* of the operand coefficients.                                       */
4805 /* Static buffers are larger than needed just for multiply, to allow  */
4806 /* for calls from other operations (notably exp).                     */
4807 /* ------------------------------------------------------------------ */
4808 #define FASTMUL (DECUSE64 && DECDPUN<5)
4809 static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4810                                  const decNumber *rhs, decContext *set,
4811                                  uInt *status) {
4812   Int    accunits;                 /* Units of accumulator in use */
4813   Int    exponent;                 /* work */
4814   Int    residue=0;                /* rounding residue */
4815   uByte  bits;                     /* result sign */
4816   Unit  *acc;                      /* -> accumulator Unit array */
4817   Int    needbytes;                /* size calculator */
4818   void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated */
4819   Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0, */
4820                                    /* *4 for calls from other operations) */
4821   const Unit *mer, *mermsup;       /* work */
4822   Int   madlength;                 /* Units in multiplicand */
4823   Int   shift;                     /* Units to shift multiplicand by */
4824
4825   #if FASTMUL
4826     /* if DECDPUN is 1 or 3 work in base 10**9, otherwise */
4827     /* (DECDPUN is 2 or 4) then work in base 10**8 */
4828     #if DECDPUN & 1                /* odd */
4829       #define FASTBASE 1000000000  /* base */
4830       #define FASTDIGS          9  /* digits in base */
4831       #define FASTLAZY         18  /* carry resolution point [1->18] */
4832     #else
4833       #define FASTBASE  100000000
4834       #define FASTDIGS          8
4835       #define FASTLAZY       1844  /* carry resolution point [1->1844] */
4836     #endif
4837     /* three buffers are used, two for chunked copies of the operands */
4838     /* (base 10**8 or base 10**9) and one base 2**64 accumulator with */
4839     /* lazy carry evaluation */
4840     uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4841     uInt  *zlhi=zlhibuff;                 /* -> lhs array */
4842     uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated */
4843     uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0) */
4844     uInt  *zrhi=zrhibuff;                 /* -> rhs array */
4845     uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated */
4846     uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0) */
4847     /* [allocacc is shared for both paths, as only one will run] */
4848     uLong *zacc=zaccbuff;          /* -> accumulator array for exact result */
4849     #if DECDPUN==1
4850     Int    zoff;                   /* accumulator offset */
4851     #endif
4852     uInt  *lip, *rip;              /* item pointers */
4853     uInt  *lmsi, *rmsi;            /* most significant items */
4854     Int    ilhs, irhs, iacc;       /* item counts in the arrays */
4855     Int    lazy;                   /* lazy carry counter */
4856     uLong  lcarry;                 /* uLong carry */
4857     uInt   carry;                  /* carry (NB not uLong) */
4858     Int    count;                  /* work */
4859     const  Unit *cup;              /* .. */
4860     Unit  *up;                     /* .. */
4861     uLong *lp;                     /* .. */
4862     Int    p;                      /* .. */
4863   #endif
4864
4865   #if DECSUBSET
4866     decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated */
4867     decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated */
4868   #endif
4869
4870   #if DECCHECK
4871   if (decCheckOperands(res, lhs, rhs, set)) return res;
4872   #endif
4873
4874   /* precalculate result sign */
4875   bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4876
4877   /* handle infinities and NaNs */
4878   if (SPECIALARGS) {               /* a special bit set */
4879     if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs */
4880       decNaNs(res, lhs, rhs, set, status);
4881       return res;}
4882     /* one or two infinities; Infinity * 0 is invalid */
4883     if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4884       ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4885       *status|=DEC_Invalid_operation;
4886       return res;}
4887     decNumberZero(res);
4888     res->bits=bits|DECINF;         /* infinity */
4889     return res;}
4890
4891   /* For best speed, as in DMSRCN [the original Rexx numerics */
4892   /* module], use the shorter number as the multiplier (rhs) and */
4893   /* the longer as the multiplicand (lhs) to minimise the number of */
4894   /* adds (partial products) */
4895   if (lhs->digits<rhs->digits) {   /* swap... */
4896     const decNumber *hold=lhs;
4897     lhs=rhs;
4898     rhs=hold;
4899     }
4900
4901   do {                             /* protect allocated storage */
4902     #if DECSUBSET
4903     if (!set->extended) {
4904       /* reduce operands and set lostDigits status, as needed */
4905       if (lhs->digits>set->digits) {
4906         alloclhs=decRoundOperand(lhs, set, status);
4907         if (alloclhs==NULL) break;
4908         lhs=alloclhs;
4909         }
4910       if (rhs->digits>set->digits) {
4911         allocrhs=decRoundOperand(rhs, set, status);
4912         if (allocrhs==NULL) break;
4913         rhs=allocrhs;
4914         }
4915       }
4916     #endif
4917     /* [following code does not require input rounding] */
4918
4919     #if FASTMUL                    /* fastpath can be used */
4920     /* use the fast path if there are enough digits in the shorter */
4921     /* operand to make the setup and takedown worthwhile */
4922     #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls */
4923     if (rhs->digits>NEEDTWO) {     /* use fastpath... */
4924       /* calculate the number of elements in each array */
4925       ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling] */
4926       irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* .. */
4927       iacc=ilhs+irhs;
4928
4929       /* allocate buffers if required, as usual */
4930       needbytes=ilhs*sizeof(uInt);
4931       if (needbytes>(Int)sizeof(zlhibuff)) {
4932         alloclhi=(uInt *)malloc(needbytes);
4933         zlhi=alloclhi;}
4934       needbytes=irhs*sizeof(uInt);
4935       if (needbytes>(Int)sizeof(zrhibuff)) {
4936         allocrhi=(uInt *)malloc(needbytes);
4937         zrhi=allocrhi;}
4938
4939       /* Allocating the accumulator space needs a special case when */
4940       /* DECDPUN=1 because when converting the accumulator to Units */
4941       /* after the multiplication each 8-byte item becomes 9 1-byte */
4942       /* units.  Therefore iacc extra bytes are needed at the front */
4943       /* (rounded up to a multiple of 8 bytes), and the uLong */
4944       /* accumulator starts offset the appropriate number of units */
4945       /* to the right to avoid overwrite during the unchunking. */
4946       needbytes=iacc*sizeof(uLong);
4947       #if DECDPUN==1
4948       zoff=(iacc+7)/8;        /* items to offset by */
4949       needbytes+=zoff*8;
4950       #endif
4951       if (needbytes>(Int)sizeof(zaccbuff)) {
4952         allocacc=(uLong *)malloc(needbytes);
4953         zacc=(uLong *)allocacc;}
4954       if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4955         *status|=DEC_Insufficient_storage;
4956         break;}
4957
4958       acc=(Unit *)zacc;       /* -> target Unit array */
4959       #if DECDPUN==1
4960       zacc+=zoff;             /* start uLong accumulator to right */
4961       #endif
4962
4963       /* assemble the chunked copies of the left and right sides */
4964       for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4965         for (p=0, *lip=0; p<FASTDIGS && count>0;
4966              p+=DECDPUN, cup++, count-=DECDPUN)
4967           *lip+=*cup*powers[p];
4968       lmsi=lip-1;     /* save -> msi */
4969       for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
4970         for (p=0, *rip=0; p<FASTDIGS && count>0;
4971              p+=DECDPUN, cup++, count-=DECDPUN)
4972           *rip+=*cup*powers[p];
4973       rmsi=rip-1;     /* save -> msi */
4974
4975       /* zero the accumulator */
4976       for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
4977
4978       /* Start the multiplication */
4979       /* Resolving carries can dominate the cost of accumulating the */
4980       /* partial products, so this is only done when necessary. */
4981       /* Each uLong item in the accumulator can hold values up to */
4982       /* 2**64-1, and each partial product can be as large as */
4983       /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to */
4984       /* itself 18.4 times in a uLong without overflowing, so during */
4985       /* the main calculation resolution is carried out every 18th */
4986       /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the */
4987       /* partial products can be added to themselves 1844.6 times in */
4988       /* a uLong without overflowing, so intermediate carry */
4989       /* resolution occurs only every 14752 digits.  Hence for common */
4990       /* short numbers usually only the one final carry resolution */
4991       /* occurs. */
4992       /* (The count is set via FASTLAZY to simplify experiments to */
4993       /* measure the value of this approach: a 35% improvement on a */
4994       /* [34x34] multiply.) */
4995       lazy=FASTLAZY;                         /* carry delay count */
4996       for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs */
4997         lp=zacc+(rip-zrhi);                  /* where to add the lhs */
4998         for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs */
4999           *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line] */
5000           } /* lip loop */
5001         lazy--;
5002         if (lazy>0 && rip!=rmsi) continue;
5003         lazy=FASTLAZY;                       /* reset delay count */
5004         /* spin up the accumulator resolving overflows */
5005         for (lp=zacc; lp<zacc+iacc; lp++) {
5006           if (*lp<FASTBASE) continue;        /* it fits */
5007           lcarry=*lp/FASTBASE;               /* top part [slow divide] */
5008           /* lcarry can exceed 2**32-1, so check again; this check */
5009           /* and occasional extra divide (slow) is well worth it, as */
5010           /* it allows FASTLAZY to be increased to 18 rather than 4 */
5011           /* in the FASTDIGS=9 case */
5012           if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual] */
5013            else { /* two-place carry [fairly rare] */
5014             uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part */
5015             *(lp+2)+=carry2;                        /* add to item+2 */
5016             *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow] */
5017             carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline] */
5018             }
5019           *(lp+1)+=carry;                    /* add to item above [inline] */
5020           *lp-=((uLong)FASTBASE*carry);      /* [inline] */
5021           } /* carry resolution */
5022         } /* rip loop */
5023
5024       /* The multiplication is complete; time to convert back into */
5025       /* units.  This can be done in-place in the accumulator and in */
5026       /* 32-bit operations, because carries were resolved after the */
5027       /* final add.  This needs N-1 divides and multiplies for */
5028       /* each item in the accumulator (which will become up to N */
5029       /* units, where 2<=N<=9). */
5030       for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5031         uInt item=(uInt)*lp;                 /* decapitate to uInt */
5032         for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5033           uInt part=item/(DECDPUNMAX+1);
5034           *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5035           item=part;
5036           } /* p */
5037         *up=(Unit)item; up++;                /* [final needs no division] */
5038         } /* lp */
5039       accunits=up-acc;                       /* count of units */
5040       }
5041      else { /* here to use units directly, without chunking ['old code'] */
5042     #endif
5043
5044       /* if accumulator will be too long for local storage, then allocate */
5045       acc=accbuff;                 /* -> assume buffer for accumulator */
5046       needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5047       if (needbytes>(Int)sizeof(accbuff)) {
5048         allocacc=(Unit *)malloc(needbytes);
5049         if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5050         acc=(Unit *)allocacc;                /* use the allocated space */
5051         }
5052
5053       /* Now the main long multiplication loop */
5054       /* Unlike the equivalent in the IBM Java implementation, there */
5055       /* is no advantage in calculating from msu to lsu.  So, do it */
5056       /* by the book, as it were. */
5057       /* Each iteration calculates ACC=ACC+MULTAND*MULT */
5058       accunits=1;                  /* accumulator starts at '0' */
5059       *acc=0;                      /* .. (lsu=0) */
5060       shift=0;                     /* no multiplicand shift at first */
5061       madlength=D2U(lhs->digits);  /* this won't change */
5062       mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier */
5063
5064       for (mer=rhs->lsu; mer<mermsup; mer++) {
5065         /* Here, *mer is the next Unit in the multiplier to use */
5066         /* If non-zero [optimization] add it... */
5067         if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5068                                             lhs->lsu, madlength, 0,
5069                                             &acc[shift], *mer)
5070                                             + shift;
5071          else { /* extend acc with a 0; it will be used shortly */
5072           *(acc+accunits)=0;       /* [this avoids length of <=0 later] */
5073           accunits++;
5074           }
5075         /* multiply multiplicand by 10**DECDPUN for next Unit to left */
5076         shift++;                   /* add this for 'logical length' */
5077         } /* n */
5078     #if FASTMUL
5079       } /* unchunked units */
5080     #endif
5081     /* common end-path */
5082     #if DECTRACE
5083       decDumpAr('*', acc, accunits);         /* Show exact result */
5084     #endif
5085
5086     /* acc now contains the exact result of the multiplication, */
5087     /* possibly with a leading zero unit; build the decNumber from */
5088     /* it, noting if any residue */
5089     res->bits=bits;                          /* set sign */
5090     res->digits=decGetDigits(acc, accunits); /* count digits exactly */
5091
5092     /* There can be a 31-bit wrap in calculating the exponent. */
5093     /* This can only happen if both input exponents are negative and */
5094     /* both their magnitudes are large.  If there was a wrap, set a */
5095     /* safe very negative exponent, from which decFinalize() will */
5096     /* raise a hard underflow shortly. */
5097     exponent=lhs->exponent+rhs->exponent;    /* calculate exponent */
5098     if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5099       exponent=-2*DECNUMMAXE;                /* force underflow */
5100     res->exponent=exponent;                  /* OK to overwrite now */
5101
5102
5103     /* Set the coefficient.  If any rounding, residue records */
5104     decSetCoeff(res, set, acc, res->digits, &residue, status);
5105     decFinish(res, set, &residue, status);   /* final cleanup */
5106     } while(0);                         /* end protected */
5107
5108   if (allocacc!=NULL) free(allocacc);   /* drop any storage used */
5109   #if DECSUBSET
5110   if (allocrhs!=NULL) free(allocrhs);   /* .. */
5111   if (alloclhs!=NULL) free(alloclhs);   /* .. */
5112   #endif
5113   #if FASTMUL
5114   if (allocrhi!=NULL) free(allocrhi);   /* .. */
5115   if (alloclhi!=NULL) free(alloclhi);   /* .. */
5116   #endif
5117   return res;
5118   } /* decMultiplyOp */
5119
5120 /* ------------------------------------------------------------------ */
5121 /* decExpOp -- effect exponentiation                                  */
5122 /*                                                                    */
5123 /*   This computes C = exp(A)                                         */
5124 /*                                                                    */
5125 /*   res is C, the result.  C may be A                                */
5126 /*   rhs is A                                                         */
5127 /*   set is the context; note that rounding mode has no effect        */
5128 /*                                                                    */
5129 /* C must have space for set->digits digits. status is updated but    */
5130 /* not set.                                                           */
5131 /*                                                                    */
5132 /* Restrictions:                                                      */
5133 /*                                                                    */
5134 /*   digits, emax, and -emin in the context must be less than         */
5135 /*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5136 /*   bounds or a zero.  This is an internal routine, so these         */
5137 /*   restrictions are contractual and not enforced.                   */
5138 /*                                                                    */
5139 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5140 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5141 /* error in rare cases.                                               */
5142 /*                                                                    */
5143 /* Finite results will always be full precision and Inexact, except   */
5144 /* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5145 /* ------------------------------------------------------------------ */
5146 /* This approach used here is similar to the algorithm described in   */
5147 /*                                                                    */
5148 /*   Variable Precision Exponential Function, T. E. Hull and          */
5149 /*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5150 /*   pp79-91, ACM, June 1986.                                         */
5151 /*                                                                    */
5152 /* with the main difference being that the iterations in the series   */
5153 /* evaluation are terminated dynamically (which does not require the  */
5154 /* extra variable-precision variables which are expensive in this     */
5155 /* context).                                                          */
5156 /*                                                                    */
5157 /* The error analysis in Hull & Abrham's paper applies except for the */
5158 /* round-off error accumulation during the series evaluation.  This   */
5159 /* code does not precalculate the number of iterations and so cannot  */
5160 /* use Horner's scheme.  Instead, the accumulation is done at double- */
5161 /* precision, which ensures that the additions of the terms are exact */
5162 /* and do not accumulate round-off (and any round-off errors in the   */
5163 /* terms themselves move 'to the right' faster than they can          */
5164 /* accumulate).  This code also extends the calculation by allowing,  */
5165 /* in the spirit of other decNumber operators, the input to be more   */
5166 /* precise than the result (the precision used is based on the more   */
5167 /* precise of the input or requested result).                         */
5168 /*                                                                    */
5169 /* Implementation notes:                                              */
5170 /*                                                                    */
5171 /* 1. This is separated out as decExpOp so it can be called from      */
5172 /*    other Mathematical functions (notably Ln) with a wider range    */
5173 /*    than normal.  In particular, it can handle the slightly wider   */
5174 /*    (double) range needed by Ln (which has to be able to calculate  */
5175 /*    exp(-x) where x can be the tiniest number (Ntiny).              */
5176 /*                                                                    */
5177 /* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5178 /*    iterations by appoximately a third with additional (although    */
5179 /*    diminishing) returns as the range is reduced to even smaller    */
5180 /*    fractions.  However, h (the power of 10 used to correct the     */
5181 /*    result at the end, see below) must be kept <=8 as otherwise     */
5182 /*    the final result cannot be computed.  Hence the leverage is a   */
5183 /*    sliding value (8-h), where potentially the range is reduced     */
5184 /*    more for smaller values.                                        */
5185 /*                                                                    */
5186 /*    The leverage that can be applied in this way is severely        */
5187 /*    limited by the cost of the raise-to-the power at the end,       */
5188 /*    which dominates when the number of iterations is small (less    */
5189 /*    than ten) or when rhs is short.  As an example, the adjustment  */
5190 /*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5191 /*                                                                    */
5192 /* 3. The restrictions (especially precision) could be raised with    */
5193 /*    care, but the full decNumber range seems very hard within the   */
5194 /*    32-bit limits.                                                  */
5195 /*                                                                    */
5196 /* 4. The working precisions for the static buffers are twice the     */
5197 /*    obvious size to allow for calls from decNumberPower.            */
5198 /* ------------------------------------------------------------------ */
5199 decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5200                          decContext *set, uInt *status) {
5201   uInt ignore=0;                   /* working status */
5202   Int h;                           /* adjusted exponent for 0.xxxx */
5203   Int p;                           /* working precision */
5204   Int residue;                     /* rounding residue */
5205   uInt needbytes;                  /* for space calculations */
5206   const decNumber *x=rhs;          /* (may point to safe copy later) */
5207   decContext aset, tset, dset;     /* working contexts */
5208   Int comp;                        /* work */
5209
5210   /* the argument is often copied to normalize it, so (unusually) it */
5211   /* is treated like other buffers, using DECBUFFER, +1 in case */
5212   /* DECBUFFER is 0 */
5213   decNumber bufr[D2N(DECBUFFER*2+1)];
5214   decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated */
5215
5216   /* the working precision will be no more than set->digits+8+1 */
5217   /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER */
5218   /* is 0 (and twice that for the accumulator) */
5219
5220   /* buffer for t, term (working precision plus) */
5221   decNumber buft[D2N(DECBUFFER*2+9+1)];
5222   decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated */
5223   decNumber *t=buft;               /* term */
5224   /* buffer for a, accumulator (working precision * 2), at least 9 */
5225   decNumber bufa[D2N(DECBUFFER*4+18+1)];
5226   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
5227   decNumber *a=bufa;               /* accumulator */
5228   /* decNumber for the divisor term; this needs at most 9 digits */
5229   /* and so can be fixed size [16 so can use standard context] */
5230   decNumber bufd[D2N(16)];
5231   decNumber *d=bufd;               /* divisor */
5232   decNumber numone;                /* constant 1 */
5233
5234   #if DECCHECK
5235   Int iterations=0;                /* for later sanity check */
5236   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5237   #endif
5238
5239   do {                                  /* protect allocated storage */
5240     if (SPECIALARG) {                   /* handle infinities and NaNs */
5241       if (decNumberIsInfinite(rhs)) {   /* an infinity */
5242         if (decNumberIsNegative(rhs))   /* -Infinity -> +0 */
5243           decNumberZero(res);
5244          else decNumberCopy(res, rhs);  /* +Infinity -> self */
5245         }
5246        else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5247       break;}
5248
5249     if (ISZERO(rhs)) {                  /* zeros -> exact 1 */
5250       decNumberZero(res);               /* make clean 1 */
5251       *res->lsu=1;                      /* .. */
5252       break;}                           /* [no status to set] */
5253
5254     /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path */
5255     /* positive and negative tiny cases which will result in inexact */
5256     /* 1.  This also allows the later add-accumulate to always be */
5257     /* exact (because its length will never be more than twice the */
5258     /* working precision). */
5259     /* The comparator (tiny) needs just one digit, so use the */
5260     /* decNumber d for it (reused as the divisor, etc., below); its */
5261     /* exponent is such that if x is positive it will have */
5262     /* set->digits-1 zeros between the decimal point and the digit, */
5263     /* which is 4, and if x is negative one more zero there as the */
5264     /* more precise result will be of the form 0.9999999 rather than */
5265     /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0 */
5266     /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than */
5267     /* this then the result will be 1.000000 */
5268     decNumberZero(d);                   /* clean */
5269     *d->lsu=4;                          /* set 4 .. */
5270     d->exponent=-set->digits;           /* * 10**(-d) */
5271     if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case */
5272     comp=decCompare(d, rhs, 1);         /* signless compare */
5273     if (comp==BADINT) {
5274       *status|=DEC_Insufficient_storage;
5275       break;}
5276     if (comp>=0) {                      /* rhs < d */
5277       Int shift=set->digits-1;
5278       decNumberZero(res);               /* set 1 */
5279       *res->lsu=1;                      /* .. */
5280       res->digits=decShiftToMost(res->lsu, 1, shift);
5281       res->exponent=-shift;                  /* make 1.0000... */
5282       *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly */
5283       break;} /* tiny */
5284
5285     /* set up the context to be used for calculating a, as this is */
5286     /* used on both paths below */
5287     decContextDefault(&aset, DEC_INIT_DECIMAL64);
5288     /* accumulator bounds are as requested (could underflow) */
5289     aset.emax=set->emax;                /* usual bounds */
5290     aset.emin=set->emin;                /* .. */
5291     aset.clamp=0;                       /* and no concrete format */
5292
5293     /* calculate the adjusted (Hull & Abrham) exponent (where the */
5294     /* decimal point is just to the left of the coefficient msd) */
5295     h=rhs->exponent+rhs->digits;
5296     /* if h>8 then 10**h cannot be calculated safely; however, when */
5297     /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at */
5298     /* least 6.59E+4342944, so (due to the restriction on Emax/Emin) */
5299     /* overflow (or underflow to 0) is guaranteed -- so this case can */
5300     /* be handled by simply forcing the appropriate excess */
5301     if (h>8) {                          /* overflow/underflow */
5302       /* set up here so Power call below will over or underflow to */
5303       /* zero; set accumulator to either 2 or 0.02 */
5304       /* [stack buffer for a is always big enough for this] */
5305       decNumberZero(a);
5306       *a->lsu=2;                        /* not 1 but < exp(1) */
5307       if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02 */
5308       h=8;                              /* clamp so 10**h computable */
5309       p=9;                              /* set a working precision */
5310       }
5311      else {                             /* h<=8 */
5312       Int maxlever=(rhs->digits>8?1:0);
5313       /* [could/should increase this for precisions >40 or so, too] */
5314
5315       /* if h is 8, cannot normalize to a lower upper limit because */
5316       /* the final result will not be computable (see notes above), */
5317       /* but leverage can be applied whenever h is less than 8. */
5318       /* Apply as much as possible, up to a MAXLEVER digits, which */
5319       /* sets the tradeoff against the cost of the later a**(10**h). */
5320       /* As h is increased, the working precision below also */
5321       /* increases to compensate for the "constant digits at the */
5322       /* front" effect. */
5323       Int lever=MINI(8-h, maxlever);    /* leverage attainable */
5324       Int use=-rhs->digits-lever;       /* exponent to use for RHS */
5325       h+=lever;                         /* apply leverage selected */
5326       if (h<0) {                        /* clamp */
5327         use+=h;                         /* [may end up subnormal] */
5328         h=0;
5329         }
5330       /* Take a copy of RHS if it needs normalization (true whenever x>=1) */
5331       if (rhs->exponent!=use) {
5332         decNumber *newrhs=bufr;         /* assume will fit on stack */
5333         needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5334         if (needbytes>sizeof(bufr)) {   /* need malloc space */
5335           allocrhs=(decNumber *)malloc(needbytes);
5336           if (allocrhs==NULL) {         /* hopeless -- abandon */
5337             *status|=DEC_Insufficient_storage;
5338             break;}
5339           newrhs=allocrhs;              /* use the allocated space */
5340           }
5341         decNumberCopy(newrhs, rhs);     /* copy to safe space */
5342         newrhs->exponent=use;           /* normalize; now <1 */
5343         x=newrhs;                       /* ready for use */
5344         /* decNumberShow(x); */
5345         }
5346
5347       /* Now use the usual power series to evaluate exp(x).  The */
5348       /* series starts as 1 + x + x^2/2 ... so prime ready for the */
5349       /* third term by setting the term variable t=x, the accumulator */
5350       /* a=1, and the divisor d=2. */
5351
5352       /* First determine the working precision.  From Hull & Abrham */
5353       /* this is set->digits+h+2.  However, if x is 'over-precise' we */
5354       /* need to allow for all its digits to potentially participate */
5355       /* (consider an x where all the excess digits are 9s) so in */
5356       /* this case use x->digits+h+2 */
5357       p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8] */
5358
5359       /* a and t are variable precision, and depend on p, so space */
5360       /* must be allocated for them if necessary */
5361
5362       /* the accumulator needs to be able to hold 2p digits so that */
5363       /* the additions on the second and subsequent iterations are */
5364       /* sufficiently exact. */
5365       needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5366       if (needbytes>sizeof(bufa)) {     /* need malloc space */
5367         allocbufa=(decNumber *)malloc(needbytes);
5368         if (allocbufa==NULL) {          /* hopeless -- abandon */
5369           *status|=DEC_Insufficient_storage;
5370           break;}
5371         a=allocbufa;                    /* use the allocated space */
5372         }
5373       /* the term needs to be able to hold p digits (which is */
5374       /* guaranteed to be larger than x->digits, so the initial copy */
5375       /* is safe); it may also be used for the raise-to-power */
5376       /* calculation below, which needs an extra two digits */
5377       needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5378       if (needbytes>sizeof(buft)) {     /* need malloc space */
5379         allocbuft=(decNumber *)malloc(needbytes);
5380         if (allocbuft==NULL) {          /* hopeless -- abandon */
5381           *status|=DEC_Insufficient_storage;
5382           break;}
5383         t=allocbuft;                    /* use the allocated space */
5384         }
5385
5386       decNumberCopy(t, x);              /* term=x */
5387       decNumberZero(a); *a->lsu=1;      /* accumulator=1 */
5388       decNumberZero(d); *d->lsu=2;      /* divisor=2 */
5389       decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment */
5390
5391       /* set up the contexts for calculating a, t, and d */
5392       decContextDefault(&tset, DEC_INIT_DECIMAL64);
5393       dset=tset;
5394       /* accumulator bounds are set above, set precision now */
5395       aset.digits=p*2;                  /* double */
5396       /* term bounds avoid any underflow or overflow */
5397       tset.digits=p;
5398       tset.emin=DEC_MIN_EMIN;           /* [emax is plenty] */
5399       /* [dset.digits=16, etc., are sufficient] */
5400
5401       /* finally ready to roll */
5402       for (;;) {
5403         #if DECCHECK
5404         iterations++;
5405         #endif
5406         /* only the status from the accumulation is interesting */
5407         /* [but it should remain unchanged after first add] */
5408         decAddOp(a, a, t, &aset, 0, status);           /* a=a+t */
5409         decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x */
5410         decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d */
5411         /* the iteration ends when the term cannot affect the result, */
5412         /* if rounded to p digits, which is when its value is smaller */
5413         /* than the accumulator by p+1 digits.  There must also be */
5414         /* full precision in a. */
5415         if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5416             && (a->digits>=p)) break;
5417         decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1 */
5418         } /* iterate */
5419
5420       #if DECCHECK
5421       /* just a sanity check; comment out test to show always */
5422       if (iterations>p+3)
5423         printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5424                iterations, *status, p, x->digits);
5425       #endif
5426       } /* h<=8 */
5427
5428     /* apply postconditioning: a=a**(10**h) -- this is calculated */
5429     /* at a slightly higher precision than Hull & Abrham suggest */
5430     if (h>0) {
5431       Int seenbit=0;               /* set once a 1-bit is seen */
5432       Int i;                       /* counter */
5433       Int n=powers[h];             /* always positive */
5434       aset.digits=p+2;             /* sufficient precision */
5435       /* avoid the overhead and many extra digits of decNumberPower */
5436       /* as all that is needed is the short 'multipliers' loop; here */
5437       /* accumulate the answer into t */
5438       decNumberZero(t); *t->lsu=1; /* acc=1 */
5439       for (i=1;;i++){              /* for each bit [top bit ignored] */
5440         /* abandon if have had overflow or terminal underflow */
5441         if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting? */
5442           if (*status&DEC_Overflow || ISZERO(t)) break;}
5443         n=n<<1;                    /* move next bit to testable position */
5444         if (n<0) {                 /* top bit is set */
5445           seenbit=1;               /* OK, have a significant bit */
5446           decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x */
5447           }
5448         if (i==31) break;          /* that was the last bit */
5449         if (!seenbit) continue;    /* no need to square 1 */
5450         decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square] */
5451         } /*i*/ /* 32 bits */
5452       /* decNumberShow(t); */
5453       a=t;                         /* and carry on using t instead of a */
5454       }
5455
5456     /* Copy and round the result to res */
5457     residue=1;                          /* indicate dirt to right .. */
5458     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0 */
5459     aset.digits=set->digits;            /* [use default rounding] */
5460     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5461     decFinish(res, set, &residue, status);       /* cleanup/set flags */
5462     } while(0);                         /* end protected */
5463
5464   if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used */
5465   if (allocbufa!=NULL) free(allocbufa); /* .. */
5466   if (allocbuft!=NULL) free(allocbuft); /* .. */
5467   /* [status is handled by caller] */
5468   return res;
5469   } /* decExpOp */
5470
5471 /* ------------------------------------------------------------------ */
5472 /* Initial-estimate natural logarithm table                           */
5473 /*                                                                    */
5474 /*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5475 /*           The result is a 4-digit encode of the coefficient (c=the */
5476 /*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5477 /*           exponent (e=the bottom 2 bits encoding 0-3)              */
5478 /*                                                                    */
5479 /*           The resulting value is given by:                         */
5480 /*                                                                    */
5481 /*             v = -c * 10**(-e-3)                                    */
5482 /*                                                                    */
5483 /*           where e and c are extracted from entry k = LNnn[x-10]    */
5484 /*           where x is truncated (NB) into the range 10 through 99,  */
5485 /*           and then c = k>>2 and e = k&3.                           */
5486 /* ------------------------------------------------------------------ */
5487 const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5488   6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5489   5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5490  39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5491  29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5492  22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5493  15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5494  10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5495   5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5496  10130,  6046, 20055};
5497
5498 /* ------------------------------------------------------------------ */
5499 /* decLnOp -- effect natural logarithm                                */
5500 /*                                                                    */
5501 /*   This computes C = ln(A)                                          */
5502 /*                                                                    */
5503 /*   res is C, the result.  C may be A                                */
5504 /*   rhs is A                                                         */
5505 /*   set is the context; note that rounding mode has no effect        */
5506 /*                                                                    */
5507 /* C must have space for set->digits digits.                          */
5508 /*                                                                    */
5509 /* Notable cases:                                                     */
5510 /*   A<0 -> Invalid                                                   */
5511 /*   A=0 -> -Infinity (Exact)                                         */
5512 /*   A=+Infinity -> +Infinity (Exact)                                 */
5513 /*   A=1 exactly -> 0 (Exact)                                         */
5514 /*                                                                    */
5515 /* Restrictions (as for Exp):                                         */
5516 /*                                                                    */
5517 /*   digits, emax, and -emin in the context must be less than         */
5518 /*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5519 /*   bounds or a zero.  This is an internal routine, so these         */
5520 /*   restrictions are contractual and not enforced.                   */
5521 /*                                                                    */
5522 /* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5523 /* almost always be correctly rounded, but may be up to 1 ulp in      */
5524 /* error in rare cases.                                               */
5525 /* ------------------------------------------------------------------ */
5526 /* The result is calculated using Newton's method, with each          */
5527 /* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5528 /* Epperson 1989.                                                     */
5529 /*                                                                    */
5530 /* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5531 /* This has to be calculated at the sum of the precision of x and the */
5532 /* working precision.                                                 */
5533 /*                                                                    */
5534 /* Implementation notes:                                              */
5535 /*                                                                    */
5536 /* 1. This is separated out as decLnOp so it can be called from       */
5537 /*    other Mathematical functions (e.g., Log 10) with a wider range  */
5538 /*    than normal.  In particular, it can handle the slightly wider   */
5539 /*    (+9+2) range needed by a power function.                        */
5540 /*                                                                    */
5541 /* 2. The speed of this function is about 10x slower than exp, as     */
5542 /*    it typically needs 4-6 iterations for short numbers, and the    */
5543 /*    extra precision needed adds a squaring effect, twice.           */
5544 /*                                                                    */
5545 /* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5546 /*    as these are common requests.  ln(10) is used by log10(x).      */
5547 /*                                                                    */
5548 /* 4. An iteration might be saved by widening the LNnn table, and     */
5549 /*    would certainly save at least one if it were made ten times     */
5550 /*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5551 /*    However, for most practical evaluations, at least four or five  */
5552 /*    iterations will be neede -- so this would only speed up by      */
5553 /*    20-25% and that probably does not justify increasing the table  */
5554 /*    size.                                                           */
5555 /*                                                                    */
5556 /* 5. The static buffers are larger than might be expected to allow   */
5557 /*    for calls from decNumberPower.                                  */
5558 /* ------------------------------------------------------------------ */
5559 decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5560                     decContext *set, uInt *status) {
5561   uInt ignore=0;                   /* working status accumulator */
5562   uInt needbytes;                  /* for space calculations */
5563   Int residue;                     /* rounding residue */
5564   Int r;                           /* rhs=f*10**r [see below] */
5565   Int p;                           /* working precision */
5566   Int pp;                          /* precision for iteration */
5567   Int t;                           /* work */
5568
5569   /* buffers for a (accumulator, typically precision+2) and b */
5570   /* (adjustment calculator, same size) */
5571   decNumber bufa[D2N(DECBUFFER+12)];
5572   decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated */
5573   decNumber *a=bufa;               /* accumulator/work */
5574   decNumber bufb[D2N(DECBUFFER*2+2)];
5575   decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated */
5576   decNumber *b=bufb;               /* adjustment/work */
5577
5578   decNumber  numone;               /* constant 1 */
5579   decNumber  cmp;                  /* work */
5580   decContext aset, bset;           /* working contexts */
5581
5582   #if DECCHECK
5583   Int iterations=0;                /* for later sanity check */
5584   if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5585   #endif
5586
5587   do {                                  /* protect allocated storage */
5588     if (SPECIALARG) {                   /* handle infinities and NaNs */
5589       if (decNumberIsInfinite(rhs)) {   /* an infinity */
5590         if (decNumberIsNegative(rhs))   /* -Infinity -> error */
5591           *status|=DEC_Invalid_operation;
5592          else decNumberCopy(res, rhs);  /* +Infinity -> self */
5593         }
5594        else decNaNs(res, rhs, NULL, set, status); /* a NaN */
5595       break;}
5596
5597     if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity */
5598       decNumberZero(res);               /* make clean */
5599       res->bits=DECINF|DECNEG;          /* set - infinity */
5600       break;}                           /* [no status to set] */
5601
5602     /* Non-zero negatives are bad... */
5603     if (decNumberIsNegative(rhs)) {     /* -x -> error */
5604       *status|=DEC_Invalid_operation;
5605       break;}
5606
5607     /* Here, rhs is positive, finite, and in range */
5608
5609     /* lookaside fastpath code for ln(2) and ln(10) at common lengths */
5610     if (rhs->exponent==0 && set->digits<=40) {
5611       #if DECDPUN==1
5612       if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10) */
5613       #else
5614       if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10) */
5615       #endif
5616         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5617         #define LN10 "2.302585092994045684017991454684364207601"
5618         decNumberFromString(res, LN10, &aset);
5619         *status|=(DEC_Inexact | DEC_Rounded); /* is inexact */
5620         break;}
5621       if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2) */
5622         aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5623         #define LN2 "0.6931471805599453094172321214581765680755"
5624         decNumberFromString(res, LN2, &aset);
5625         *status|=(DEC_Inexact | DEC_Rounded);
5626         break;}
5627       } /* integer and short */
5628
5629     /* Determine the working precision.  This is normally the */
5630     /* requested precision + 2, with a minimum of 9.  However, if */
5631     /* the rhs is 'over-precise' then allow for all its digits to */
5632     /* potentially participate (consider an rhs where all the excess */
5633     /* digits are 9s) so in this case use rhs->digits+2. */
5634     p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5635
5636     /* Allocate space for the accumulator and the high-precision */
5637     /* adjustment calculator, if necessary.  The accumulator must */
5638     /* be able to hold p digits, and the adjustment up to */
5639     /* rhs->digits+p digits.  They are also made big enough for 16 */
5640     /* digits so that they can be used for calculating the initial */
5641     /* estimate. */
5642     needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5643     if (needbytes>sizeof(bufa)) {     /* need malloc space */
5644       allocbufa=(decNumber *)malloc(needbytes);
5645       if (allocbufa==NULL) {          /* hopeless -- abandon */
5646         *status|=DEC_Insufficient_storage;
5647         break;}
5648       a=allocbufa;                    /* use the allocated space */
5649       }
5650     pp=p+rhs->digits;
5651     needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5652     if (needbytes>sizeof(bufb)) {     /* need malloc space */
5653       allocbufb=(decNumber *)malloc(needbytes);
5654       if (allocbufb==NULL) {          /* hopeless -- abandon */
5655         *status|=DEC_Insufficient_storage;
5656         break;}
5657       b=allocbufb;                    /* use the allocated space */
5658       }
5659
5660     /* Prepare an initial estimate in acc. Calculate this by */
5661     /* considering the coefficient of x to be a normalized fraction, */
5662     /* f, with the decimal point at far left and multiplied by */
5663     /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and */
5664     /*   ln(x) = ln(f) + ln(10)*r */
5665     /* Get the initial estimate for ln(f) from a small lookup */
5666     /* table (see above) indexed by the first two digits of f, */
5667     /* truncated. */
5668
5669     decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended */
5670     r=rhs->exponent+rhs->digits;        /* 'normalised' exponent */
5671     decNumberFromInt32(a, r);           /* a=r */
5672     decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585) */
5673     b->exponent=-6;                     /*  .. */
5674     decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b */
5675     /* now get top two digits of rhs into b by simple truncate and */
5676     /* force to integer */
5677     residue=0;                          /* (no residue) */
5678     aset.digits=2; aset.round=DEC_ROUND_DOWN;
5679     decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten */
5680     b->exponent=0;                      /* make integer */
5681     t=decGetInt(b);                     /* [cannot fail] */
5682     if (t<10) t=X10(t);                 /* adjust single-digit b */
5683     t=LNnn[t-10];                       /* look up ln(b) */
5684     decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient */
5685     b->exponent=-(t&3)-3;               /* set exponent */
5686     b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve */
5687     aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore */
5688     decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b */
5689     /* the initial estimate is now in a, with up to 4 digits correct. */
5690     /* When rhs is at or near Nmax the estimate will be low, so we */
5691     /* will approach it from below, avoiding overflow when calling exp. */
5692
5693     decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment */
5694
5695     /* accumulator bounds are as requested (could underflow, but */
5696     /* cannot overflow) */
5697     aset.emax=set->emax;
5698     aset.emin=set->emin;
5699     aset.clamp=0;                       /* no concrete format */
5700     /* set up a context to be used for the multiply and subtract */
5701     bset=aset;
5702     bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the */
5703     bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation */
5704                                         /* [see decExpOp call below] */
5705     /* for each iteration double the number of digits to calculate, */
5706     /* up to a maximum of p */
5707     pp=9;                               /* initial precision */
5708     /* [initially 9 as then the sequence starts 7+2, 16+2, and */
5709     /* 34+2, which is ideal for standard-sized numbers] */
5710     aset.digits=pp;                     /* working context */
5711     bset.digits=pp+rhs->digits;         /* wider context */
5712     for (;;) {                          /* iterate */
5713       #if DECCHECK
5714       iterations++;
5715       if (iterations>24) break;         /* consider 9 * 2**24 */
5716       #endif
5717       /* calculate the adjustment (exp(-a)*x-1) into b.  This is a */
5718       /* catastrophic subtraction but it really is the difference */
5719       /* from 1 that is of interest. */
5720       /* Use the internal entry point to Exp as it allows the double */
5721       /* range for calculating exp(-a) when a is the tiniest subnormal. */
5722       a->bits^=DECNEG;                  /* make -a */
5723       decExpOp(b, a, &bset, &ignore);   /* b=exp(-a) */
5724       a->bits^=DECNEG;                  /* restore sign of a */
5725       /* now multiply by rhs and subtract 1, at the wider precision */
5726       decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs */
5727       decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1 */
5728
5729       /* the iteration ends when the adjustment cannot affect the */
5730       /* result by >=0.5 ulp (at the requested digits), which */
5731       /* is when its value is smaller than the accumulator by */
5732       /* set->digits+1 digits (or it is zero) -- this is a looser */
5733       /* requirement than for Exp because all that happens to the */
5734       /* accumulator after this is the final rounding (but note that */
5735       /* there must also be full precision in a, or a=0). */
5736
5737       if (decNumberIsZero(b) ||
5738           (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5739         if (a->digits==p) break;
5740         if (decNumberIsZero(a)) {
5741           decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ? */
5742           if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0 */
5743            else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact */
5744           break;
5745           }
5746         /* force padding if adjustment has gone to 0 before full length */
5747         if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5748         }
5749
5750       /* not done yet ... */
5751       decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate */
5752       if (pp==p) continue;                   /* precision is at maximum */
5753       /* lengthen the next calculation */
5754       pp=pp*2;                               /* double precision */
5755       if (pp>p) pp=p;                        /* clamp to maximum */
5756       aset.digits=pp;                        /* working context */
5757       bset.digits=pp+rhs->digits;            /* wider context */
5758       } /* Newton's iteration */
5759
5760     #if DECCHECK
5761     /* just a sanity check; remove the test to show always */
5762     if (iterations>24)
5763       printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5764             iterations, *status, p, rhs->digits);
5765     #endif
5766
5767     /* Copy and round the result to res */
5768     residue=1;                          /* indicate dirt to right */
5769     if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0 */
5770     aset.digits=set->digits;            /* [use default rounding] */
5771     decCopyFit(res, a, &aset, &residue, status); /* copy & shorten */
5772     decFinish(res, set, &residue, status);       /* cleanup/set flags */
5773     } while(0);                         /* end protected */
5774
5775   if (allocbufa!=NULL) free(allocbufa); /* drop any storage used */
5776   if (allocbufb!=NULL) free(allocbufb); /* .. */
5777   /* [status is handled by caller] */
5778   return res;
5779   } /* decLnOp */
5780
5781 /* ------------------------------------------------------------------ */
5782 /* decQuantizeOp  -- force exponent to requested value                */
5783 /*                                                                    */
5784 /*   This computes C = op(A, B), where op adjusts the coefficient     */
5785 /*   of C (by rounding or shifting) such that the exponent (-scale)   */
5786 /*   of C has the value B or matches the exponent of B.               */
5787 /*   The numerical value of C will equal A, except for the effects of */
5788 /*   any rounding that occurred.                                      */
5789 /*                                                                    */
5790 /*   res is C, the result.  C may be A or B                           */
5791 /*   lhs is A, the number to adjust                                   */
5792 /*   rhs is B, the requested exponent                                 */
5793 /*   set is the context                                               */
5794 /*   quant is 1 for quantize or 0 for rescale                         */
5795 /*   status is the status accumulator (this can be called without     */
5796 /*          risk of control loss)                                     */
5797 /*                                                                    */
5798 /* C must have space for set->digits digits.                          */
5799 /*                                                                    */
5800 /* Unless there is an error or the result is infinite, the exponent   */
5801 /* after the operation is guaranteed to be that requested.            */
5802 /* ------------------------------------------------------------------ */
5803 static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5804                                  const decNumber *rhs, decContext *set,
5805                                  Flag quant, uInt *status) {
5806   #if DECSUBSET
5807   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
5808   decNumber *allocrhs=NULL;        /* .., rhs */
5809   #endif
5810   const decNumber *inrhs=rhs;      /* save original rhs */
5811   Int   reqdigits=set->digits;     /* requested DIGITS */
5812   Int   reqexp;                    /* requested exponent [-scale] */
5813   Int   residue=0;                 /* rounding residue */
5814   Int   etiny=set->emin-(reqdigits-1);
5815
5816   #if DECCHECK
5817   if (decCheckOperands(res, lhs, rhs, set)) return res;
5818   #endif
5819
5820   do {                             /* protect allocated storage */
5821     #if DECSUBSET
5822     if (!set->extended) {
5823       /* reduce operands and set lostDigits status, as needed */
5824       if (lhs->digits>reqdigits) {
5825         alloclhs=decRoundOperand(lhs, set, status);
5826         if (alloclhs==NULL) break;
5827         lhs=alloclhs;
5828         }
5829       if (rhs->digits>reqdigits) { /* [this only checks lostDigits] */
5830         allocrhs=decRoundOperand(rhs, set, status);
5831         if (allocrhs==NULL) break;
5832         rhs=allocrhs;
5833         }
5834       }
5835     #endif
5836     /* [following code does not require input rounding] */
5837
5838     /* Handle special values */
5839     if (SPECIALARGS) {
5840       /* NaNs get usual processing */
5841       if (SPECIALARGS & (DECSNAN | DECNAN))
5842         decNaNs(res, lhs, rhs, set, status);
5843       /* one infinity but not both is bad */
5844       else if ((lhs->bits ^ rhs->bits) & DECINF)
5845         *status|=DEC_Invalid_operation;
5846       /* both infinity: return lhs */
5847       else decNumberCopy(res, lhs);          /* [nop if in place] */
5848       break;
5849       }
5850
5851     /* set requested exponent */
5852     if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents */
5853      else {                             /* rescale -- use value of rhs */
5854       /* Original rhs must be an integer that fits and is in range, */
5855       /* which could be from -1999999997 to +999999999, thanks to */
5856       /* subnormals */
5857       reqexp=decGetInt(inrhs);               /* [cannot fail] */
5858       }
5859
5860     #if DECSUBSET
5861     if (!set->extended) etiny=set->emin;     /* no subnormals */
5862     #endif
5863
5864     if (reqexp==BADINT                       /* bad (rescale only) or .. */
5865      || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or .. */
5866      || (reqexp<etiny)                       /* < lowest */
5867      || (reqexp>set->emax)) {                /* > emax */
5868       *status|=DEC_Invalid_operation;
5869       break;}
5870
5871     /* the RHS has been processed, so it can be overwritten now if necessary */
5872     if (ISZERO(lhs)) {                       /* zero coefficient unchanged */
5873       decNumberCopy(res, lhs);               /* [nop if in place] */
5874       res->exponent=reqexp;                  /* .. just set exponent */
5875       #if DECSUBSET
5876       if (!set->extended) res->bits=0;       /* subset specification; no -0 */
5877       #endif
5878       }
5879      else {                                  /* non-zero lhs */
5880       Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed */
5881       /* if adjusted coefficient will definitely not fit, give up now */
5882       if ((lhs->digits-adjust)>reqdigits) {
5883         *status|=DEC_Invalid_operation;
5884         break;
5885         }
5886
5887       if (adjust>0) {                        /* increasing exponent */
5888         /* this will decrease the length of the coefficient by adjust */
5889         /* digits, and must round as it does so */
5890         decContext workset;                  /* work */
5891         workset=*set;                        /* clone rounding, etc. */
5892         workset.digits=lhs->digits-adjust;   /* set requested length */
5893         /* [note that the latter can be <1, here] */
5894         decCopyFit(res, lhs, &workset, &residue, status); /* fit to result */
5895         decApplyRound(res, &workset, residue, status);    /* .. and round */
5896         residue=0;                                        /* [used] */
5897         /* If just rounded a 999s case, exponent will be off by one; */
5898         /* adjust back (after checking space), if so. */
5899         if (res->exponent>reqexp) {
5900           /* re-check needed, e.g., for quantize(0.9999, 0.001) under */
5901           /* set->digits==3 */
5902           if (res->digits==reqdigits) {      /* cannot shift by 1 */
5903             *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these] */
5904             *status|=DEC_Invalid_operation;
5905             break;
5906             }
5907           res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift */
5908           res->exponent--;                   /* (re)adjust the exponent. */
5909           }
5910         #if DECSUBSET
5911         if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0 */
5912         #endif
5913         } /* increase */
5914        else /* adjust<=0 */ {                /* decreasing or = exponent */
5915         /* this will increase the length of the coefficient by -adjust */
5916         /* digits, by adding zero or more trailing zeros; this is */
5917         /* already checked for fit, above */
5918         decNumberCopy(res, lhs);             /* [it will fit] */
5919         /* if padding needed (adjust<0), add it now... */
5920         if (adjust<0) {
5921           res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5922           res->exponent+=adjust;             /* adjust the exponent */
5923           }
5924         } /* decrease */
5925       } /* non-zero */
5926
5927     /* Check for overflow [do not use Finalize in this case, as an */
5928     /* overflow here is a "don't fit" situation] */
5929     if (res->exponent>set->emax-res->digits+1) {  /* too big */
5930       *status|=DEC_Invalid_operation;
5931       break;
5932       }
5933      else {
5934       decFinalize(res, set, &residue, status);    /* set subnormal flags */
5935       *status&=~DEC_Underflow;          /* suppress Underflow [754r] */
5936       }
5937     } while(0);                         /* end protected */
5938
5939   #if DECSUBSET
5940   if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used */
5941   if (alloclhs!=NULL) free(alloclhs);   /* .. */
5942   #endif
5943   return res;
5944   } /* decQuantizeOp */
5945
5946 /* ------------------------------------------------------------------ */
5947 /* decCompareOp -- compare, min, or max two Numbers                   */
5948 /*                                                                    */
5949 /*   This computes C = A ? B and carries out one of four operations:  */
5950 /*     COMPARE    -- returns the signum (as a number) giving the      */
5951 /*                   result of a comparison unless one or both        */
5952 /*                   operands is a NaN (in which case a NaN results)  */
5953 /*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5954 /*                   Invalid operation.                               */
5955 /*     COMPMAX    -- returns the larger of the operands, using the    */
5956 /*                   754r maxnum operation                            */
5957 /*     COMPMAXMAG -- ditto, comparing absolute values                 */
5958 /*     COMPMIN    -- the 754r minnum operation                        */
5959 /*     COMPMINMAG -- ditto, comparing absolute values                 */
5960 /*     COMTOTAL   -- returns the signum (as a number) giving the      */
5961 /*                   result of a comparison using 754r total ordering */
5962 /*                                                                    */
5963 /*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
5964 /*   lhs is A                                                         */
5965 /*   rhs is B                                                         */
5966 /*   set is the context                                               */
5967 /*   op  is the operation flag                                        */
5968 /*   status is the usual accumulator                                  */
5969 /*                                                                    */
5970 /* C must have space for one digit for COMPARE or set->digits for     */
5971 /* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
5972 /* ------------------------------------------------------------------ */
5973 /* The emphasis here is on speed for common cases, and avoiding       */
5974 /* coefficient comparison if possible.                                */
5975 /* ------------------------------------------------------------------ */
5976 decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
5977                          const decNumber *rhs, decContext *set,
5978                          Flag op, uInt *status) {
5979   #if DECSUBSET
5980   decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated */
5981   decNumber *allocrhs=NULL;        /* .., rhs */
5982   #endif
5983   Int   result=0;                  /* default result value */
5984   uByte merged;                    /* work */
5985
5986   #if DECCHECK
5987   if (decCheckOperands(res, lhs, rhs, set)) return res;
5988   #endif
5989
5990   do {                             /* protect allocated storage */
5991     #if DECSUBSET
5992     if (!set->extended) {
5993       /* reduce operands and set lostDigits status, as needed */
5994       if (lhs->digits>set->digits) {
5995         alloclhs=decRoundOperand(lhs, set, status);
5996         if (alloclhs==NULL) {result=BADINT; break;}
5997         lhs=alloclhs;
5998         }
5999       if (rhs->digits>set->digits) {
6000         allocrhs=decRoundOperand(rhs, set, status);
6001         if (allocrhs==NULL) {result=BADINT; break;}
6002         rhs=allocrhs;
6003         }
6004       }
6005     #endif
6006     /* [following code does not require input rounding] */
6007
6008     /* If total ordering then handle differing signs 'up front' */
6009     if (op==COMPTOTAL) {                /* total ordering */
6010       if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6011         result=-1;
6012         break;
6013         }
6014       if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6015         result=+1;
6016         break;
6017         }
6018       }
6019
6020     /* handle NaNs specially; let infinities drop through */
6021     /* This assumes sNaN (even just one) leads to NaN. */
6022     merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6023     if (merged) {                       /* a NaN bit set */
6024       if (op==COMPARE);                 /* result will be NaN */
6025        else if (op==COMPSIG)            /* treat qNaN as sNaN */
6026         *status|=DEC_Invalid_operation | DEC_sNaN;
6027        else if (op==COMPTOTAL) {        /* total ordering, always finite */
6028         /* signs are known to be the same; compute the ordering here */
6029         /* as if the signs are both positive, then invert for negatives */
6030         if (!decNumberIsNaN(lhs)) result=-1;
6031          else if (!decNumberIsNaN(rhs)) result=+1;
6032          /* here if both NaNs */
6033          else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6034          else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6035          else { /* both NaN or both sNaN */
6036           /* now it just depends on the payload */
6037           result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6038                                 rhs->lsu, D2U(rhs->digits), 0);
6039           /* [Error not possible, as these are 'aligned'] */
6040           } /* both same NaNs */
6041         if (decNumberIsNegative(lhs)) result=-result;
6042         break;
6043         } /* total order */
6044
6045        else if (merged & DECSNAN);           /* sNaN -> qNaN */
6046        else { /* here if MIN or MAX and one or two quiet NaNs */
6047         /* min or max -- 754r rules ignore single NaN */
6048         if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6049           /* just one NaN; force choice to be the non-NaN operand */
6050           op=COMPMAX;
6051           if (lhs->bits & DECNAN) result=-1; /* pick rhs */
6052                              else result=+1; /* pick lhs */
6053           break;
6054           }
6055         } /* max or min */
6056       op=COMPNAN;                            /* use special path */
6057       decNaNs(res, lhs, rhs, set, status);   /* propagate NaN */
6058       break;
6059       }
6060     /* have numbers */
6061     if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6062      else result=decCompare(lhs, rhs, 0);    /* sign matters */
6063     } while(0);                              /* end protected */
6064
6065   if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare */
6066    else {
6067     if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum */
6068       if (op==COMPTOTAL && result==0) {
6069         /* operands are numerically equal or same NaN (and same sign, */
6070         /* tested first); if identical, leave result 0 */
6071         if (lhs->exponent!=rhs->exponent) {
6072           if (lhs->exponent<rhs->exponent) result=-1;
6073            else result=+1;
6074           if (decNumberIsNegative(lhs)) result=-result;
6075           } /* lexp!=rexp */
6076         } /* total-order by exponent */
6077       decNumberZero(res);               /* [always a valid result] */
6078       if (result!=0) {                  /* must be -1 or +1 */
6079         *res->lsu=1;
6080         if (result<0) res->bits=DECNEG;
6081         }
6082       }
6083      else if (op==COMPNAN);             /* special, drop through */
6084      else {                             /* MAX or MIN, non-NaN result */
6085       Int residue=0;                    /* rounding accumulator */
6086       /* choose the operand for the result */
6087       const decNumber *choice;
6088       if (result==0) { /* operands are numerically equal */
6089         /* choose according to sign then exponent (see 754r) */
6090         uByte slhs=(lhs->bits & DECNEG);
6091         uByte srhs=(rhs->bits & DECNEG);
6092         #if DECSUBSET
6093         if (!set->extended) {           /* subset: force left-hand */
6094           op=COMPMAX;
6095           result=+1;
6096           }
6097         else
6098         #endif
6099         if (slhs!=srhs) {          /* signs differ */
6100           if (slhs) result=-1;     /* rhs is max */
6101                else result=+1;     /* lhs is max */
6102           }
6103          else if (slhs && srhs) {  /* both negative */
6104           if (lhs->exponent<rhs->exponent) result=+1;
6105                                       else result=-1;
6106           /* [if equal, use lhs, technically identical] */
6107           }
6108          else {                    /* both positive */
6109           if (lhs->exponent>rhs->exponent) result=+1;
6110                                       else result=-1;
6111           /* [ditto] */
6112           }
6113         } /* numerically equal */
6114       /* here result will be non-0; reverse if looking for MIN */
6115       if (op==COMPMIN || op==COMPMINMAG) result=-result;
6116       choice=(result>0 ? lhs : rhs);    /* choose */
6117       /* copy chosen to result, rounding if need be */
6118       decCopyFit(res, choice, set, &residue, status);
6119       decFinish(res, set, &residue, status);
6120       }
6121     }
6122   #if DECSUBSET
6123   if (allocrhs!=NULL) free(allocrhs);   /* free any storage used */
6124   if (alloclhs!=NULL) free(alloclhs);   /* .. */
6125   #endif
6126   return res;
6127   } /* decCompareOp */
6128
6129 /* ------------------------------------------------------------------ */
6130 /* decCompare -- compare two decNumbers by numerical value            */
6131 /*                                                                    */
6132 /*  This routine compares A ? B without altering them.                */
6133 /*                                                                    */
6134 /*  Arg1 is A, a decNumber which is not a NaN                         */
6135 /*  Arg2 is B, a decNumber which is not a NaN                         */
6136 /*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6137 /*                                                                    */
6138 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6139 /*  (the only possible failure is an allocation error)                */
6140 /* ------------------------------------------------------------------ */
6141 static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6142                       Flag abs) {
6143   Int   result;                    /* result value */
6144   Int   sigr;                      /* rhs signum */
6145   Int   compare;                   /* work */
6146
6147   result=1;                                  /* assume signum(lhs) */
6148   if (ISZERO(lhs)) result=0;
6149   if (abs) {
6150     if (ISZERO(rhs)) return result;          /* LHS wins or both 0 */
6151     /* RHS is non-zero */
6152     if (result==0) return -1;                /* LHS is 0; RHS wins */
6153     /* [here, both non-zero, result=1] */
6154     }
6155    else {                                    /* signs matter */
6156     if (result && decNumberIsNegative(lhs)) result=-1;
6157     sigr=1;                                  /* compute signum(rhs) */
6158     if (ISZERO(rhs)) sigr=0;
6159      else if (decNumberIsNegative(rhs)) sigr=-1;
6160     if (result > sigr) return +1;            /* L > R, return 1 */
6161     if (result < sigr) return -1;            /* L < R, return -1 */
6162     if (result==0) return 0;                   /* both 0 */
6163     }
6164
6165   /* signums are the same; both are non-zero */
6166   if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities */
6167     if (decNumberIsInfinite(rhs)) {
6168       if (decNumberIsInfinite(lhs)) result=0;/* both infinite */
6169        else result=-result;                  /* only rhs infinite */
6170       }
6171     return result;
6172     }
6173   /* must compare the coefficients, allowing for exponents */
6174   if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger */
6175     /* swap sides, and sign */
6176     const decNumber *temp=lhs;
6177     lhs=rhs;
6178     rhs=temp;
6179     result=-result;
6180     }
6181   compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6182                          rhs->lsu, D2U(rhs->digits),
6183                          rhs->exponent-lhs->exponent);
6184   if (compare!=BADINT) compare*=result;      /* comparison succeeded */
6185   return compare;
6186   } /* decCompare */
6187
6188 /* ------------------------------------------------------------------ */
6189 /* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6190 /*                                                                    */
6191 /*  This routine compares A ? B*10**E where A and B are unit arrays   */
6192 /*  A is a plain integer                                              */
6193 /*  B has an exponent of E (which must be non-negative)               */
6194 /*                                                                    */
6195 /*  Arg1 is A first Unit (lsu)                                        */
6196 /*  Arg2 is A length in Units                                         */
6197 /*  Arg3 is B first Unit (lsu)                                        */
6198 /*  Arg4 is B length in Units                                         */
6199 /*  Arg5 is E (0 if the units are aligned)                            */
6200 /*                                                                    */
6201 /*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6202 /*  (the only possible failure is an allocation error, which can      */
6203 /*  only occur if E!=0)                                               */
6204 /* ------------------------------------------------------------------ */
6205 static Int decUnitCompare(const Unit *a, Int alength,
6206                           const Unit *b, Int blength, Int exp) {
6207   Unit  *acc;                      /* accumulator for result */
6208   Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer */
6209   Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated */
6210   Int   accunits, need;            /* units in use or needed for acc */
6211   const Unit *l, *r, *u;           /* work */
6212   Int   expunits, exprem, result;  /* .. */
6213
6214   if (exp==0) {                    /* aligned; fastpath */
6215     if (alength>blength) return 1;
6216     if (alength<blength) return -1;
6217     /* same number of units in both -- need unit-by-unit compare */
6218     l=a+alength-1;
6219     r=b+alength-1;
6220     for (;l>=a; l--, r--) {
6221       if (*l>*r) return 1;
6222       if (*l<*r) return -1;
6223       }
6224     return 0;                      /* all units match */
6225     } /* aligned */
6226
6227   /* Unaligned.  If one is >1 unit longer than the other, padded */
6228   /* approximately, then can return easily */
6229   if (alength>blength+(Int)D2U(exp)) return 1;
6230   if (alength+1<blength+(Int)D2U(exp)) return -1;
6231
6232   /* Need to do a real subtract.  For this, a result buffer is needed */
6233   /* even though only the sign is of interest.  Its length needs */
6234   /* to be the larger of alength and padded blength, +2 */
6235   need=blength+D2U(exp);                /* maximum real length of B */
6236   if (need<alength) need=alength;
6237   need+=2;
6238   acc=accbuff;                          /* assume use local buffer */
6239   if (need*sizeof(Unit)>sizeof(accbuff)) {
6240     allocacc=(Unit *)malloc(need*sizeof(Unit));
6241     if (allocacc==NULL) return BADINT;  /* hopeless -- abandon */
6242     acc=allocacc;
6243     }
6244   /* Calculate units and remainder from exponent. */
6245   expunits=exp/DECDPUN;
6246   exprem=exp%DECDPUN;
6247   /* subtract [A+B*(-m)] */
6248   accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6249                          -(Int)powers[exprem]);
6250   /* [UnitAddSub result may have leading zeros, even on zero] */
6251   if (accunits<0) result=-1;            /* negative result */
6252    else {                               /* non-negative result */
6253     /* check units of the result before freeing any storage */
6254     for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6255     result=(*u==0 ? 0 : +1);
6256     }
6257   /* clean up and return the result */
6258   if (allocacc!=NULL) free(allocacc);   /* drop any storage used */
6259   return result;
6260   } /* decUnitCompare */
6261
6262 /* ------------------------------------------------------------------ */
6263 /* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6264 /*                                                                    */
6265 /*  This routine performs the calculation:                            */
6266 /*                                                                    */
6267 /*  C=A+(B*M)                                                         */
6268 /*                                                                    */
6269 /*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6270 /*                                                                    */
6271 /*  A may be shorter or longer than B.                                */
6272 /*                                                                    */
6273 /*  Leading zeros are not removed after a calculation.  The result is */
6274 /*  either the same length as the longer of A and B (adding any       */
6275 /*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6276 /*                                                                    */
6277 /*  A and B content are not altered unless C is also A or B.          */
6278 /*  C may be the same array as A or B, but only if no zero padding is */
6279 /*  requested (that is, C may be B only if bshift==0).                */
6280 /*  C is filled from the lsu; only those units necessary to complete  */
6281 /*  the calculation are referenced.                                   */
6282 /*                                                                    */
6283 /*  Arg1 is A first Unit (lsu)                                        */
6284 /*  Arg2 is A length in Units                                         */
6285 /*  Arg3 is B first Unit (lsu)                                        */
6286 /*  Arg4 is B length in Units                                         */
6287 /*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6288 /*  Arg6 is C first Unit (lsu)                                        */
6289 /*  Arg7 is M, the multiplier                                         */
6290 /*                                                                    */
6291 /*  returns the count of Units written to C, which will be non-zero   */
6292 /*  and negated if the result is negative.  That is, the sign of the  */
6293 /*  returned Int is the sign of the result (positive for zero) and    */
6294 /*  the absolute value of the Int is the count of Units.              */
6295 /*                                                                    */
6296 /*  It is the caller's responsibility to make sure that C size is     */
6297 /*  safe, allowing space if necessary for a one-Unit carry.           */
6298 /*                                                                    */
6299 /*  This routine is severely performance-critical; *any* change here  */
6300 /*  must be measured (timed) to assure no performance degradation.    */
6301 /*  In particular, trickery here tends to be counter-productive, as   */
6302 /*  increased complexity of code hurts register optimizations on      */
6303 /*  register-poor architectures.  Avoiding divisions is nearly        */
6304 /*  always a Good Idea, however.                                      */
6305 /*                                                                    */
6306 /* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6307 /* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6308 /* ------------------------------------------------------------------ */
6309 static Int decUnitAddSub(const Unit *a, Int alength,
6310                          const Unit *b, Int blength, Int bshift,
6311                          Unit *c, Int m) {
6312   const Unit *alsu=a;              /* A lsu [need to remember it] */
6313   Unit *clsu=c;                    /* C ditto */
6314   Unit *minC;                      /* low water mark for C */
6315   Unit *maxC;                      /* high water mark for C */
6316   eInt carry=0;                    /* carry integer (could be Long) */
6317   Int  add;                        /* work */
6318   #if DECDPUN<=4                   /* myriadal, millenary, etc. */
6319   Int  est;                        /* estimated quotient */
6320   #endif
6321
6322   #if DECTRACE
6323   if (alength<1 || blength<1)
6324     printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6325   #endif
6326
6327   maxC=c+alength;                  /* A is usually the longer */
6328   minC=c+blength;                  /* .. and B the shorter */
6329   if (bshift!=0) {                 /* B is shifted; low As copy across */
6330     minC+=bshift;
6331     /* if in place [common], skip copy unless there's a gap [rare] */
6332     if (a==c && bshift<=alength) {
6333       c+=bshift;
6334       a+=bshift;
6335       }
6336      else for (; c<clsu+bshift; a++, c++) {  /* copy needed */
6337       if (a<alsu+alength) *c=*a;
6338        else *c=0;
6339       }
6340     }
6341   if (minC>maxC) { /* swap */
6342     Unit *hold=minC;
6343     minC=maxC;
6344     maxC=hold;
6345     }
6346
6347   /* For speed, do the addition as two loops; the first where both A */
6348   /* and B contribute, and the second (if necessary) where only one or */
6349   /* other of the numbers contribute. */
6350   /* Carry handling is the same (i.e., duplicated) in each case. */
6351   for (; c<minC; c++) {
6352     carry+=*a;
6353     a++;
6354     carry+=((eInt)*b)*m;                /* [special-casing m=1/-1 */
6355     b++;                                /* here is not a win] */
6356     /* here carry is new Unit of digits; it could be +ve or -ve */
6357     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX */
6358       *c=(Unit)carry;
6359       carry=0;
6360       continue;
6361       }
6362     #if DECDPUN==4                           /* use divide-by-multiply */
6363       if (carry>=0) {
6364         est=(((ueInt)carry>>11)*53687)>>18;
6365         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6366         carry=est;                           /* likely quotient [89%] */
6367         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6368         carry++;
6369         *c-=DECDPUNMAX+1;
6370         continue;
6371         }
6372       /* negative case */
6373       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6374       est=(((ueInt)carry>>11)*53687)>>18;
6375       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6376       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6377       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6378       carry++;
6379       *c-=DECDPUNMAX+1;
6380     #elif DECDPUN==3
6381       if (carry>=0) {
6382         est=(((ueInt)carry>>3)*16777)>>21;
6383         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6384         carry=est;                           /* likely quotient [99%] */
6385         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6386         carry++;
6387         *c-=DECDPUNMAX+1;
6388         continue;
6389         }
6390       /* negative case */
6391       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6392       est=(((ueInt)carry>>3)*16777)>>21;
6393       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6394       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6395       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6396       carry++;
6397       *c-=DECDPUNMAX+1;
6398     #elif DECDPUN<=2
6399       /* Can use QUOT10 as carry <= 4 digits */
6400       if (carry>=0) {
6401         est=QUOT10(carry, DECDPUN);
6402         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6403         carry=est;                           /* quotient */
6404         continue;
6405         }
6406       /* negative case */
6407       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6408       est=QUOT10(carry, DECDPUN);
6409       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6410       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6411     #else
6412       /* remainder operator is undefined if negative, so must test */
6413       if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1 */
6414         *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions] */
6415         carry=1;
6416         continue;
6417         }
6418       if (carry>=0) {
6419         *c=(Unit)(carry%(DECDPUNMAX+1));
6420         carry=carry/(DECDPUNMAX+1);
6421         continue;
6422         }
6423       /* negative case */
6424       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6425       *c=(Unit)(carry%(DECDPUNMAX+1));
6426       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6427     #endif
6428     } /* c */
6429
6430   /* now may have one or other to complete */
6431   /* [pretest to avoid loop setup/shutdown] */
6432   if (c<maxC) for (; c<maxC; c++) {
6433     if (a<alsu+alength) {               /* still in A */
6434       carry+=*a;
6435       a++;
6436       }
6437      else {                             /* inside B */
6438       carry+=((eInt)*b)*m;
6439       b++;
6440       }
6441     /* here carry is new Unit of digits; it could be +ve or -ve and */
6442     /* magnitude up to DECDPUNMAX squared */
6443     if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX */
6444       *c=(Unit)carry;
6445       carry=0;
6446       continue;
6447       }
6448     /* result for this unit is negative or >DECDPUNMAX */
6449     #if DECDPUN==4                           /* use divide-by-multiply */
6450       if (carry>=0) {
6451         est=(((ueInt)carry>>11)*53687)>>18;
6452         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6453         carry=est;                           /* likely quotient [79.7%] */
6454         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6455         carry++;
6456         *c-=DECDPUNMAX+1;
6457         continue;
6458         }
6459       /* negative case */
6460       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6461       est=(((ueInt)carry>>11)*53687)>>18;
6462       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6463       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6464       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6465       carry++;
6466       *c-=DECDPUNMAX+1;
6467     #elif DECDPUN==3
6468       if (carry>=0) {
6469         est=(((ueInt)carry>>3)*16777)>>21;
6470         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6471         carry=est;                           /* likely quotient [99%] */
6472         if (*c<DECDPUNMAX+1) continue;       /* estimate was correct */
6473         carry++;
6474         *c-=DECDPUNMAX+1;
6475         continue;
6476         }
6477       /* negative case */
6478       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6479       est=(((ueInt)carry>>3)*16777)>>21;
6480       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6481       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6482       if (*c<DECDPUNMAX+1) continue;         /* was OK */
6483       carry++;
6484       *c-=DECDPUNMAX+1;
6485     #elif DECDPUN<=2
6486       if (carry>=0) {
6487         est=QUOT10(carry, DECDPUN);
6488         *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder */
6489         carry=est;                           /* quotient */
6490         continue;
6491         }
6492       /* negative case */
6493       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6494       est=QUOT10(carry, DECDPUN);
6495       *c=(Unit)(carry-est*(DECDPUNMAX+1));
6496       carry=est-(DECDPUNMAX+1);              /* correctly negative */
6497     #else
6498       if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1 */
6499         *c=(Unit)(carry-(DECDPUNMAX+1));
6500         carry=1;
6501         continue;
6502         }
6503       /* remainder operator is undefined if negative, so must test */
6504       if (carry>=0) {
6505         *c=(Unit)(carry%(DECDPUNMAX+1));
6506         carry=carry/(DECDPUNMAX+1);
6507         continue;
6508         }
6509       /* negative case */
6510       carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive */
6511       *c=(Unit)(carry%(DECDPUNMAX+1));
6512       carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6513     #endif
6514     } /* c */
6515
6516   /* OK, all A and B processed; might still have carry or borrow */
6517   /* return number of Units in the result, negated if a borrow */
6518   if (carry==0) return c-clsu;     /* no carry, so no more to do */
6519   if (carry>0) {                   /* positive carry */
6520     *c=(Unit)carry;                /* place as new unit */
6521     c++;                           /* .. */
6522     return c-clsu;
6523     }
6524   /* -ve carry: it's a borrow; complement needed */
6525   add=1;                           /* temporary carry... */
6526   for (c=clsu; c<maxC; c++) {
6527     add=DECDPUNMAX+add-*c;
6528     if (add<=DECDPUNMAX) {
6529       *c=(Unit)add;
6530       add=0;
6531       }
6532      else {
6533       *c=0;
6534       add=1;
6535       }
6536     }
6537   /* add an extra unit iff it would be non-zero */
6538   #if DECTRACE
6539     printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6540   #endif
6541   if ((add-carry-1)!=0) {
6542     *c=(Unit)(add-carry-1);
6543     c++;                      /* interesting, include it */
6544     }
6545   return clsu-c;              /* -ve result indicates borrowed */
6546   } /* decUnitAddSub */
6547
6548 /* ------------------------------------------------------------------ */
6549 /* decTrim -- trim trailing zeros or normalize                        */
6550 /*                                                                    */
6551 /*   dn is the number to trim or normalize                            */
6552 /*   set is the context to use to check for clamp                     */
6553 /*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6554 /*   dropped returns the number of discarded trailing zeros           */
6555 /*   returns dn                                                       */
6556 /*                                                                    */
6557 /* If clamp is set in the context then the number of zeros trimmed    */
6558 /* may be limited if the exponent is high.                            */
6559 /* All fields are updated as required.  This is a utility operation,  */
6560 /* so special values are unchanged and no error is possible.          */
6561 /* ------------------------------------------------------------------ */
6562 static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6563                            Int *dropped) {
6564   Int   d, exp;                    /* work */
6565   uInt  cut;                       /* .. */
6566   Unit  *up;                       /* -> current Unit */
6567
6568   #if DECCHECK
6569   if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6570   #endif
6571
6572   *dropped=0;                           /* assume no zeros dropped */
6573   if ((dn->bits & DECSPECIAL)           /* fast exit if special .. */
6574     || (*dn->lsu & 0x01)) return dn;    /* .. or odd */
6575   if (ISZERO(dn)) {                     /* .. or 0 */
6576     dn->exponent=0;                     /* (sign is preserved) */
6577     return dn;
6578     }
6579
6580   /* have a finite number which is even */
6581   exp=dn->exponent;
6582   cut=1;                           /* digit (1-DECDPUN) in Unit */
6583   up=dn->lsu;                      /* -> current Unit */
6584   for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit] */
6585     /* slice by powers */
6586     #if DECDPUN<=4
6587       uInt quot=QUOT10(*up, cut);
6588       if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit */
6589     #else
6590       if (*up%powers[cut]!=0) break;         /* found non-0 digit */
6591     #endif
6592     /* have a trailing 0 */
6593     if (!all) {                    /* trimming */
6594       /* [if exp>0 then all trailing 0s are significant for trim] */
6595       if (exp<=0) {                /* if digit might be significant */
6596         if (exp==0) break;         /* then quit */
6597         exp++;                     /* next digit might be significant */
6598         }
6599       }
6600     cut++;                         /* next power */
6601     if (cut>DECDPUN) {             /* need new Unit */
6602       up++;
6603       cut=1;
6604       }
6605     } /* d */
6606   if (d==0) return dn;             /* none to drop */
6607
6608   /* may need to limit drop if clamping */
6609   if (set->clamp) {
6610     Int maxd=set->emax-set->digits+1-dn->exponent;
6611     if (maxd<=0) return dn;        /* nothing possible */
6612     if (d>maxd) d=maxd;
6613     }
6614
6615   /* effect the drop */
6616   decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6617   dn->exponent+=d;                 /* maintain numerical value */
6618   dn->digits-=d;                   /* new length */
6619   *dropped=d;                      /* report the count */
6620   return dn;
6621   } /* decTrim */
6622
6623 /* ------------------------------------------------------------------ */
6624 /* decReverse -- reverse a Unit array in place                        */
6625 /*                                                                    */
6626 /*   ulo    is the start of the array                                 */
6627 /*   uhi    is the end of the array (highest Unit to include)         */
6628 /*                                                                    */
6629 /* The units ulo through uhi are reversed in place (if the number     */
6630 /* of units is odd, the middle one is untouched).  Note that the      */
6631 /* digit(s) in each unit are unaffected.                              */
6632 /* ------------------------------------------------------------------ */
6633 static void decReverse(Unit *ulo, Unit *uhi) {
6634   Unit temp;
6635   for (; ulo<uhi; ulo++, uhi--) {
6636     temp=*ulo;
6637     *ulo=*uhi;
6638     *uhi=temp;
6639     }
6640   return;
6641   } /* decReverse */
6642
6643 /* ------------------------------------------------------------------ */
6644 /* decShiftToMost -- shift digits in array towards most significant   */
6645 /*                                                                    */
6646 /*   uar    is the array                                              */
6647 /*   digits is the count of digits in use in the array                */
6648 /*   shift  is the number of zeros to pad with (least significant);   */
6649 /*     it must be zero or positive                                    */
6650 /*                                                                    */
6651 /*   returns the new length of the integer in the array, in digits    */
6652 /*                                                                    */
6653 /* No overflow is permitted (that is, the uar array must be known to  */
6654 /* be large enough to hold the result, after shifting).               */
6655 /* ------------------------------------------------------------------ */
6656 static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6657   Unit  *target, *source, *first;  /* work */
6658   Int   cut;                       /* odd 0's to add */
6659   uInt  next;                      /* work */
6660
6661   if (shift==0) return digits;     /* [fastpath] nothing to do */
6662   if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case */
6663     *uar=(Unit)(*uar*powers[shift]);
6664     return digits+shift;
6665     }
6666
6667   next=0;                          /* all paths */
6668   source=uar+D2U(digits)-1;        /* where msu comes from */
6669   target=source+D2U(shift);        /* where upper part of first cut goes */
6670   cut=DECDPUN-MSUDIGITS(shift);    /* where to slice */
6671   if (cut==0) {                    /* unit-boundary case */
6672     for (; source>=uar; source--, target--) *target=*source;
6673     }
6674    else {
6675     first=uar+D2U(digits+shift)-1; /* where msu of source will end up */
6676     for (; source>=uar; source--, target--) {
6677       /* split the source Unit and accumulate remainder for next */
6678       #if DECDPUN<=4
6679         uInt quot=QUOT10(*source, cut);
6680         uInt rem=*source-quot*powers[cut];
6681         next+=quot;
6682       #else
6683         uInt rem=*source%powers[cut];
6684         next+=*source/powers[cut];
6685       #endif
6686       if (target<=first) *target=(Unit)next;   /* write to target iff valid */
6687       next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit */
6688       }
6689     } /* shift-move */
6690
6691   /* propagate any partial unit to one below and clear the rest */
6692   for (; target>=uar; target--) {
6693     *target=(Unit)next;
6694     next=0;
6695     }
6696   return digits+shift;
6697   } /* decShiftToMost */
6698
6699 /* ------------------------------------------------------------------ */
6700 /* decShiftToLeast -- shift digits in array towards least significant */
6701 /*                                                                    */
6702 /*   uar   is the array                                               */
6703 /*   units is length of the array, in units                           */
6704 /*   shift is the number of digits to remove from the lsu end; it     */
6705 /*     must be zero or positive and <= than units*DECDPUN.            */
6706 /*                                                                    */
6707 /*   returns the new length of the integer in the array, in units     */
6708 /*                                                                    */
6709 /* Removed digits are discarded (lost).  Units not required to hold   */
6710 /* the final result are unchanged.                                    */
6711 /* ------------------------------------------------------------------ */
6712 static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6713   Unit  *target, *up;              /* work */
6714   Int   cut, count;                /* work */
6715   Int   quot, rem;                 /* for division */
6716
6717   if (shift==0) return units;      /* [fastpath] nothing to do */
6718   if (shift==units*DECDPUN) {      /* [fastpath] little to do */
6719     *uar=0;                        /* all digits cleared gives zero */
6720     return 1;                      /* leaves just the one */
6721     }
6722
6723   target=uar;                      /* both paths */
6724   cut=MSUDIGITS(shift);
6725   if (cut==DECDPUN) {              /* unit-boundary case; easy */
6726     up=uar+D2U(shift);
6727     for (; up<uar+units; target++, up++) *target=*up;
6728     return target-uar;
6729     }
6730
6731   /* messier */
6732   up=uar+D2U(shift-cut);           /* source; correct to whole Units */
6733   count=units*DECDPUN-shift;       /* the maximum new length */
6734   #if DECDPUN<=4
6735     quot=QUOT10(*up, cut);
6736   #else
6737     quot=*up/powers[cut];
6738   #endif
6739   for (; ; target++) {
6740     *target=(Unit)quot;
6741     count-=(DECDPUN-cut);
6742     if (count<=0) break;
6743     up++;
6744     quot=*up;
6745     #if DECDPUN<=4
6746       quot=QUOT10(quot, cut);
6747       rem=*up-quot*powers[cut];
6748     #else
6749       rem=quot%powers[cut];
6750       quot=quot/powers[cut];
6751     #endif
6752     *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6753     count-=cut;
6754     if (count<=0) break;
6755     }
6756   return target-uar+1;
6757   } /* decShiftToLeast */
6758
6759 #if DECSUBSET
6760 /* ------------------------------------------------------------------ */
6761 /* decRoundOperand -- round an operand  [used for subset only]        */
6762 /*                                                                    */
6763 /*   dn is the number to round (dn->digits is > set->digits)          */
6764 /*   set is the relevant context                                      */
6765 /*   status is the status accumulator                                 */
6766 /*                                                                    */
6767 /*   returns an allocated decNumber with the rounded result.          */
6768 /*                                                                    */
6769 /* lostDigits and other status may be set by this.                    */
6770 /*                                                                    */
6771 /* Since the input is an operand, it must not be modified.            */
6772 /* Instead, return an allocated decNumber, rounded as required.       */
6773 /* It is the caller's responsibility to free the allocated storage.   */
6774 /*                                                                    */
6775 /* If no storage is available then the result cannot be used, so NULL */
6776 /* is returned.                                                       */
6777 /* ------------------------------------------------------------------ */
6778 static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6779                                   uInt *status) {
6780   decNumber *res;                       /* result structure */
6781   uInt newstatus=0;                     /* status from round */
6782   Int  residue=0;                       /* rounding accumulator */
6783
6784   /* Allocate storage for the returned decNumber, big enough for the */
6785   /* length specified by the context */
6786   res=(decNumber *)malloc(sizeof(decNumber)
6787                           +(D2U(set->digits)-1)*sizeof(Unit));
6788   if (res==NULL) {
6789     *status|=DEC_Insufficient_storage;
6790     return NULL;
6791     }
6792   decCopyFit(res, dn, set, &residue, &newstatus);
6793   decApplyRound(res, set, residue, &newstatus);
6794
6795   /* If that set Inexact then "lost digits" is raised... */
6796   if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6797   *status|=newstatus;
6798   return res;
6799   } /* decRoundOperand */
6800 #endif
6801
6802 /* ------------------------------------------------------------------ */
6803 /* decCopyFit -- copy a number, truncating the coefficient if needed  */
6804 /*                                                                    */
6805 /*   dest is the target decNumber                                     */
6806 /*   src  is the source decNumber                                     */
6807 /*   set is the context [used for length (digits) and rounding mode]  */
6808 /*   residue is the residue accumulator                               */
6809 /*   status contains the current status to be updated                 */
6810 /*                                                                    */
6811 /* (dest==src is allowed and will be a no-op if fits)                 */
6812 /* All fields are updated as required.                                */
6813 /* ------------------------------------------------------------------ */
6814 static void decCopyFit(decNumber *dest, const decNumber *src,
6815                        decContext *set, Int *residue, uInt *status) {
6816   dest->bits=src->bits;
6817   dest->exponent=src->exponent;
6818   decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6819   } /* decCopyFit */
6820
6821 /* ------------------------------------------------------------------ */
6822 /* decSetCoeff -- set the coefficient of a number                     */
6823 /*                                                                    */
6824 /*   dn    is the number whose coefficient array is to be set.        */
6825 /*         It must have space for set->digits digits                  */
6826 /*   set   is the context [for size]                                  */
6827 /*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6828 /*   len   is digits in the source coefficient [may be dn->digits]    */
6829 /*   residue is the residue accumulator.  This has values as in       */
6830 /*         decApplyRound, and will be unchanged unless the            */
6831 /*         target size is less than len.  In this case, the           */
6832 /*         coefficient is truncated and the residue is updated to     */
6833 /*         reflect the previous residue and the dropped digits.       */
6834 /*   status is the status accumulator, as usual                       */
6835 /*                                                                    */
6836 /* The coefficient may already be in the number, or it can be an      */
6837 /* external intermediate array.  If it is in the number, lsu must ==  */
6838 /* dn->lsu and len must == dn->digits.                                */
6839 /*                                                                    */
6840 /* Note that the coefficient length (len) may be < set->digits, and   */
6841 /* in this case this merely copies the coefficient (or is a no-op     */
6842 /* if dn->lsu==lsu).                                                  */
6843 /*                                                                    */
6844 /* Note also that (only internally, from decQuantizeOp and            */
6845 /* decSetSubnormal) the value of set->digits may be less than one,    */
6846 /* indicating a round to left.  This routine handles that case        */
6847 /* correctly; caller ensures space.                                   */
6848 /*                                                                    */
6849 /* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6850 /* updated as necessary.   dn->bits (sign) is unchanged.              */
6851 /*                                                                    */
6852 /* DEC_Rounded status is set if any digits are discarded.             */
6853 /* DEC_Inexact status is set if any non-zero digits are discarded, or */
6854 /*                       incoming residue was non-0 (implies rounded) */
6855 /* ------------------------------------------------------------------ */
6856 /* mapping array: maps 0-9 to canonical residues, so that a residue */
6857 /* can be adjusted in the range [-1, +1] and achieve correct rounding */
6858 /*                             0  1  2  3  4  5  6  7  8  9 */
6859 static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6860 static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6861                         Int len, Int *residue, uInt *status) {
6862   Int   discard;              /* number of digits to discard */
6863   uInt  cut;                  /* cut point in Unit */
6864   const Unit *up;             /* work */
6865   Unit  *target;              /* .. */
6866   Int   count;                /* .. */
6867   #if DECDPUN<=4
6868   uInt  temp;                 /* .. */
6869   #endif
6870
6871   discard=len-set->digits;    /* digits to discard */
6872   if (discard<=0) {           /* no digits are being discarded */
6873     if (dn->lsu!=lsu) {       /* copy needed */
6874       /* copy the coefficient array to the result number; no shift needed */
6875       count=len;              /* avoids D2U */
6876       up=lsu;
6877       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6878         *target=*up;
6879       dn->digits=len;         /* set the new length */
6880       }
6881     /* dn->exponent and residue are unchanged, record any inexactitude */
6882     if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6883     return;
6884     }
6885
6886   /* some digits must be discarded ... */
6887   dn->exponent+=discard;      /* maintain numerical value */
6888   *status|=DEC_Rounded;       /* accumulate Rounded status */
6889   if (*residue>1) *residue=1; /* previous residue now to right, so reduce */
6890
6891   if (discard>len) {          /* everything, +1, is being discarded */
6892     /* guard digit is 0 */
6893     /* residue is all the number [NB could be all 0s] */
6894     if (*residue<=0) {        /* not already positive */
6895       count=len;              /* avoids D2U */
6896       for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0 */
6897         *residue=1;
6898         break;                /* no need to check any others */
6899         }
6900       }
6901     if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
6902     *dn->lsu=0;               /* coefficient will now be 0 */
6903     dn->digits=1;             /* .. */
6904     return;
6905     } /* total discard */
6906
6907   /* partial discard [most common case] */
6908   /* here, at least the first (most significant) discarded digit exists */
6909
6910   /* spin up the number, noting residue during the spin, until get to */
6911   /* the Unit with the first discarded digit.  When reach it, extract */
6912   /* it and remember its position */
6913   count=0;
6914   for (up=lsu;; up++) {
6915     count+=DECDPUN;
6916     if (count>=discard) break; /* full ones all checked */
6917     if (*up!=0) *residue=1;
6918     } /* up */
6919
6920   /* here up -> Unit with first discarded digit */
6921   cut=discard-(count-DECDPUN)-1;
6922   if (cut==DECDPUN-1) {       /* unit-boundary case (fast) */
6923     Unit half=(Unit)powers[DECDPUN]>>1;
6924     /* set residue directly */
6925     if (*up>=half) {
6926       if (*up>half) *residue=7;
6927       else *residue+=5;       /* add sticky bit */
6928       }
6929      else { /* <half */
6930       if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit] */
6931       }
6932     if (set->digits<=0) {     /* special for Quantize/Subnormal :-( */
6933       *dn->lsu=0;             /* .. result is 0 */
6934       dn->digits=1;           /* .. */
6935       }
6936      else {                   /* shift to least */
6937       count=set->digits;      /* now digits to end up with */
6938       dn->digits=count;       /* set the new length */
6939       up++;                   /* move to next */
6940       /* on unit boundary, so shift-down copy loop is simple */
6941       for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6942         *target=*up;
6943       }
6944     } /* unit-boundary case */
6945
6946    else { /* discard digit is in low digit(s), and not top digit */
6947     uInt  discard1;                /* first discarded digit */
6948     uInt  quot, rem;               /* for divisions */
6949     if (cut==0) quot=*up;          /* is at bottom of unit */
6950      else /* cut>0 */ {            /* it's not at bottom of unit */
6951       #if DECDPUN<=4
6952         quot=QUOT10(*up, cut);
6953         rem=*up-quot*powers[cut];
6954       #else
6955         rem=*up%powers[cut];
6956         quot=*up/powers[cut];
6957       #endif
6958       if (rem!=0) *residue=1;
6959       }
6960     /* discard digit is now at bottom of quot */
6961     #if DECDPUN<=4
6962       temp=(quot*6554)>>16;        /* fast /10 */
6963       /* Vowels algorithm here not a win (9 instructions) */
6964       discard1=quot-X10(temp);
6965       quot=temp;
6966     #else
6967       discard1=quot%10;
6968       quot=quot/10;
6969     #endif
6970     /* here, discard1 is the guard digit, and residue is everything */
6971     /* else [use mapping array to accumulate residue safely] */
6972     *residue+=resmap[discard1];
6973     cut++;                         /* update cut */
6974     /* here: up -> Unit of the array with bottom digit */
6975     /*       cut is the division point for each Unit */
6976     /*       quot holds the uncut high-order digits for the current unit */
6977     if (set->digits<=0) {          /* special for Quantize/Subnormal :-( */
6978       *dn->lsu=0;                  /* .. result is 0 */
6979       dn->digits=1;                /* .. */
6980       }
6981      else {                        /* shift to least needed */
6982       count=set->digits;           /* now digits to end up with */
6983       dn->digits=count;            /* set the new length */
6984       /* shift-copy the coefficient array to the result number */
6985       for (target=dn->lsu; ; target++) {
6986         *target=(Unit)quot;
6987         count-=(DECDPUN-cut);
6988         if (count<=0) break;
6989         up++;
6990         quot=*up;
6991         #if DECDPUN<=4
6992           quot=QUOT10(quot, cut);
6993           rem=*up-quot*powers[cut];
6994         #else
6995           rem=quot%powers[cut];
6996           quot=quot/powers[cut];
6997         #endif
6998         *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6999         count-=cut;
7000         if (count<=0) break;
7001         } /* shift-copy loop */
7002       } /* shift to least */
7003     } /* not unit boundary */
7004
7005   if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude */
7006   return;
7007   } /* decSetCoeff */
7008
7009 /* ------------------------------------------------------------------ */
7010 /* decApplyRound -- apply pending rounding to a number                */
7011 /*                                                                    */
7012 /*   dn    is the number, with space for set->digits digits           */
7013 /*   set   is the context [for size and rounding mode]                */
7014 /*   residue indicates pending rounding, being any accumulated        */
7015 /*         guard and sticky information.  It may be:                  */
7016 /*         6-9: rounding digit is >5                                  */
7017 /*         5:   rounding digit is exactly half-way                    */
7018 /*         1-4: rounding digit is <5 and >0                           */
7019 /*         0:   the coefficient is exact                              */
7020 /*        -1:   as 1, but the hidden digits are subtractive, that     */
7021 /*              is, of the opposite sign to dn.  In this case the     */
7022 /*              coefficient must be non-0.  This case occurs when     */
7023 /*              subtracting a small number (which can be reduced to   */
7024 /*              a sticky bit); see decAddOp.                          */
7025 /*   status is the status accumulator, as usual                       */
7026 /*                                                                    */
7027 /* This routine applies rounding while keeping the length of the      */
7028 /* coefficient constant.  The exponent and status are unchanged       */
7029 /* except if:                                                         */
7030 /*                                                                    */
7031 /*   -- the coefficient was increased and is all nines (in which      */
7032 /*      case Overflow could occur, and is handled directly here so    */
7033 /*      the caller does not need to re-test for overflow)             */
7034 /*                                                                    */
7035 /*   -- the coefficient was decreased and becomes all nines (in which */
7036 /*      case Underflow could occur, and is also handled directly).    */
7037 /*                                                                    */
7038 /* All fields in dn are updated as required.                          */
7039 /*                                                                    */
7040 /* ------------------------------------------------------------------ */
7041 static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7042                           uInt *status) {
7043   Int  bump;                  /* 1 if coefficient needs to be incremented */
7044                               /* -1 if coefficient needs to be decremented */
7045
7046   if (residue==0) return;     /* nothing to apply */
7047
7048   bump=0;                     /* assume a smooth ride */
7049
7050   /* now decide whether, and how, to round, depending on mode */
7051   switch (set->round) {
7052     case DEC_ROUND_05UP: {    /* round zero or five up (for reround) */
7053       /* This is the same as DEC_ROUND_DOWN unless there is a */
7054       /* positive residue and the lsd of dn is 0 or 5, in which case */
7055       /* it is bumped; when residue is <0, the number is therefore */
7056       /* bumped down unless the final digit was 1 or 6 (in which */
7057       /* case it is bumped down and then up -- a no-op) */
7058       Int lsd5=*dn->lsu%5;     /* get lsd and quintate */
7059       if (residue<0 && lsd5!=1) bump=-1;
7060        else if (residue>0 && lsd5==0) bump=1;
7061       /* [bump==1 could be applied directly; use common path for clarity] */
7062       break;} /* r-05 */
7063
7064     case DEC_ROUND_DOWN: {
7065       /* no change, except if negative residue */
7066       if (residue<0) bump=-1;
7067       break;} /* r-d */
7068
7069     case DEC_ROUND_HALF_DOWN: {
7070       if (residue>5) bump=1;
7071       break;} /* r-h-d */
7072
7073     case DEC_ROUND_HALF_EVEN: {
7074       if (residue>5) bump=1;            /* >0.5 goes up */
7075        else if (residue==5) {           /* exactly 0.5000... */
7076         /* 0.5 goes up iff [new] lsd is odd */
7077         if (*dn->lsu & 0x01) bump=1;
7078         }
7079       break;} /* r-h-e */
7080
7081     case DEC_ROUND_HALF_UP: {
7082       if (residue>=5) bump=1;
7083       break;} /* r-h-u */
7084
7085     case DEC_ROUND_UP: {
7086       if (residue>0) bump=1;
7087       break;} /* r-u */
7088
7089     case DEC_ROUND_CEILING: {
7090       /* same as _UP for positive numbers, and as _DOWN for negatives */
7091       /* [negative residue cannot occur on 0] */
7092       if (decNumberIsNegative(dn)) {
7093         if (residue<0) bump=-1;
7094         }
7095        else {
7096         if (residue>0) bump=1;
7097         }
7098       break;} /* r-c */
7099
7100     case DEC_ROUND_FLOOR: {
7101       /* same as _UP for negative numbers, and as _DOWN for positive */
7102       /* [negative residue cannot occur on 0] */
7103       if (!decNumberIsNegative(dn)) {
7104         if (residue<0) bump=-1;
7105         }
7106        else {
7107         if (residue>0) bump=1;
7108         }
7109       break;} /* r-f */
7110
7111     default: {      /* e.g., DEC_ROUND_MAX */
7112       *status|=DEC_Invalid_context;
7113       #if DECTRACE || (DECCHECK && DECVERB)
7114       printf("Unknown rounding mode: %d\n", set->round);
7115       #endif
7116       break;}
7117     } /* switch */
7118
7119   /* now bump the number, up or down, if need be */
7120   if (bump==0) return;                       /* no action required */
7121
7122   /* Simply use decUnitAddSub unless bumping up and the number is */
7123   /* all nines.  In this special case set to 100... explicitly */
7124   /* and adjust the exponent by one (as otherwise could overflow */
7125   /* the array) */
7126   /* Similarly handle all-nines result if bumping down. */
7127   if (bump>0) {
7128     Unit *up;                                /* work */
7129     uInt count=dn->digits;                   /* digits to be checked */
7130     for (up=dn->lsu; ; up++) {
7131       if (count<=DECDPUN) {
7132         /* this is the last Unit (the msu) */
7133         if (*up!=powers[count]-1) break;     /* not still 9s */
7134         /* here if it, too, is all nines */
7135         *up=(Unit)powers[count-1];           /* here 999 -> 100 etc. */
7136         for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0 */
7137         dn->exponent++;                      /* and bump exponent */
7138         /* [which, very rarely, could cause Overflow...] */
7139         if ((dn->exponent+dn->digits)>set->emax+1) {
7140           decSetOverflow(dn, set, status);
7141           }
7142         return;                              /* done */
7143         }
7144       /* a full unit to check, with more to come */
7145       if (*up!=DECDPUNMAX) break;            /* not still 9s */
7146       count-=DECDPUN;
7147       } /* up */
7148     } /* bump>0 */
7149    else {                                    /* -1 */
7150     /* here checking for a pre-bump of 1000... (leading 1, all */
7151     /* other digits zero) */
7152     Unit *up, *sup;                          /* work */
7153     uInt count=dn->digits;                   /* digits to be checked */
7154     for (up=dn->lsu; ; up++) {
7155       if (count<=DECDPUN) {
7156         /* this is the last Unit (the msu) */
7157         if (*up!=powers[count-1]) break;     /* not 100.. */
7158         /* here if have the 1000... case */
7159         sup=up;                              /* save msu pointer */
7160         *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999 */
7161         /* others all to all-nines, too */
7162         for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7163         dn->exponent--;                      /* and bump exponent */
7164
7165         /* iff the number was at the subnormal boundary (exponent=etiny) */
7166         /* then the exponent is now out of range, so it will in fact get */
7167         /* clamped to etiny and the final 9 dropped. */
7168         /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin, */
7169         /*        dn->exponent, set->digits); */
7170         if (dn->exponent+1==set->emin-set->digits+1) {
7171           if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9] */
7172            else {
7173             *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99.. */
7174             dn->digits--;
7175             }
7176           dn->exponent++;
7177           *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7178           }
7179         return;                              /* done */
7180         }
7181
7182       /* a full unit to check, with more to come */
7183       if (*up!=0) break;                     /* not still 0s */
7184       count-=DECDPUN;
7185       } /* up */
7186
7187     } /* bump<0 */
7188
7189   /* Actual bump needed.  Do it. */
7190   decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7191   } /* decApplyRound */
7192
7193 #if DECSUBSET
7194 /* ------------------------------------------------------------------ */
7195 /* decFinish -- finish processing a number                            */
7196 /*                                                                    */
7197 /*   dn is the number                                                 */
7198 /*   set is the context                                               */
7199 /*   residue is the rounding accumulator (as in decApplyRound)        */
7200 /*   status is the accumulator                                        */
7201 /*                                                                    */
7202 /* This finishes off the current number by:                           */
7203 /*    1. If not extended:                                             */
7204 /*       a. Converting a zero result to clean '0'                     */
7205 /*       b. Reducing positive exponents to 0, if would fit in digits  */
7206 /*    2. Checking for overflow and subnormals (always)                */
7207 /* Note this is just Finalize when no subset arithmetic.              */
7208 /* All fields are updated as required.                                */
7209 /* ------------------------------------------------------------------ */
7210 static void decFinish(decNumber *dn, decContext *set, Int *residue,
7211                       uInt *status) {
7212   if (!set->extended) {
7213     if ISZERO(dn) {                /* value is zero */
7214       dn->exponent=0;              /* clean exponent .. */
7215       dn->bits=0;                  /* .. and sign */
7216       return;                      /* no error possible */
7217       }
7218     if (dn->exponent>=0) {         /* non-negative exponent */
7219       /* >0; reduce to integer if possible */
7220       if (set->digits >= (dn->exponent+dn->digits)) {
7221         dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7222         dn->exponent=0;
7223         }
7224       }
7225     } /* !extended */
7226
7227   decFinalize(dn, set, residue, status);
7228   } /* decFinish */
7229 #endif
7230
7231 /* ------------------------------------------------------------------ */
7232 /* decFinalize -- final check, clamp, and round of a number           */
7233 /*                                                                    */
7234 /*   dn is the number                                                 */
7235 /*   set is the context                                               */
7236 /*   residue is the rounding accumulator (as in decApplyRound)        */
7237 /*   status is the status accumulator                                 */
7238 /*                                                                    */
7239 /* This finishes off the current number by checking for subnormal     */
7240 /* results, applying any pending rounding, checking for overflow,     */
7241 /* and applying any clamping.                                         */
7242 /* Underflow and overflow conditions are raised as appropriate.       */
7243 /* All fields are updated as required.                                */
7244 /* ------------------------------------------------------------------ */
7245 static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7246                         uInt *status) {
7247   Int shift;                            /* shift needed if clamping */
7248   Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary */
7249
7250   /* Must be careful, here, when checking the exponent as the */
7251   /* adjusted exponent could overflow 31 bits [because it may already */
7252   /* be up to twice the expected]. */
7253
7254   /* First test for subnormal.  This must be done before any final */
7255   /* round as the result could be rounded to Nmin or 0. */
7256   if (dn->exponent<=tinyexp) {          /* prefilter */
7257     Int comp;
7258     decNumber nmin;
7259     /* A very nasty case here is dn == Nmin and residue<0 */
7260     if (dn->exponent<tinyexp) {
7261       /* Go handle subnormals; this will apply round if needed. */
7262       decSetSubnormal(dn, set, residue, status);
7263       return;
7264       }
7265     /* Equals case: only subnormal if dn=Nmin and negative residue */
7266     decNumberZero(&nmin);
7267     nmin.lsu[0]=1;
7268     nmin.exponent=set->emin;
7269     comp=decCompare(dn, &nmin, 1);                /* (signless compare) */
7270     if (comp==BADINT) {                           /* oops */
7271       *status|=DEC_Insufficient_storage;          /* abandon... */
7272       return;
7273       }
7274     if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin */
7275       decApplyRound(dn, set, *residue, status);   /* might force down */
7276       decSetSubnormal(dn, set, residue, status);
7277       return;
7278       }
7279     }
7280
7281   /* now apply any pending round (this could raise overflow). */
7282   if (*residue!=0) decApplyRound(dn, set, *residue, status);
7283
7284   /* Check for overflow [redundant in the 'rare' case] or clamp */
7285   if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed */
7286
7287
7288   /* here when might have an overflow or clamp to do */
7289   if (dn->exponent>set->emax-dn->digits+1) {           /* too big */
7290     decSetOverflow(dn, set, status);
7291     return;
7292     }
7293   /* here when the result is normal but in clamp range */
7294   if (!set->clamp) return;
7295
7296   /* here when need to apply the IEEE exponent clamp (fold-down) */
7297   shift=dn->exponent-(set->emax-set->digits+1);
7298
7299   /* shift coefficient (if non-zero) */
7300   if (!ISZERO(dn)) {
7301     dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7302     }
7303   dn->exponent-=shift;   /* adjust the exponent to match */
7304   *status|=DEC_Clamped;  /* and record the dirty deed */
7305   return;
7306   } /* decFinalize */
7307
7308 /* ------------------------------------------------------------------ */
7309 /* decSetOverflow -- set number to proper overflow value              */
7310 /*                                                                    */
7311 /*   dn is the number (used for sign [only] and result)               */
7312 /*   set is the context [used for the rounding mode, etc.]            */
7313 /*   status contains the current status to be updated                 */
7314 /*                                                                    */
7315 /* This sets the sign of a number and sets its value to either        */
7316 /* Infinity or the maximum finite value, depending on the sign of     */
7317 /* dn and the rounding mode, following IEEE 854 rules.                */
7318 /* ------------------------------------------------------------------ */
7319 static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7320   Flag needmax=0;                  /* result is maximum finite value */
7321   uByte sign=dn->bits&DECNEG;      /* clean and save sign bit */
7322
7323   if (ISZERO(dn)) {                /* zero does not overflow magnitude */
7324     Int emax=set->emax;                      /* limit value */
7325     if (set->clamp) emax-=set->digits-1;     /* lower if clamping */
7326     if (dn->exponent>emax) {                 /* clamp required */
7327       dn->exponent=emax;
7328       *status|=DEC_Clamped;
7329       }
7330     return;
7331     }
7332
7333   decNumberZero(dn);
7334   switch (set->round) {
7335     case DEC_ROUND_DOWN: {
7336       needmax=1;                   /* never Infinity */
7337       break;} /* r-d */
7338     case DEC_ROUND_05UP: {
7339       needmax=1;                   /* never Infinity */
7340       break;} /* r-05 */
7341     case DEC_ROUND_CEILING: {
7342       if (sign) needmax=1;         /* Infinity if non-negative */
7343       break;} /* r-c */
7344     case DEC_ROUND_FLOOR: {
7345       if (!sign) needmax=1;        /* Infinity if negative */
7346       break;} /* r-f */
7347     default: break;                /* Infinity in all other cases */
7348     }
7349   if (needmax) {
7350     decSetMaxValue(dn, set);
7351     dn->bits=sign;                 /* set sign */
7352     }
7353    else dn->bits=sign|DECINF;      /* Value is +/-Infinity */
7354   *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7355   } /* decSetOverflow */
7356
7357 /* ------------------------------------------------------------------ */
7358 /* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7359 /*                                                                    */
7360 /*   dn is the number to set                                          */
7361 /*   set is the context [used for digits and emax]                    */
7362 /*                                                                    */
7363 /* This sets the number to the maximum positive value.                */
7364 /* ------------------------------------------------------------------ */
7365 static void decSetMaxValue(decNumber *dn, decContext *set) {
7366   Unit *up;                        /* work */
7367   Int count=set->digits;           /* nines to add */
7368   dn->digits=count;
7369   /* fill in all nines to set maximum value */
7370   for (up=dn->lsu; ; up++) {
7371     if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines */
7372      else {                             /* this is the msu */
7373       *up=(Unit)(powers[count]-1);
7374       break;
7375       }
7376     count-=DECDPUN;                /* filled those digits */
7377     } /* up */
7378   dn->bits=0;                      /* + sign */
7379   dn->exponent=set->emax-set->digits+1;
7380   } /* decSetMaxValue */
7381
7382 /* ------------------------------------------------------------------ */
7383 /* decSetSubnormal -- process value whose exponent is <Emin           */
7384 /*                                                                    */
7385 /*   dn is the number (used as input as well as output; it may have   */
7386 /*         an allowed subnormal value, which may need to be rounded)  */
7387 /*   set is the context [used for the rounding mode]                  */
7388 /*   residue is any pending residue                                   */
7389 /*   status contains the current status to be updated                 */
7390 /*                                                                    */
7391 /* If subset mode, set result to zero and set Underflow flags.        */
7392 /*                                                                    */
7393 /* Value may be zero with a low exponent; this does not set Subnormal */
7394 /* but the exponent will be clamped to Etiny.                         */
7395 /*                                                                    */
7396 /* Otherwise ensure exponent is not out of range, and round as        */
7397 /* necessary.  Underflow is set if the result is Inexact.             */
7398 /* ------------------------------------------------------------------ */
7399 static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7400                             uInt *status) {
7401   Int        dnexp;           /* saves original exponent */
7402   decContext workset;         /* work */
7403   Int        etiny, adjust;   /* .. */
7404
7405   #if DECSUBSET
7406   /* simple set to zero and 'hard underflow' for subset */
7407   if (!set->extended) {
7408     decNumberZero(dn);
7409     /* always full overflow */
7410     *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7411     return;
7412     }
7413   #endif
7414
7415   /* Full arithmetic -- allow subnormals, rounded to minimum exponent */
7416   /* (Etiny) if needed */
7417   etiny=set->emin-(set->digits-1);      /* smallest allowed exponent */
7418
7419   if ISZERO(dn) {                       /* value is zero */
7420     /* residue can never be non-zero here */
7421     #if DECCHECK
7422       if (*residue!=0) {
7423         printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7424         *status|=DEC_Invalid_operation;
7425         }
7426     #endif
7427     if (dn->exponent<etiny) {           /* clamp required */
7428       dn->exponent=etiny;
7429       *status|=DEC_Clamped;
7430       }
7431     return;
7432     }
7433
7434   *status|=DEC_Subnormal;               /* have a non-zero subnormal */
7435   adjust=etiny-dn->exponent;            /* calculate digits to remove */
7436   if (adjust<=0) {                      /* not out of range; unrounded */
7437     /* residue can never be non-zero here, except in the Nmin-residue */
7438     /* case (which is a subnormal result), so can take fast-path here */
7439     /* it may already be inexact (from setting the coefficient) */
7440     if (*status&DEC_Inexact) *status|=DEC_Underflow;
7441     return;
7442     }
7443
7444   /* adjust>0, so need to rescale the result so exponent becomes Etiny */
7445   /* [this code is similar to that in rescale] */
7446   dnexp=dn->exponent;                   /* save exponent */
7447   workset=*set;                         /* clone rounding, etc. */
7448   workset.digits=dn->digits-adjust;     /* set requested length */
7449   workset.emin-=adjust;                 /* and adjust emin to match */
7450   /* [note that the latter can be <1, here, similar to Rescale case] */
7451   decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7452   decApplyRound(dn, &workset, *residue, status);
7453
7454   /* Use 754R/854 default rule: Underflow is set iff Inexact */
7455   /* [independent of whether trapped] */
7456   if (*status&DEC_Inexact) *status|=DEC_Underflow;
7457
7458   /* if rounded up a 999s case, exponent will be off by one; adjust */
7459   /* back if so [it will fit, because it was shortened earlier] */
7460   if (dn->exponent>etiny) {
7461     dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7462     dn->exponent--;                     /* (re)adjust the exponent. */
7463     }
7464
7465   /* if rounded to zero, it is by definition clamped... */
7466   if (ISZERO(dn)) *status|=DEC_Clamped;
7467   } /* decSetSubnormal */
7468
7469 /* ------------------------------------------------------------------ */
7470 /* decCheckMath - check entry conditions for a math function          */
7471 /*                                                                    */
7472 /*   This checks the context and the operand                          */
7473 /*                                                                    */
7474 /*   rhs is the operand to check                                      */
7475 /*   set is the context to check                                      */
7476 /*   status is unchanged if both are good                             */
7477 /*                                                                    */
7478 /* returns non-zero if status is changed, 0 otherwise                 */
7479 /*                                                                    */
7480 /* Restrictions enforced:                                             */
7481 /*                                                                    */
7482 /*   digits, emax, and -emin in the context must be less than         */
7483 /*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7484 /*   non-zero.  Invalid_operation is set in the status if a           */
7485 /*   restriction is violated.                                         */
7486 /* ------------------------------------------------------------------ */
7487 static uInt decCheckMath(const decNumber *rhs, decContext *set,
7488                          uInt *status) {
7489   uInt save=*status;                         /* record */
7490   if (set->digits>DEC_MAX_MATH
7491    || set->emax>DEC_MAX_MATH
7492    || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7493    else if ((rhs->digits>DEC_MAX_MATH
7494      || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7495      || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7496      && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7497   return (*status!=save);
7498   } /* decCheckMath */
7499
7500 /* ------------------------------------------------------------------ */
7501 /* decGetInt -- get integer from a number                             */
7502 /*                                                                    */
7503 /*   dn is the number [which will not be altered]                     */
7504 /*                                                                    */
7505 /*   returns one of:                                                  */
7506 /*     BADINT if there is a non-zero fraction                         */
7507 /*     the converted integer                                          */
7508 /*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7509 /*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7510 /*                                                                    */
7511 /* This checks and gets a whole number from the input decNumber.      */
7512 /* The sign can be determined from dn by the caller when BIGEVEN or   */
7513 /* BIGODD is returned.                                                */
7514 /* ------------------------------------------------------------------ */
7515 static Int decGetInt(const decNumber *dn) {
7516   Int  theInt;                          /* result accumulator */
7517   const Unit *up;                       /* work */
7518   Int  got;                             /* digits (real or not) processed */
7519   Int  ilength=dn->digits+dn->exponent; /* integral length */
7520   Flag neg=decNumberIsNegative(dn);     /* 1 if -ve */
7521
7522   /* The number must be an integer that fits in 10 digits */
7523   /* Assert, here, that 10 is enough for any rescale Etiny */
7524   #if DEC_MAX_EMAX > 999999999
7525     #error GetInt may need updating [for Emax]
7526   #endif
7527   #if DEC_MIN_EMIN < -999999999
7528     #error GetInt may need updating [for Emin]
7529   #endif
7530   if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent */
7531
7532   up=dn->lsu;                           /* ready for lsu */
7533   theInt=0;                             /* ready to accumulate */
7534   if (dn->exponent>=0) {                /* relatively easy */
7535     /* no fractional part [usual]; allow for positive exponent */
7536     got=dn->exponent;
7537     }
7538    else { /* -ve exponent; some fractional part to check and discard */
7539     Int count=-dn->exponent;            /* digits to discard */
7540     /* spin up whole units until reach the Unit with the unit digit */
7541     for (; count>=DECDPUN; up++) {
7542       if (*up!=0) return BADINT;        /* non-zero Unit to discard */
7543       count-=DECDPUN;
7544       }
7545     if (count==0) got=0;                /* [a multiple of DECDPUN] */
7546      else {                             /* [not multiple of DECDPUN] */
7547       Int rem;                          /* work */
7548       /* slice off fraction digits and check for non-zero */
7549       #if DECDPUN<=4
7550         theInt=QUOT10(*up, count);
7551         rem=*up-theInt*powers[count];
7552       #else
7553         rem=*up%powers[count];          /* slice off discards */
7554         theInt=*up/powers[count];
7555       #endif
7556       if (rem!=0) return BADINT;        /* non-zero fraction */
7557       /* it looks good */
7558       got=DECDPUN-count;                /* number of digits so far */
7559       up++;                             /* ready for next */
7560       }
7561     }
7562   /* now it's known there's no fractional part */
7563
7564   /* tricky code now, to accumulate up to 9.3 digits */
7565   if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there */
7566
7567   if (ilength<11) {
7568     Int save=theInt;
7569     /* collect any remaining unit(s) */
7570     for (; got<ilength; up++) {
7571       theInt+=*up*powers[got];
7572       got+=DECDPUN;
7573       }
7574     if (ilength==10) {                  /* need to check for wrap */
7575       if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7576          /* [that test also disallows the BADINT result case] */
7577        else if (neg && theInt>1999999997) ilength=11;
7578        else if (!neg && theInt>999999999) ilength=11;
7579       if (ilength==11) theInt=save;     /* restore correct low bit */
7580       }
7581     }
7582
7583   if (ilength>10) {                     /* too big */
7584     if (theInt&1) return BIGODD;        /* bottom bit 1 */
7585     return BIGEVEN;                     /* bottom bit 0 */
7586     }
7587
7588   if (neg) theInt=-theInt;              /* apply sign */
7589   return theInt;
7590   } /* decGetInt */
7591
7592 /* ------------------------------------------------------------------ */
7593 /* decDecap -- decapitate the coefficient of a number                 */
7594 /*                                                                    */
7595 /*   dn   is the number to be decapitated                             */
7596 /*   drop is the number of digits to be removed from the left of dn;  */
7597 /*     this must be <= dn->digits (if equal, the coefficient is       */
7598 /*     set to 0)                                                      */
7599 /*                                                                    */
7600 /* Returns dn; dn->digits will be <= the initial digits less drop     */
7601 /* (after removing drop digits there may be leading zero digits       */
7602 /* which will also be removed).  Only dn->lsu and dn->digits change.  */
7603 /* ------------------------------------------------------------------ */
7604 static decNumber *decDecap(decNumber *dn, Int drop) {
7605   Unit *msu;                            /* -> target cut point */
7606   Int cut;                              /* work */
7607   if (drop>=dn->digits) {               /* losing the whole thing */
7608     #if DECCHECK
7609     if (drop>dn->digits)
7610       printf("decDecap called with drop>digits [%ld>%ld]\n",
7611              (LI)drop, (LI)dn->digits);
7612     #endif
7613     dn->lsu[0]=0;
7614     dn->digits=1;
7615     return dn;
7616     }
7617   msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu */
7618   cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu */
7619   if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits */
7620   /* that may have left leading zero digits, so do a proper count... */
7621   dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7622   return dn;
7623   } /* decDecap */
7624
7625 /* ------------------------------------------------------------------ */
7626 /* decBiStr -- compare string with pairwise options                   */
7627 /*                                                                    */
7628 /*   targ is the string to compare                                    */
7629 /*   str1 is one of the strings to compare against (length may be 0)  */
7630 /*   str2 is the other; it must be the same length as str1            */
7631 /*                                                                    */
7632 /*   returns 1 if strings compare equal, (that is, it is the same     */
7633 /*   length as str1 and str2, and each character of targ is in either */
7634 /*   str1 or str2 in the corresponding position), or 0 otherwise      */
7635 /*                                                                    */
7636 /* This is used for generic caseless compare, including the awkward   */
7637 /* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7638 /*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7639 /* ------------------------------------------------------------------ */
7640 static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7641   for (;;targ++, str1++, str2++) {
7642     if (*targ!=*str1 && *targ!=*str2) return 0;
7643     /* *targ has a match in one (or both, if terminator) */
7644     if (*targ=='\0') break;
7645     } /* forever */
7646   return 1;
7647   } /* decBiStr */
7648
7649 /* ------------------------------------------------------------------ */
7650 /* decNaNs -- handle NaN operand or operands                          */
7651 /*                                                                    */
7652 /*   res     is the result number                                     */
7653 /*   lhs     is the first operand                                     */
7654 /*   rhs     is the second operand, or NULL if none                   */
7655 /*   context is used to limit payload length                          */
7656 /*   status  contains the current status                              */
7657 /*   returns res in case convenient                                   */
7658 /*                                                                    */
7659 /* Called when one or both operands is a NaN, and propagates the      */
7660 /* appropriate result to res.  When an sNaN is found, it is changed   */
7661 /* to a qNaN and Invalid operation is set.                            */
7662 /* ------------------------------------------------------------------ */
7663 static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7664                            const decNumber *rhs, decContext *set,
7665                            uInt *status) {
7666   /* This decision tree ends up with LHS being the source pointer, */
7667   /* and status updated if need be */
7668   if (lhs->bits & DECSNAN)
7669     *status|=DEC_Invalid_operation | DEC_sNaN;
7670    else if (rhs==NULL);
7671    else if (rhs->bits & DECSNAN) {
7672     lhs=rhs;
7673     *status|=DEC_Invalid_operation | DEC_sNaN;
7674     }
7675    else if (lhs->bits & DECNAN);
7676    else lhs=rhs;
7677
7678   /* propagate the payload */
7679   if (lhs->digits<=set->digits) decNumberCopy(res, lhs); /* easy */
7680    else { /* too long */
7681     const Unit *ul;
7682     Unit *ur, *uresp1;
7683     /* copy safe number of units, then decapitate */
7684     res->bits=lhs->bits;                /* need sign etc. */
7685     uresp1=res->lsu+D2U(set->digits);
7686     for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7687     res->digits=D2U(set->digits)*DECDPUN;
7688     /* maybe still too long */
7689     if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7690     }
7691
7692   res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while */
7693   res->bits|=DECNAN;          /* .. preserving sign */
7694   res->exponent=0;            /* clean exponent */
7695                               /* [coefficient was copied/decapitated] */
7696   return res;
7697   } /* decNaNs */
7698
7699 /* ------------------------------------------------------------------ */
7700 /* decStatus -- apply non-zero status                                 */
7701 /*                                                                    */
7702 /*   dn     is the number to set if error                             */
7703 /*   status contains the current status (not yet in context)          */
7704 /*   set    is the context                                            */
7705 /*                                                                    */
7706 /* If the status is an error status, the number is set to a NaN,      */
7707 /* unless the error was an overflow, divide-by-zero, or underflow,    */
7708 /* in which case the number will have already been set.               */
7709 /*                                                                    */
7710 /* The context status is then updated with the new status.  Note that */
7711 /* this may raise a signal, so control may never return from this     */
7712 /* routine (hence resources must be recovered before it is called).   */
7713 /* ------------------------------------------------------------------ */
7714 static void decStatus(decNumber *dn, uInt status, decContext *set) {
7715   if (status & DEC_NaNs) {              /* error status -> NaN */
7716     /* if cause was an sNaN, clear and propagate [NaN is already set up] */
7717     if (status & DEC_sNaN) status&=~DEC_sNaN;
7718      else {
7719       decNumberZero(dn);                /* other error: clean throughout */
7720       dn->bits=DECNAN;                  /* and make a quiet NaN */
7721       }
7722     }
7723   decContextSetStatus(set, status);     /* [may not return] */
7724   return;
7725   } /* decStatus */
7726
7727 /* ------------------------------------------------------------------ */
7728 /* decGetDigits -- count digits in a Units array                      */
7729 /*                                                                    */
7730 /*   uar is the Unit array holding the number (this is often an       */
7731 /*          accumulator of some sort)                                 */
7732 /*   len is the length of the array in units [>=1]                    */
7733 /*                                                                    */
7734 /*   returns the number of (significant) digits in the array          */
7735 /*                                                                    */
7736 /* All leading zeros are excluded, except the last if the array has   */
7737 /* only zero Units.                                                   */
7738 /* ------------------------------------------------------------------ */
7739 /* This may be called twice during some operations. */
7740 static Int decGetDigits(Unit *uar, Int len) {
7741   Unit *up=uar+(len-1);            /* -> msu */
7742   Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu */
7743   #if DECDPUN>4
7744   uInt const *pow;                 /* work */
7745   #endif
7746                                    /* (at least 1 in final msu) */
7747   #if DECCHECK
7748   if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7749   #endif
7750
7751   for (; up>=uar; up--) {
7752     if (*up==0) {                  /* unit is all 0s */
7753       if (digits==1) break;        /* a zero has one digit */
7754       digits-=DECDPUN;             /* adjust for 0 unit */
7755       continue;}
7756     /* found the first (most significant) non-zero Unit */
7757     #if DECDPUN>1                  /* not done yet */
7758     if (*up<10) break;             /* is 1-9 */
7759     digits++;
7760     #if DECDPUN>2                  /* not done yet */
7761     if (*up<100) break;            /* is 10-99 */
7762     digits++;
7763     #if DECDPUN>3                  /* not done yet */
7764     if (*up<1000) break;           /* is 100-999 */
7765     digits++;
7766     #if DECDPUN>4                  /* count the rest ... */
7767     for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7768     #endif
7769     #endif
7770     #endif
7771     #endif
7772     break;
7773     } /* up */
7774   return digits;
7775   } /* decGetDigits */
7776
7777 #if DECTRACE | DECCHECK
7778 /* ------------------------------------------------------------------ */
7779 /* decNumberShow -- display a number [debug aid]                      */
7780 /*   dn is the number to show                                         */
7781 /*                                                                    */
7782 /* Shows: sign, exponent, coefficient (msu first), digits             */
7783 /*    or: sign, special-value                                         */
7784 /* ------------------------------------------------------------------ */
7785 /* this is public so other modules can use it */
7786 void decNumberShow(const decNumber *dn) {
7787   const Unit *up;                  /* work */
7788   uInt u, d;                       /* .. */
7789   Int cut;                         /* .. */
7790   char isign='+';                  /* main sign */
7791   if (dn==NULL) {
7792     printf("NULL\n");
7793     return;}
7794   if (decNumberIsNegative(dn)) isign='-';
7795   printf(" >> %c ", isign);
7796   if (dn->bits&DECSPECIAL) {       /* Is a special value */
7797     if (decNumberIsInfinite(dn)) printf("Infinity");
7798      else {                                  /* a NaN */
7799       if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN */
7800        else printf("NaN");
7801       }
7802     /* if coefficient and exponent are 0, no more to do */
7803     if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7804       printf("\n");
7805       return;}
7806     /* drop through to report other information */
7807     printf(" ");
7808     }
7809
7810   /* now carefully display the coefficient */
7811   up=dn->lsu+D2U(dn->digits)-1;         /* msu */
7812   printf("%ld", (LI)*up);
7813   for (up=up-1; up>=dn->lsu; up--) {
7814     u=*up;
7815     printf(":");
7816     for (cut=DECDPUN-1; cut>=0; cut--) {
7817       d=u/powers[cut];
7818       u-=d*powers[cut];
7819       printf("%ld", (LI)d);
7820       } /* cut */
7821     } /* up */
7822   if (dn->exponent!=0) {
7823     char esign='+';
7824     if (dn->exponent<0) esign='-';
7825     printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7826     }
7827   printf(" [%ld]\n", (LI)dn->digits);
7828   } /* decNumberShow */
7829 #endif
7830
7831 #if DECTRACE || DECCHECK
7832 /* ------------------------------------------------------------------ */
7833 /* decDumpAr -- display a unit array [debug/check aid]                */
7834 /*   name is a single-character tag name                              */
7835 /*   ar   is the array to display                                     */
7836 /*   len  is the length of the array in Units                         */
7837 /* ------------------------------------------------------------------ */
7838 static void decDumpAr(char name, const Unit *ar, Int len) {
7839   Int i;
7840   const char *spec;
7841   #if DECDPUN==9
7842     spec="%09d ";
7843   #elif DECDPUN==8
7844     spec="%08d ";
7845   #elif DECDPUN==7
7846     spec="%07d ";
7847   #elif DECDPUN==6
7848     spec="%06d ";
7849   #elif DECDPUN==5
7850     spec="%05d ";
7851   #elif DECDPUN==4
7852     spec="%04d ";
7853   #elif DECDPUN==3
7854     spec="%03d ";
7855   #elif DECDPUN==2
7856     spec="%02d ";
7857   #else
7858     spec="%d ";
7859   #endif
7860   printf("  :%c: ", name);
7861   for (i=len-1; i>=0; i--) {
7862     if (i==len-1) printf("%ld ", (LI)ar[i]);
7863      else printf(spec, ar[i]);
7864     }
7865   printf("\n");
7866   return;}
7867 #endif
7868
7869 #if DECCHECK
7870 /* ------------------------------------------------------------------ */
7871 /* decCheckOperands -- check operand(s) to a routine                  */
7872 /*   res is the result structure (not checked; it will be set to      */
7873 /*          quiet NaN if error found (and it is not NULL))            */
7874 /*   lhs is the first operand (may be DECUNRESU)                      */
7875 /*   rhs is the second (may be DECUNUSED)                             */
7876 /*   set is the context (may be DECUNCONT)                            */
7877 /*   returns 0 if both operands, and the context are clean, or 1      */
7878 /*     otherwise (in which case the context will show an error,       */
7879 /*     unless NULL).  Note that res is not cleaned; caller should     */
7880 /*     handle this so res=NULL case is safe.                          */
7881 /* The caller is expected to abandon immediately if 1 is returned.    */
7882 /* ------------------------------------------------------------------ */
7883 static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7884                              const decNumber *rhs, decContext *set) {
7885   Flag bad=0;
7886   if (set==NULL) {                 /* oops; hopeless */
7887     #if DECTRACE || DECVERB
7888     printf("Reference to context is NULL.\n");
7889     #endif
7890     bad=1;
7891     return 1;}
7892    else if (set!=DECUNCONT
7893      && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7894     bad=1;
7895     #if DECTRACE || DECVERB
7896     printf("Bad context [digits=%ld round=%ld].\n",
7897            (LI)set->digits, (LI)set->round);
7898     #endif
7899     }
7900    else {
7901     if (res==NULL) {
7902       bad=1;
7903       #if DECTRACE
7904       /* this one not DECVERB as standard tests include NULL */
7905       printf("Reference to result is NULL.\n");
7906       #endif
7907       }
7908     if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7909     if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7910     }
7911   if (bad) {
7912     if (set!=DECUNCONT) decContextSetStatus(set, DEC_Invalid_operation);
7913     if (res!=DECUNRESU && res!=NULL) {
7914       decNumberZero(res);
7915       res->bits=DECNAN;       /* qNaN */
7916       }
7917     }
7918   return bad;
7919   } /* decCheckOperands */
7920
7921 /* ------------------------------------------------------------------ */
7922 /* decCheckNumber -- check a number                                   */
7923 /*   dn is the number to check                                        */
7924 /*   returns 0 if the number is clean, or 1 otherwise                 */
7925 /*                                                                    */
7926 /* The number is considered valid if it could be a result from some   */
7927 /* operation in some valid context.                                   */
7928 /* ------------------------------------------------------------------ */
7929 static Flag decCheckNumber(const decNumber *dn) {
7930   const Unit *up;             /* work */
7931   uInt maxuint;               /* .. */
7932   Int ae, d, digits;          /* .. */
7933   Int emin, emax;             /* .. */
7934
7935   if (dn==NULL) {             /* hopeless */
7936     #if DECTRACE
7937     /* this one not DECVERB as standard tests include NULL */
7938     printf("Reference to decNumber is NULL.\n");
7939     #endif
7940     return 1;}
7941
7942   /* check special values */
7943   if (dn->bits & DECSPECIAL) {
7944     if (dn->exponent!=0) {
7945       #if DECTRACE || DECVERB
7946       printf("Exponent %ld (not 0) for a special value [%02x].\n",
7947              (LI)dn->exponent, dn->bits);
7948       #endif
7949       return 1;}
7950
7951     /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only */
7952     if (decNumberIsInfinite(dn)) {
7953       if (dn->digits!=1) {
7954         #if DECTRACE || DECVERB
7955         printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7956         #endif
7957         return 1;}
7958       if (*dn->lsu!=0) {
7959         #if DECTRACE || DECVERB
7960         printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7961         #endif
7962         decDumpAr('I', dn->lsu, D2U(dn->digits));
7963         return 1;}
7964       } /* Inf */
7965     /* 2002.12.26: negative NaNs can now appear through proposed IEEE */
7966     /*             concrete formats (decimal64, etc.). */
7967     return 0;
7968     }
7969
7970   /* check the coefficient */
7971   if (dn->digits<1 || dn->digits>DECNUMMAXP) {
7972     #if DECTRACE || DECVERB
7973     printf("Digits %ld in number.\n", (LI)dn->digits);
7974     #endif
7975     return 1;}
7976
7977   d=dn->digits;
7978
7979   for (up=dn->lsu; d>0; up++) {
7980     if (d>DECDPUN) maxuint=DECDPUNMAX;
7981      else {                   /* reached the msu */
7982       maxuint=powers[d]-1;
7983       if (dn->digits>1 && *up<powers[d-1]) {
7984         #if DECTRACE || DECVERB
7985         printf("Leading 0 in number.\n");
7986         decNumberShow(dn);
7987         #endif
7988         return 1;}
7989       }
7990     if (*up>maxuint) {
7991       #if DECTRACE || DECVERB
7992       printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
7993               (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
7994       #endif
7995       return 1;}
7996     d-=DECDPUN;
7997     }
7998
7999   /* check the exponent.  Note that input operands can have exponents */
8000   /* which are out of the set->emin/set->emax and set->digits range */
8001   /* (just as they can have more digits than set->digits). */
8002   ae=dn->exponent+dn->digits-1;    /* adjusted exponent */
8003   emax=DECNUMMAXE;
8004   emin=DECNUMMINE;
8005   digits=DECNUMMAXP;
8006   if (ae<emin-(digits-1)) {
8007     #if DECTRACE || DECVERB
8008     printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8009     decNumberShow(dn);
8010     #endif
8011     return 1;}
8012   if (ae>+emax) {
8013     #if DECTRACE || DECVERB
8014     printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8015     decNumberShow(dn);
8016     #endif
8017     return 1;}
8018
8019   return 0;              /* it's OK */
8020   } /* decCheckNumber */
8021
8022 /* ------------------------------------------------------------------ */
8023 /* decCheckInexact -- check a normal finite inexact result has digits */
8024 /*   dn is the number to check                                        */
8025 /*   set is the context (for status and precision)                    */
8026 /*   sets Invalid operation, etc., if some digits are missing         */
8027 /* [this check is not made for DECSUBSET compilation or when          */
8028 /* subnormal is not set]                                              */
8029 /* ------------------------------------------------------------------ */
8030 static void decCheckInexact(const decNumber *dn, decContext *set) {
8031   #if !DECSUBSET && DECEXTFLAG
8032     if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8033      && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8034       #if DECTRACE || DECVERB
8035       printf("Insufficient digits [%ld] on normal Inexact result.\n",
8036              (LI)dn->digits);
8037       decNumberShow(dn);
8038       #endif
8039       decContextSetStatus(set, DEC_Invalid_operation);
8040       }
8041   #else
8042     /* next is a noop for quiet compiler */
8043     if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8044   #endif
8045   return;
8046   } /* decCheckInexact */
8047 #endif
8048
8049 #if DECALLOC
8050 #undef malloc
8051 #undef free
8052 /* ------------------------------------------------------------------ */
8053 /* decMalloc -- accountable allocation routine                        */
8054 /*   n is the number of bytes to allocate                             */
8055 /*                                                                    */
8056 /* Semantics is the same as the stdlib malloc routine, but bytes      */
8057 /* allocated are accounted for globally, and corruption fences are    */
8058 /* added before and after the 'actual' storage.                       */
8059 /* ------------------------------------------------------------------ */
8060 /* This routine allocates storage with an extra twelve bytes; 8 are   */
8061 /* at the start and hold:                                             */
8062 /*   0-3 the original length requested                                */
8063 /*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8064 /* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8065 /* ------------------------------------------------------------------ */
8066 static void *decMalloc(size_t n) {
8067   uInt  size=n+12;                 /* true size */
8068   void  *alloc;                    /* -> allocated storage */
8069   uInt  *j;                        /* work */
8070   uByte *b, *b0;                   /* .. */
8071
8072   alloc=malloc(size);              /* -> allocated storage */
8073   if (alloc==NULL) return NULL;    /* out of strorage */
8074   b0=(uByte *)alloc;               /* as bytes */
8075   decAllocBytes+=n;                /* account for storage */
8076   j=(uInt *)alloc;                 /* -> first four bytes */
8077   *j=n;                            /* save n */
8078   /* printf(" alloc ++ dAB: %ld (%d)\n", decAllocBytes, n); */
8079   for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8080   for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8081   return b0+8;                     /* -> play area */
8082   } /* decMalloc */
8083
8084 /* ------------------------------------------------------------------ */
8085 /* decFree -- accountable free routine                                */
8086 /*   alloc is the storage to free                                     */
8087 /*                                                                    */
8088 /* Semantics is the same as the stdlib malloc routine, except that    */
8089 /* the global storage accounting is updated and the fences are        */
8090 /* checked to ensure that no routine has written 'out of bounds'.     */
8091 /* ------------------------------------------------------------------ */
8092 /* This routine first checks that the fences have not been corrupted. */
8093 /* It then frees the storage using the 'truw' storage address (that   */
8094 /* is, offset by 8).                                                  */
8095 /* ------------------------------------------------------------------ */
8096 static void decFree(void *alloc) {
8097   uInt  *j, n;                     /* pointer, original length */
8098   uByte *b, *b0;                   /* work */
8099
8100   if (alloc==NULL) return;         /* allowed; it's a nop */
8101   b0=(uByte *)alloc;               /* as bytes */
8102   b0-=8;                           /* -> true start of storage */
8103   j=(uInt *)b0;                    /* -> first four bytes */
8104   n=*j;                            /* lift */
8105   for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8106     printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8107            b-b0-8, (Int)b0);
8108   for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8109     printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8110            b-b0-8, (Int)b0, n);
8111   free(b0);                        /* drop the storage */
8112   decAllocBytes-=n;                /* account for storage */
8113   /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n); */
8114   } /* decFree */
8115 #define malloc(a) decMalloc(a)
8116 #define free(a) decFree(a)
8117 #endif