1/* ------------------------------------------------------------------ */
2/* Decimal Number arithmetic module                                   */
3/* ------------------------------------------------------------------ */
4/* Copyright (c) IBM Corporation, 2000-2010.  All rights reserved.    */
5/*                                                                    */
6/* This software is made available under the terms of the             */
7/* ICU License -- ICU 1.8.1 and later.                                */
8/*                                                                    */
9/* The description and User's Guide ("The decNumber C Library") for   */
10/* this software is called decNumber.pdf.  This document is           */
11/* available, together with arithmetic and format specifications,     */
12/* testcases, and Web links, on the General Decimal Arithmetic page.  */
13/*                                                                    */
14/* Please send comments, suggestions, and corrections to the author:  */
15/*   mfc@uk.ibm.com                                                   */
16/*   Mike Cowlishaw, IBM Fellow                                       */
17/*   IBM UK, PO Box 31, Birmingham Road, Warwick CV34 5JL, UK         */
18/* ------------------------------------------------------------------ */
19
20/* Modified version, for use from within ICU.
21 *    Renamed public functions, to avoid an unwanted export of the
22 *    standard names from the ICU library.
23 *
24 *    Use ICU's uprv_malloc() and uprv_free()
25 *
26 *    Revert comment syntax to plain C
27 *
28 *    Remove a few compiler warnings.
29 */
30
31/* This module comprises the routines for arbitrary-precision General */
32/* Decimal Arithmetic as defined in the specification which may be    */
33/* found on the General Decimal Arithmetic pages.  It implements both */
34/* the full ('extended') arithmetic and the simpler ('subset')        */
35/* arithmetic.                                                        */
36/*                                                                    */
37/* Usage notes:                                                       */
38/*                                                                    */
39/* 1. This code is ANSI C89 except:                                   */
40/*                                                                    */
41/*    a) C99 line comments (double forward slash) are used.  (Most C  */
42/*       compilers accept these.  If yours does not, a simple script  */
43/*       can be used to convert them to ANSI C comments.)             */
44/*                                                                    */
45/*    b) Types from C99 stdint.h are used.  If you do not have this   */
46/*       header file, see the User's Guide section of the decNumber   */
47/*       documentation; this lists the necessary definitions.         */
48/*                                                                    */
49/*    c) If DECDPUN>4 or DECUSE64=1, the C99 64-bit int64_t and       */
50/*       uint64_t types may be used.  To avoid these, set DECUSE64=0  */
51/*       and DECDPUN<=4 (see documentation).                          */
52/*                                                                    */
53/*    The code also conforms to C99 restrictions; in particular,      */
54/*    strict aliasing rules are observed.                             */
55/*                                                                    */
56/* 2. The decNumber format which this library uses is optimized for   */
57/*    efficient processing of relatively short numbers; in particular */
58/*    it allows the use of fixed sized structures and minimizes copy  */
59/*    and move operations.  It does, however, support arbitrary       */
60/*    precision (up to 999,999,999 digits) and arbitrary exponent     */
61/*    range (Emax in the range 0 through 999,999,999 and Emin in the  */
62/*    range -999,999,999 through 0).  Mathematical functions (for     */
63/*    example decNumberExp) as identified below are restricted more   */
64/*    tightly: digits, emax, and -emin in the context must be <=      */
65/*    DEC_MAX_MATH (999999), and their operand(s) must be within      */
66/*    these bounds.                                                   */
67/*                                                                    */
68/* 3. Logical functions are further restricted; their operands must   */
69/*    be finite, positive, have an exponent of zero, and all digits   */
70/*    must be either 0 or 1.  The result will only contain digits     */
71/*    which are 0 or 1 (and will have exponent=0 and a sign of 0).    */
72/*                                                                    */
73/* 4. Operands to operator functions are never modified unless they   */
74/*    are also specified to be the result number (which is always     */
75/*    permitted).  Other than that case, operands must not overlap.   */
76/*                                                                    */
77/* 5. Error handling: the type of the error is ORed into the status   */
78/*    flags in the current context (decContext structure).  The       */
79/*    SIGFPE signal is then raised if the corresponding trap-enabler  */
80/*    flag in the decContext is set (is 1).                           */
81/*                                                                    */
82/*    It is the responsibility of the caller to clear the status      */
83/*    flags as required.                                              */
84/*                                                                    */
85/*    The result of any routine which returns a number will always    */
86/*    be a valid number (which may be a special value, such as an     */
87/*    Infinity or NaN).                                               */
88/*                                                                    */
89/* 6. The decNumber format is not an exchangeable concrete            */
90/*    representation as it comprises fields which may be machine-     */
91/*    dependent (packed or unpacked, or special length, for example). */
92/*    Canonical conversions to and from strings are provided; other   */
93/*    conversions are available in separate modules.                  */
94/*                                                                    */
95/* 7. Normally, input operands are assumed to be valid.  Set DECCHECK */
96/*    to 1 for extended operand checking (including NULL operands).   */
97/*    Results are undefined if a badly-formed structure (or a NULL    */
98/*    pointer to a structure) is provided, though with DECCHECK       */
99/*    enabled the operator routines are protected against exceptions. */
100/*    (Except if the result pointer is NULL, which is unrecoverable.) */
101/*                                                                    */
102/*    However, the routines will never cause exceptions if they are   */
103/*    given well-formed operands, even if the value of the operands   */
104/*    is inappropriate for the operation and DECCHECK is not set.     */
105/*    (Except for SIGFPE, as and where documented.)                   */
106/*                                                                    */
107/* 8. Subset arithmetic is available only if DECSUBSET is set to 1.   */
108/* ------------------------------------------------------------------ */
109/* Implementation notes for maintenance of this module:               */
110/*                                                                    */
111/* 1. Storage leak protection:  Routines which use malloc are not     */
112/*    permitted to use return for fastpath or error exits (i.e.,      */
113/*    they follow strict structured programming conventions).         */
114/*    Instead they have a do{}while(0); construct surrounding the     */
115/*    code which is protected -- break may be used to exit this.      */
116/*    Other routines can safely use the return statement inline.      */
117/*                                                                    */
118/*    Storage leak accounting can be enabled using DECALLOC.          */
119/*                                                                    */
120/* 2. All loops use the for(;;) construct.  Any do construct does     */
121/*    not loop; it is for allocation protection as just described.    */
122/*                                                                    */
123/* 3. Setting status in the context must always be the very last      */
124/*    action in a routine, as non-0 status may raise a trap and hence */
125/*    the call to set status may not return (if the handler uses long */
126/*    jump).  Therefore all cleanup must be done first.  In general,  */
127/*    to achieve this status is accumulated and is only applied just  */
128/*    before return by calling decContextSetStatus (via decStatus).   */
129/*                                                                    */
130/*    Routines which allocate storage cannot, in general, use the     */
131/*    'top level' routines which could cause a non-returning          */
132/*    transfer of control.  The decXxxxOp routines are safe (do not   */
133/*    call decStatus even if traps are set in the context) and should */
134/*    be used instead (they are also a little faster).                */
135/*                                                                    */
136/* 4. Exponent checking is minimized by allowing the exponent to      */
137/*    grow outside its limits during calculations, provided that      */
138/*    the decFinalize function is called later.  Multiplication and   */
139/*    division, and intermediate calculations in exponentiation,      */
140/*    require more careful checks because of the risk of 31-bit       */
141/*    overflow (the most negative valid exponent is -1999999997, for  */
142/*    a 999999999-digit number with adjusted exponent of -999999999). */
143/*                                                                    */
144/* 5. Rounding is deferred until finalization of results, with any    */
145/*    'off to the right' data being represented as a single digit     */
146/*    residue (in the range -1 through 9).  This avoids any double-   */
147/*    rounding when more than one shortening takes place (for         */
148/*    example, when a result is subnormal).                           */
149/*                                                                    */
150/* 6. The digits count is allowed to rise to a multiple of DECDPUN    */
151/*    during many operations, so whole Units are handled and exact    */
152/*    accounting of digits is not needed.  The correct digits value   */
153/*    is found by decGetDigits, which accounts for leading zeros.     */
154/*    This must be called before any rounding if the number of digits */
155/*    is not known exactly.                                           */
156/*                                                                    */
157/* 7. The multiply-by-reciprocal 'trick' is used for partitioning     */
158/*    numbers up to four digits, using appropriate constants.  This   */
159/*    is not useful for longer numbers because overflow of 32 bits    */
160/*    would lead to 4 multiplies, which is almost as expensive as     */
161/*    a divide (unless a floating-point or 64-bit multiply is         */
162/*    assumed to be available).                                       */
163/*                                                                    */
164/* 8. Unusual abbreviations that may be used in the commentary:       */
165/*      lhs -- left hand side (operand, of an operation)              */
166/*      lsd -- least significant digit (of coefficient)               */
167/*      lsu -- least significant Unit (of coefficient)                */
168/*      msd -- most significant digit (of coefficient)                */
169/*      msi -- most significant item (in an array)                    */
170/*      msu -- most significant Unit (of coefficient)                 */
171/*      rhs -- right hand side (operand, of an operation)             */
172/*      +ve -- positive                                               */
173/*      -ve -- negative                                               */
174/*      **  -- raise to the power                                     */
175/* ------------------------------------------------------------------ */
176
177#include <stdlib.h>                /* for malloc, free, etc.  */
178/*  #include <stdio.h>   */        /* for printf [if needed]  */
179#include <string.h>                /* for strcpy  */
180#include <ctype.h>                 /* for lower  */
181#include "cmemory.h"               /* for uprv_malloc, etc., in ICU */
182#include "decNumber.h"             /* base number library  */
183#include "decNumberLocal.h"        /* decNumber local types, etc.  */
184
185/* Constants */
186/* Public lookup table used by the D2U macro  */
187const uByte d2utable[DECMAXD2U+1]=D2UTABLE;
188
189#define DECVERB     1              /* set to 1 for verbose DECCHECK  */
190#define powers      DECPOWERS      /* old internal name  */
191
192/* Local constants  */
193#define DIVIDE      0x80           /* Divide operators  */
194#define REMAINDER   0x40           /* ..  */
195#define DIVIDEINT   0x20           /* ..  */
196#define REMNEAR     0x10           /* ..  */
197#define COMPARE     0x01           /* Compare operators  */
198#define COMPMAX     0x02           /* ..  */
199#define COMPMIN     0x03           /* ..  */
200#define COMPTOTAL   0x04           /* ..  */
201#define COMPNAN     0x05           /* .. [NaN processing]  */
202#define COMPSIG     0x06           /* .. [signaling COMPARE]  */
203#define COMPMAXMAG  0x07           /* ..  */
204#define COMPMINMAG  0x08           /* ..  */
205
206#define DEC_sNaN     0x40000000    /* local status: sNaN signal  */
207#define BADINT  (Int)0x80000000    /* most-negative Int; error indicator  */
208/* Next two indicate an integer >= 10**6, and its parity (bottom bit)  */
209#define BIGEVEN (Int)0x80000002
210#define BIGODD  (Int)0x80000003
211
212static Unit uarrone[1]={1};   /* Unit array of 1, used for incrementing  */
213
214/* Granularity-dependent code */
215#if DECDPUN<=4
216  #define eInt  Int           /* extended integer  */
217  #define ueInt uInt          /* unsigned extended integer  */
218  /* Constant multipliers for divide-by-power-of five using reciprocal  */
219  /* multiply, after removing powers of 2 by shifting, and final shift  */
220  /* of 17 [we only need up to **4]  */
221  static const uInt multies[]={131073, 26215, 5243, 1049, 210};
222  /* QUOT10 -- macro to return the quotient of unit u divided by 10**n  */
223  #define QUOT10(u, n) ((((uInt)(u)>>(n))*multies[n])>>17)
224#else
225  /* For DECDPUN>4 non-ANSI-89 64-bit types are needed.  */
226  #if !DECUSE64
227    #error decNumber.c: DECUSE64 must be 1 when DECDPUN>4
228  #endif
229  #define eInt  Long          /* extended integer  */
230  #define ueInt uLong         /* unsigned extended integer  */
231#endif
232
233/* Local routines */
234static decNumber * decAddOp(decNumber *, const decNumber *, const decNumber *,
235                              decContext *, uByte, uInt *);
236static Flag        decBiStr(const char *, const char *, const char *);
237static uInt        decCheckMath(const decNumber *, decContext *, uInt *);
238static void        decApplyRound(decNumber *, decContext *, Int, uInt *);
239static Int         decCompare(const decNumber *lhs, const decNumber *rhs, Flag);
240static decNumber * decCompareOp(decNumber *, const decNumber *,
241                              const decNumber *, decContext *,
242                              Flag, uInt *);
243static void        decCopyFit(decNumber *, const decNumber *, decContext *,
244                              Int *, uInt *);
245static decNumber * decDecap(decNumber *, Int);
246static decNumber * decDivideOp(decNumber *, const decNumber *,
247                              const decNumber *, decContext *, Flag, uInt *);
248static decNumber * decExpOp(decNumber *, const decNumber *,
249                              decContext *, uInt *);
250static void        decFinalize(decNumber *, decContext *, Int *, uInt *);
251static Int         decGetDigits(Unit *, Int);
252static Int         decGetInt(const decNumber *);
253static decNumber * decLnOp(decNumber *, const decNumber *,
254                              decContext *, uInt *);
255static decNumber * decMultiplyOp(decNumber *, const decNumber *,
256                              const decNumber *, decContext *,
257                              uInt *);
258static decNumber * decNaNs(decNumber *, const decNumber *,
259                              const decNumber *, decContext *, uInt *);
260static decNumber * decQuantizeOp(decNumber *, const decNumber *,
261                              const decNumber *, decContext *, Flag,
262                              uInt *);
263static void        decReverse(Unit *, Unit *);
264static void        decSetCoeff(decNumber *, decContext *, const Unit *,
265                              Int, Int *, uInt *);
266static void        decSetMaxValue(decNumber *, decContext *);
267static void        decSetOverflow(decNumber *, decContext *, uInt *);
268static void        decSetSubnormal(decNumber *, decContext *, Int *, uInt *);
269static Int         decShiftToLeast(Unit *, Int, Int);
270static Int         decShiftToMost(Unit *, Int, Int);
271static void        decStatus(decNumber *, uInt, decContext *);
272static void        decToString(const decNumber *, char[], Flag);
273static decNumber * decTrim(decNumber *, decContext *, Flag, Flag, Int *);
274static Int         decUnitAddSub(const Unit *, Int, const Unit *, Int, Int,
275                              Unit *, Int);
276static Int         decUnitCompare(const Unit *, Int, const Unit *, Int, Int);
277
278#if !DECSUBSET
279/* decFinish == decFinalize when no subset arithmetic needed */
280#define decFinish(a,b,c,d) decFinalize(a,b,c,d)
281#else
282static void        decFinish(decNumber *, decContext *, Int *, uInt *);
283static decNumber * decRoundOperand(const decNumber *, decContext *, uInt *);
284#endif
285
286/* Local macros */
287/* masked special-values bits  */
288#define SPECIALARG  (rhs->bits & DECSPECIAL)
289#define SPECIALARGS ((lhs->bits | rhs->bits) & DECSPECIAL)
290
291/* For use in ICU */
292#define malloc(a) uprv_malloc(a)
293#define free(a) uprv_free(a)
294
295/* Diagnostic macros, etc. */
296#if DECALLOC
297/* Handle malloc/free accounting.  If enabled, our accountable routines  */
298/* are used; otherwise the code just goes straight to the system malloc  */
299/* and free routines.  */
300#define malloc(a) decMalloc(a)
301#define free(a) decFree(a)
302#define DECFENCE 0x5a              /* corruption detector  */
303/* 'Our' malloc and free:  */
304static void *decMalloc(size_t);
305static void  decFree(void *);
306uInt decAllocBytes=0;              /* count of bytes allocated  */
307/* Note that DECALLOC code only checks for storage buffer overflow.  */
308/* To check for memory leaks, the decAllocBytes variable must be  */
309/* checked to be 0 at appropriate times (e.g., after the test  */
310/* harness completes a set of tests).  This checking may be unreliable  */
311/* if the testing is done in a multi-thread environment.  */
312#endif
313
314#if DECCHECK
315/* Optional checking routines.  Enabling these means that decNumber  */
316/* and decContext operands to operator routines are checked for  */
317/* correctness.  This roughly doubles the execution time of the  */
318/* fastest routines (and adds 600+ bytes), so should not normally be  */
319/* used in 'production'.  */
320/* decCheckInexact is used to check that inexact results have a full  */
321/* complement of digits (where appropriate -- this is not the case  */
322/* for Quantize, for example)  */
323#define DECUNRESU ((decNumber *)(void *)0xffffffff)
324#define DECUNUSED ((const decNumber *)(void *)0xffffffff)
325#define DECUNCONT ((decContext *)(void *)(0xffffffff))
326static Flag decCheckOperands(decNumber *, const decNumber *,
327                             const decNumber *, decContext *);
328static Flag decCheckNumber(const decNumber *);
329static void decCheckInexact(const decNumber *, decContext *);
330#endif
331
332#if DECTRACE || DECCHECK
333/* Optional trace/debugging routines (may or may not be used)  */
334void decNumberShow(const decNumber *);  /* displays the components of a number  */
335static void decDumpAr(char, const Unit *, Int);
336#endif
337
338/* ================================================================== */
339/* Conversions                                                        */
340/* ================================================================== */
341
342/* ------------------------------------------------------------------ */
343/* from-int32 -- conversion from Int or uInt                          */
344/*                                                                    */
345/*  dn is the decNumber to receive the integer                        */
346/*  in or uin is the integer to be converted                          */
347/*  returns dn                                                        */
348/*                                                                    */
349/* No error is possible.                                              */
350/* ------------------------------------------------------------------ */
351U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromInt32(decNumber *dn, Int in) {
352  uInt unsig;
353  if (in>=0) unsig=in;
354   else {                               /* negative (possibly BADINT)  */
355    if (in==BADINT) unsig=(uInt)1073741824*2; /* special case  */
356     else unsig=-in;                    /* invert  */
357    }
358  /* in is now positive  */
359  uprv_decNumberFromUInt32(dn, unsig);
360  if (in<0) dn->bits=DECNEG;            /* sign needed  */
361  return dn;
362  } /* decNumberFromInt32  */
363
364U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromUInt32(decNumber *dn, uInt uin) {
365  Unit *up;                             /* work pointer  */
366  uprv_decNumberZero(dn);                    /* clean  */
367  if (uin==0) return dn;                /* [or decGetDigits bad call]  */
368  for (up=dn->lsu; uin>0; up++) {
369    *up=(Unit)(uin%(DECDPUNMAX+1));
370    uin=uin/(DECDPUNMAX+1);
371    }
372  dn->digits=decGetDigits(dn->lsu, up-dn->lsu);
373  return dn;
374  } /* decNumberFromUInt32  */
375
376/* ------------------------------------------------------------------ */
377/* to-int32 -- conversion to Int or uInt                              */
378/*                                                                    */
379/*  dn is the decNumber to convert                                    */
380/*  set is the context for reporting errors                           */
381/*  returns the converted decNumber, or 0 if Invalid is set           */
382/*                                                                    */
383/* Invalid is set if the decNumber does not have exponent==0 or if    */
384/* it is a NaN, Infinite, or out-of-range.                            */
385/* ------------------------------------------------------------------ */
386U_CAPI Int U_EXPORT2 uprv_decNumberToInt32(const decNumber *dn, decContext *set) {
387  #if DECCHECK
388  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
389  #endif
390
391  /* special or too many digits, or bad exponent  */
392  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0) ; /* bad  */
393   else { /* is a finite integer with 10 or fewer digits  */
394    Int d;                         /* work  */
395    const Unit *up;                /* ..  */
396    uInt hi=0, lo;                 /* ..  */
397    up=dn->lsu;                    /* -> lsu  */
398    lo=*up;                        /* get 1 to 9 digits  */
399    #if DECDPUN>1                  /* split to higher  */
400      hi=lo/10;
401      lo=lo%10;
402    #endif
403    up++;
404    /* collect remaining Units, if any, into hi  */
405    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
406    /* now low has the lsd, hi the remainder  */
407    if (hi>214748364 || (hi==214748364 && lo>7)) { /* out of range?  */
408      /* most-negative is a reprieve  */
409      if (dn->bits&DECNEG && hi==214748364 && lo==8) return 0x80000000;
410      /* bad -- drop through  */
411      }
412     else { /* in-range always  */
413      Int i=X10(hi)+lo;
414      if (dn->bits&DECNEG) return -i;
415      return i;
416      }
417    } /* integer  */
418  uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
419  return 0;
420  } /* decNumberToInt32  */
421
422U_CAPI uInt U_EXPORT2 uprv_decNumberToUInt32(const decNumber *dn, decContext *set) {
423  #if DECCHECK
424  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
425  #endif
426  /* special or too many digits, or bad exponent, or negative (<0)  */
427  if (dn->bits&DECSPECIAL || dn->digits>10 || dn->exponent!=0
428    || (dn->bits&DECNEG && !ISZERO(dn)));                   /* bad  */
429   else { /* is a finite integer with 10 or fewer digits  */
430    Int d;                         /* work  */
431    const Unit *up;                /* ..  */
432    uInt hi=0, lo;                 /* ..  */
433    up=dn->lsu;                    /* -> lsu  */
434    lo=*up;                        /* get 1 to 9 digits  */
435    #if DECDPUN>1                  /* split to higher  */
436      hi=lo/10;
437      lo=lo%10;
438    #endif
439    up++;
440    /* collect remaining Units, if any, into hi  */
441    for (d=DECDPUN; d<dn->digits; up++, d+=DECDPUN) hi+=*up*powers[d-1];
442
443    /* now low has the lsd, hi the remainder  */
444    if (hi>429496729 || (hi==429496729 && lo>5)) ; /* no reprieve possible  */
445     else return X10(hi)+lo;
446    } /* integer  */
447  uprv_decContextSetStatus(set, DEC_Invalid_operation); /* [may not return]  */
448  return 0;
449  } /* decNumberToUInt32  */
450
451/* ------------------------------------------------------------------ */
452/* to-scientific-string -- conversion to numeric string               */
453/* to-engineering-string -- conversion to numeric string              */
454/*                                                                    */
455/*   decNumberToString(dn, string);                                   */
456/*   decNumberToEngString(dn, string);                                */
457/*                                                                    */
458/*  dn is the decNumber to convert                                    */
459/*  string is the string where the result will be laid out            */
460/*                                                                    */
461/*  string must be at least dn->digits+14 characters long             */
462/*                                                                    */
463/*  No error is possible, and no status can be set.                   */
464/* ------------------------------------------------------------------ */
465U_CAPI char * U_EXPORT2 uprv_decNumberToString(const decNumber *dn, char *string){
466  decToString(dn, string, 0);
467  return string;
468  } /* DecNumberToString  */
469
470U_CAPI char * U_EXPORT2 uprv_decNumberToEngString(const decNumber *dn, char *string){
471  decToString(dn, string, 1);
472  return string;
473  } /* DecNumberToEngString  */
474
475/* ------------------------------------------------------------------ */
476/* to-number -- conversion from numeric string                        */
477/*                                                                    */
478/* decNumberFromString -- convert string to decNumber                 */
479/*   dn        -- the number structure to fill                        */
480/*   chars[]   -- the string to convert ('\0' terminated)             */
481/*   set       -- the context used for processing any error,          */
482/*                determining the maximum precision available         */
483/*                (set.digits), determining the maximum and minimum   */
484/*                exponent (set.emax and set.emin), determining if    */
485/*                extended values are allowed, and checking the       */
486/*                rounding mode if overflow occurs or rounding is     */
487/*                needed.                                             */
488/*                                                                    */
489/* The length of the coefficient and the size of the exponent are     */
490/* checked by this routine, so the correct error (Underflow or        */
491/* Overflow) can be reported or rounding applied, as necessary.       */
492/*                                                                    */
493/* If bad syntax is detected, the result will be a quiet NaN.         */
494/* ------------------------------------------------------------------ */
495U_CAPI decNumber * U_EXPORT2 uprv_decNumberFromString(decNumber *dn, const char chars[],
496                                decContext *set) {
497  Int   exponent=0;                /* working exponent [assume 0]  */
498  uByte bits=0;                    /* working flags [assume +ve]  */
499  Unit  *res;                      /* where result will be built  */
500  Unit  resbuff[SD2U(DECBUFFER+9)];/* local buffer in case need temporary  */
501                                   /* [+9 allows for ln() constants]  */
502  Unit  *allocres=NULL;            /* -> allocated result, iff allocated  */
503  Int   d=0;                       /* count of digits found in decimal part  */
504  const char *dotchar=NULL;        /* where dot was found  */
505  const char *cfirst=chars;        /* -> first character of decimal part  */
506  const char *last=NULL;           /* -> last digit of decimal part  */
507  const char *c;                   /* work  */
508  Unit  *up;                       /* ..  */
509  #if DECDPUN>1
510  Int   cut, out;                  /* ..  */
511  #endif
512  Int   residue;                   /* rounding residue  */
513  uInt  status=0;                  /* error code  */
514
515  #if DECCHECK
516  if (decCheckOperands(DECUNRESU, DECUNUSED, DECUNUSED, set))
517    return uprv_decNumberZero(dn);
518  #endif
519
520  do {                             /* status & malloc protection  */
521    for (c=chars;; c++) {          /* -> input character  */
522      if (*c>='0' && *c<='9') {    /* test for Arabic digit  */
523        last=c;
524        d++;                       /* count of real digits  */
525        continue;                  /* still in decimal part  */
526        }
527      if (*c=='.' && dotchar==NULL) { /* first '.'  */
528        dotchar=c;                 /* record offset into decimal part  */
529        if (c==cfirst) cfirst++;   /* first digit must follow  */
530        continue;}
531      if (c==chars) {              /* first in string...  */
532        if (*c=='-') {             /* valid - sign  */
533          cfirst++;
534          bits=DECNEG;
535          continue;}
536        if (*c=='+') {             /* valid + sign  */
537          cfirst++;
538          continue;}
539        }
540      /* *c is not a digit, or a valid +, -, or '.'  */
541      break;
542      } /* c  */
543
544    if (last==NULL) {              /* no digits yet  */
545      status=DEC_Conversion_syntax;/* assume the worst  */
546      if (*c=='\0') break;         /* and no more to come...  */
547      #if DECSUBSET
548      /* if subset then infinities and NaNs are not allowed  */
549      if (!set->extended) break;   /* hopeless  */
550      #endif
551      /* Infinities and NaNs are possible, here  */
552      if (dotchar!=NULL) break;    /* .. unless had a dot  */
553      uprv_decNumberZero(dn);           /* be optimistic  */
554      if (decBiStr(c, "infinity", "INFINITY")
555       || decBiStr(c, "inf", "INF")) {
556        dn->bits=bits | DECINF;
557        status=0;                  /* is OK  */
558        break; /* all done  */
559        }
560      /* a NaN expected  */
561      /* 2003.09.10 NaNs are now permitted to have a sign  */
562      dn->bits=bits | DECNAN;      /* assume simple NaN  */
563      if (*c=='s' || *c=='S') {    /* looks like an sNaN  */
564        c++;
565        dn->bits=bits | DECSNAN;
566        }
567      if (*c!='n' && *c!='N') break;    /* check caseless "NaN"  */
568      c++;
569      if (*c!='a' && *c!='A') break;    /* ..  */
570      c++;
571      if (*c!='n' && *c!='N') break;    /* ..  */
572      c++;
573      /* now either nothing, or nnnn payload, expected  */
574      /* -> start of integer and skip leading 0s [including plain 0]  */
575      for (cfirst=c; *cfirst=='0';) cfirst++;
576      if (*cfirst=='\0') {         /* "NaN" or "sNaN", maybe with all 0s  */
577        status=0;                  /* it's good  */
578        break;                     /* ..  */
579        }
580      /* something other than 0s; setup last and d as usual [no dots]  */
581      for (c=cfirst;; c++, d++) {
582        if (*c<'0' || *c>'9') break; /* test for Arabic digit  */
583        last=c;
584        }
585      if (*c!='\0') break;         /* not all digits  */
586      if (d>set->digits-1) {
587        /* [NB: payload in a decNumber can be full length unless  */
588        /* clamped, in which case can only be digits-1]  */
589        if (set->clamp) break;
590        if (d>set->digits) break;
591        } /* too many digits?  */
592      /* good; drop through to convert the integer to coefficient  */
593      status=0;                    /* syntax is OK  */
594      bits=dn->bits;               /* for copy-back  */
595      } /* last==NULL  */
596
597     else if (*c!='\0') {          /* more to process...  */
598      /* had some digits; exponent is only valid sequence now  */
599      Flag nege;                   /* 1=negative exponent  */
600      const char *firstexp;        /* -> first significant exponent digit  */
601      status=DEC_Conversion_syntax;/* assume the worst  */
602      if (*c!='e' && *c!='E') break;
603      /* Found 'e' or 'E' -- now process explicit exponent */
604      /* 1998.07.11: sign no longer required  */
605      nege=0;
606      c++;                         /* to (possible) sign  */
607      if (*c=='-') {nege=1; c++;}
608       else if (*c=='+') c++;
609      if (*c=='\0') break;
610
611      for (; *c=='0' && *(c+1)!='\0';) c++;  /* strip insignificant zeros  */
612      firstexp=c;                            /* save exponent digit place  */
613      for (; ;c++) {
614        if (*c<'0' || *c>'9') break;         /* not a digit  */
615        exponent=X10(exponent)+(Int)*c-(Int)'0';
616        } /* c  */
617      /* if not now on a '\0', *c must not be a digit  */
618      if (*c!='\0') break;
619
620      /* (this next test must be after the syntax checks)  */
621      /* if it was too long the exponent may have wrapped, so check  */
622      /* carefully and set it to a certain overflow if wrap possible  */
623      if (c>=firstexp+9+1) {
624        if (c>firstexp+9+1 || *firstexp>'1') exponent=DECNUMMAXE*2;
625        /* [up to 1999999999 is OK, for example 1E-1000000998]  */
626        }
627      if (nege) exponent=-exponent;     /* was negative  */
628      status=0;                         /* is OK  */
629      } /* stuff after digits  */
630
631    /* Here when whole string has been inspected; syntax is good  */
632    /* cfirst->first digit (never dot), last->last digit (ditto)  */
633
634    /* strip leading zeros/dot [leave final 0 if all 0's]  */
635    if (*cfirst=='0') {                 /* [cfirst has stepped over .]  */
636      for (c=cfirst; c<last; c++, cfirst++) {
637        if (*c=='.') continue;          /* ignore dots  */
638        if (*c!='0') break;             /* non-zero found  */
639        d--;                            /* 0 stripped  */
640        } /* c  */
641      #if DECSUBSET
642      /* make a rapid exit for easy zeros if !extended  */
643      if (*cfirst=='0' && !set->extended) {
644        uprv_decNumberZero(dn);              /* clean result  */
645        break;                          /* [could be return]  */
646        }
647      #endif
648      } /* at least one leading 0  */
649
650    /* Handle decimal point...  */
651    if (dotchar!=NULL && dotchar<last)  /* non-trailing '.' found?  */
652      exponent-=(last-dotchar);         /* adjust exponent  */
653    /* [we can now ignore the .]  */
654
655    /* OK, the digits string is good.  Assemble in the decNumber, or in  */
656    /* a temporary units array if rounding is needed  */
657    if (d<=set->digits) res=dn->lsu;    /* fits into supplied decNumber  */
658     else {                             /* rounding needed  */
659      Int needbytes=D2U(d)*sizeof(Unit);/* bytes needed  */
660      res=resbuff;                      /* assume use local buffer  */
661      if (needbytes>(Int)sizeof(resbuff)) { /* too big for local  */
662        allocres=(Unit *)malloc(needbytes);
663        if (allocres==NULL) {status|=DEC_Insufficient_storage; break;}
664        res=allocres;
665        }
666      }
667    /* res now -> number lsu, buffer, or allocated storage for Unit array  */
668
669    /* Place the coefficient into the selected Unit array  */
670    /* [this is often 70% of the cost of this function when DECDPUN>1]  */
671    #if DECDPUN>1
672    out=0;                         /* accumulator  */
673    up=res+D2U(d)-1;               /* -> msu  */
674    cut=d-(up-res)*DECDPUN;        /* digits in top unit  */
675    for (c=cfirst;; c++) {         /* along the digits  */
676      if (*c=='.') continue;       /* ignore '.' [don't decrement cut]  */
677      out=X10(out)+(Int)*c-(Int)'0';
678      if (c==last) break;          /* done [never get to trailing '.']  */
679      cut--;
680      if (cut>0) continue;         /* more for this unit  */
681      *up=(Unit)out;               /* write unit  */
682      up--;                        /* prepare for unit below..  */
683      cut=DECDPUN;                 /* ..  */
684      out=0;                       /* ..  */
685      } /* c  */
686    *up=(Unit)out;                 /* write lsu  */
687
688    #else
689    /* DECDPUN==1  */
690    up=res;                        /* -> lsu  */
691    for (c=last; c>=cfirst; c--) { /* over each character, from least  */
692      if (*c=='.') continue;       /* ignore . [don't step up]  */
693      *up=(Unit)((Int)*c-(Int)'0');
694      up++;
695      } /* c  */
696    #endif
697
698    dn->bits=bits;
699    dn->exponent=exponent;
700    dn->digits=d;
701
702    /* if not in number (too long) shorten into the number  */
703    if (d>set->digits) {
704      residue=0;
705      decSetCoeff(dn, set, res, d, &residue, &status);
706      /* always check for overflow or subnormal and round as needed  */
707      decFinalize(dn, set, &residue, &status);
708      }
709     else { /* no rounding, but may still have overflow or subnormal  */
710      /* [these tests are just for performance; finalize repeats them]  */
711      if ((dn->exponent-1<set->emin-dn->digits)
712       || (dn->exponent-1>set->emax-set->digits)) {
713        residue=0;
714        decFinalize(dn, set, &residue, &status);
715        }
716      }
717    /* decNumberShow(dn);  */
718    } while(0);                         /* [for break]  */
719
720  if (allocres!=NULL) free(allocres);   /* drop any storage used  */
721  if (status!=0) decStatus(dn, status, set);
722  return dn;
723  } /* decNumberFromString */
724
725/* ================================================================== */
726/* Operators                                                          */
727/* ================================================================== */
728
729/* ------------------------------------------------------------------ */
730/* decNumberAbs -- absolute value operator                            */
731/*                                                                    */
732/*   This computes C = abs(A)                                         */
733/*                                                                    */
734/*   res is C, the result.  C may be A                                */
735/*   rhs is A                                                         */
736/*   set is the context                                               */
737/*                                                                    */
738/* See also decNumberCopyAbs for a quiet bitwise version of this.     */
739/* C must have space for set->digits digits.                          */
740/* ------------------------------------------------------------------ */
741/* This has the same effect as decNumberPlus unless A is negative,    */
742/* in which case it has the same effect as decNumberMinus.            */
743/* ------------------------------------------------------------------ */
744U_CAPI decNumber * U_EXPORT2 uprv_decNumberAbs(decNumber *res, const decNumber *rhs,
745                         decContext *set) {
746  decNumber dzero;                      /* for 0  */
747  uInt status=0;                        /* accumulator  */
748
749  #if DECCHECK
750  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
751  #endif
752
753  uprv_decNumberZero(&dzero);                /* set 0  */
754  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
755  decAddOp(res, &dzero, rhs, set, (uByte)(rhs->bits & DECNEG), &status);
756  if (status!=0) decStatus(res, status, set);
757  #if DECCHECK
758  decCheckInexact(res, set);
759  #endif
760  return res;
761  } /* decNumberAbs  */
762
763/* ------------------------------------------------------------------ */
764/* decNumberAdd -- add two Numbers                                    */
765/*                                                                    */
766/*   This computes C = A + B                                          */
767/*                                                                    */
768/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
769/*   lhs is A                                                         */
770/*   rhs is B                                                         */
771/*   set is the context                                               */
772/*                                                                    */
773/* C must have space for set->digits digits.                          */
774/* ------------------------------------------------------------------ */
775/* This just calls the routine shared with Subtract                   */
776U_CAPI decNumber * U_EXPORT2 uprv_decNumberAdd(decNumber *res, const decNumber *lhs,
777                         const decNumber *rhs, decContext *set) {
778  uInt status=0;                        /* accumulator  */
779  decAddOp(res, lhs, rhs, set, 0, &status);
780  if (status!=0) decStatus(res, status, set);
781  #if DECCHECK
782  decCheckInexact(res, set);
783  #endif
784  return res;
785  } /* decNumberAdd  */
786
787/* ------------------------------------------------------------------ */
788/* decNumberAnd -- AND two Numbers, digitwise                         */
789/*                                                                    */
790/*   This computes C = A & B                                          */
791/*                                                                    */
792/*   res is C, the result.  C may be A and/or B (e.g., X=X&X)         */
793/*   lhs is A                                                         */
794/*   rhs is B                                                         */
795/*   set is the context (used for result length and error report)     */
796/*                                                                    */
797/* C must have space for set->digits digits.                          */
798/*                                                                    */
799/* Logical function restrictions apply (see above); a NaN is          */
800/* returned with Invalid_operation if a restriction is violated.      */
801/* ------------------------------------------------------------------ */
802U_CAPI decNumber * U_EXPORT2 uprv_decNumberAnd(decNumber *res, const decNumber *lhs,
803                         const decNumber *rhs, decContext *set) {
804  const Unit *ua, *ub;                  /* -> operands  */
805  const Unit *msua, *msub;              /* -> operand msus  */
806  Unit *uc,  *msuc;                     /* -> result and its msu  */
807  Int   msudigs;                        /* digits in res msu  */
808  #if DECCHECK
809  if (decCheckOperands(res, lhs, rhs, set)) return res;
810  #endif
811
812  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
813   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
814    decStatus(res, DEC_Invalid_operation, set);
815    return res;
816    }
817
818  /* operands are valid  */
819  ua=lhs->lsu;                          /* bottom-up  */
820  ub=rhs->lsu;                          /* ..  */
821  uc=res->lsu;                          /* ..  */
822  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
823  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
824  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
825  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
826  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
827    Unit a, b;                          /* extract units  */
828    if (ua>msua) a=0;
829     else a=*ua;
830    if (ub>msub) b=0;
831     else b=*ub;
832    *uc=0;                              /* can now write back  */
833    if (a|b) {                          /* maybe 1 bits to examine  */
834      Int i, j;
835      *uc=0;                            /* can now write back  */
836      /* This loop could be unrolled and/or use BIN2BCD tables  */
837      for (i=0; i<DECDPUN; i++) {
838        if (a&b&1) *uc=*uc+(Unit)powers[i];  /* effect AND  */
839        j=a%10;
840        a=a/10;
841        j|=b%10;
842        b=b/10;
843        if (j>1) {
844          decStatus(res, DEC_Invalid_operation, set);
845          return res;
846          }
847        if (uc==msuc && i==msudigs-1) break; /* just did final digit  */
848        } /* each digit  */
849      } /* both OK  */
850    } /* each unit  */
851  /* [here uc-1 is the msu of the result]  */
852  res->digits=decGetDigits(res->lsu, uc-res->lsu);
853  res->exponent=0;                      /* integer  */
854  res->bits=0;                          /* sign=0  */
855  return res;  /* [no status to set]  */
856  } /* decNumberAnd  */
857
858/* ------------------------------------------------------------------ */
859/* decNumberCompare -- compare two Numbers                            */
860/*                                                                    */
861/*   This computes C = A ? B                                          */
862/*                                                                    */
863/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
864/*   lhs is A                                                         */
865/*   rhs is B                                                         */
866/*   set is the context                                               */
867/*                                                                    */
868/* C must have space for one digit (or NaN).                          */
869/* ------------------------------------------------------------------ */
870U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompare(decNumber *res, const decNumber *lhs,
871                             const decNumber *rhs, decContext *set) {
872  uInt status=0;                        /* accumulator  */
873  decCompareOp(res, lhs, rhs, set, COMPARE, &status);
874  if (status!=0) decStatus(res, status, set);
875  return res;
876  } /* decNumberCompare  */
877
878/* ------------------------------------------------------------------ */
879/* decNumberCompareSignal -- compare, signalling on all NaNs          */
880/*                                                                    */
881/*   This computes C = A ? B                                          */
882/*                                                                    */
883/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
884/*   lhs is A                                                         */
885/*   rhs is B                                                         */
886/*   set is the context                                               */
887/*                                                                    */
888/* C must have space for one digit (or NaN).                          */
889/* ------------------------------------------------------------------ */
890U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareSignal(decNumber *res, const decNumber *lhs,
891                                   const decNumber *rhs, decContext *set) {
892  uInt status=0;                        /* accumulator  */
893  decCompareOp(res, lhs, rhs, set, COMPSIG, &status);
894  if (status!=0) decStatus(res, status, set);
895  return res;
896  } /* decNumberCompareSignal  */
897
898/* ------------------------------------------------------------------ */
899/* decNumberCompareTotal -- compare two Numbers, using total ordering */
900/*                                                                    */
901/*   This computes C = A ? B, under total ordering                    */
902/*                                                                    */
903/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
904/*   lhs is A                                                         */
905/*   rhs is B                                                         */
906/*   set is the context                                               */
907/*                                                                    */
908/* C must have space for one digit; the result will always be one of  */
909/* -1, 0, or 1.                                                       */
910/* ------------------------------------------------------------------ */
911U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotal(decNumber *res, const decNumber *lhs,
912                                  const decNumber *rhs, decContext *set) {
913  uInt status=0;                        /* accumulator  */
914  decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
915  if (status!=0) decStatus(res, status, set);
916  return res;
917  } /* decNumberCompareTotal  */
918
919/* ------------------------------------------------------------------ */
920/* decNumberCompareTotalMag -- compare, total ordering of magnitudes  */
921/*                                                                    */
922/*   This computes C = |A| ? |B|, under total ordering                */
923/*                                                                    */
924/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
925/*   lhs is A                                                         */
926/*   rhs is B                                                         */
927/*   set is the context                                               */
928/*                                                                    */
929/* C must have space for one digit; the result will always be one of  */
930/* -1, 0, or 1.                                                       */
931/* ------------------------------------------------------------------ */
932U_CAPI decNumber * U_EXPORT2 uprv_decNumberCompareTotalMag(decNumber *res, const decNumber *lhs,
933                                     const decNumber *rhs, decContext *set) {
934  uInt status=0;                   /* accumulator  */
935  uInt needbytes;                  /* for space calculations  */
936  decNumber bufa[D2N(DECBUFFER+1)];/* +1 in case DECBUFFER=0  */
937  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
938  decNumber bufb[D2N(DECBUFFER+1)];
939  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
940  decNumber *a, *b;                /* temporary pointers  */
941
942  #if DECCHECK
943  if (decCheckOperands(res, lhs, rhs, set)) return res;
944  #endif
945
946  do {                                  /* protect allocated storage  */
947    /* if either is negative, take a copy and absolute  */
948    if (decNumberIsNegative(lhs)) {     /* lhs<0  */
949      a=bufa;
950      needbytes=sizeof(decNumber)+(D2U(lhs->digits)-1)*sizeof(Unit);
951      if (needbytes>sizeof(bufa)) {     /* need malloc space  */
952        allocbufa=(decNumber *)malloc(needbytes);
953        if (allocbufa==NULL) {          /* hopeless -- abandon  */
954          status|=DEC_Insufficient_storage;
955          break;}
956        a=allocbufa;                    /* use the allocated space  */
957        }
958      uprv_decNumberCopy(a, lhs);            /* copy content  */
959      a->bits&=~DECNEG;                 /* .. and clear the sign  */
960      lhs=a;                            /* use copy from here on  */
961      }
962    if (decNumberIsNegative(rhs)) {     /* rhs<0  */
963      b=bufb;
964      needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
965      if (needbytes>sizeof(bufb)) {     /* need malloc space  */
966        allocbufb=(decNumber *)malloc(needbytes);
967        if (allocbufb==NULL) {          /* hopeless -- abandon  */
968          status|=DEC_Insufficient_storage;
969          break;}
970        b=allocbufb;                    /* use the allocated space  */
971        }
972      uprv_decNumberCopy(b, rhs);            /* copy content  */
973      b->bits&=~DECNEG;                 /* .. and clear the sign  */
974      rhs=b;                            /* use copy from here on  */
975      }
976    decCompareOp(res, lhs, rhs, set, COMPTOTAL, &status);
977    } while(0);                         /* end protected  */
978
979  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
980  if (allocbufb!=NULL) free(allocbufb); /* ..  */
981  if (status!=0) decStatus(res, status, set);
982  return res;
983  } /* decNumberCompareTotalMag  */
984
985/* ------------------------------------------------------------------ */
986/* decNumberDivide -- divide one number by another                    */
987/*                                                                    */
988/*   This computes C = A / B                                          */
989/*                                                                    */
990/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
991/*   lhs is A                                                         */
992/*   rhs is B                                                         */
993/*   set is the context                                               */
994/*                                                                    */
995/* C must have space for set->digits digits.                          */
996/* ------------------------------------------------------------------ */
997U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivide(decNumber *res, const decNumber *lhs,
998                            const decNumber *rhs, decContext *set) {
999  uInt status=0;                        /* accumulator  */
1000  decDivideOp(res, lhs, rhs, set, DIVIDE, &status);
1001  if (status!=0) decStatus(res, status, set);
1002  #if DECCHECK
1003  decCheckInexact(res, set);
1004  #endif
1005  return res;
1006  } /* decNumberDivide  */
1007
1008/* ------------------------------------------------------------------ */
1009/* decNumberDivideInteger -- divide and return integer quotient       */
1010/*                                                                    */
1011/*   This computes C = A # B, where # is the integer divide operator  */
1012/*                                                                    */
1013/*   res is C, the result.  C may be A and/or B (e.g., X=X#X)         */
1014/*   lhs is A                                                         */
1015/*   rhs is B                                                         */
1016/*   set is the context                                               */
1017/*                                                                    */
1018/* C must have space for set->digits digits.                          */
1019/* ------------------------------------------------------------------ */
1020U_CAPI decNumber * U_EXPORT2 uprv_decNumberDivideInteger(decNumber *res, const decNumber *lhs,
1021                                   const decNumber *rhs, decContext *set) {
1022  uInt status=0;                        /* accumulator  */
1023  decDivideOp(res, lhs, rhs, set, DIVIDEINT, &status);
1024  if (status!=0) decStatus(res, status, set);
1025  return res;
1026  } /* decNumberDivideInteger  */
1027
1028/* ------------------------------------------------------------------ */
1029/* decNumberExp -- exponentiation                                     */
1030/*                                                                    */
1031/*   This computes C = exp(A)                                         */
1032/*                                                                    */
1033/*   res is C, the result.  C may be A                                */
1034/*   rhs is A                                                         */
1035/*   set is the context; note that rounding mode has no effect        */
1036/*                                                                    */
1037/* C must have space for set->digits digits.                          */
1038/*                                                                    */
1039/* Mathematical function restrictions apply (see above); a NaN is     */
1040/* returned with Invalid_operation if a restriction is violated.      */
1041/*                                                                    */
1042/* Finite results will always be full precision and Inexact, except   */
1043/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
1044/*                                                                    */
1045/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1046/* almost always be correctly rounded, but may be up to 1 ulp in      */
1047/* error in rare cases.                                               */
1048/* ------------------------------------------------------------------ */
1049/* This is a wrapper for decExpOp which can handle the slightly wider */
1050/* (double) range needed by Ln (which has to be able to calculate     */
1051/* exp(-a) where a can be the tiniest number (Ntiny).                 */
1052/* ------------------------------------------------------------------ */
1053U_CAPI decNumber * U_EXPORT2 uprv_decNumberExp(decNumber *res, const decNumber *rhs,
1054                         decContext *set) {
1055  uInt status=0;                        /* accumulator  */
1056  #if DECSUBSET
1057  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1058  #endif
1059
1060  #if DECCHECK
1061  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1062  #endif
1063
1064  /* Check restrictions; these restrictions ensure that if h=8 (see  */
1065  /* decExpOp) then the result will either overflow or underflow to 0.  */
1066  /* Other math functions restrict the input range, too, for inverses.  */
1067  /* If not violated then carry out the operation.  */
1068  if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1069    #if DECSUBSET
1070    if (!set->extended) {
1071      /* reduce operand and set lostDigits status, as needed  */
1072      if (rhs->digits>set->digits) {
1073        allocrhs=decRoundOperand(rhs, set, &status);
1074        if (allocrhs==NULL) break;
1075        rhs=allocrhs;
1076        }
1077      }
1078    #endif
1079    decExpOp(res, rhs, set, &status);
1080    } while(0);                         /* end protected  */
1081
1082  #if DECSUBSET
1083  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1084  #endif
1085  /* apply significant status  */
1086  if (status!=0) decStatus(res, status, set);
1087  #if DECCHECK
1088  decCheckInexact(res, set);
1089  #endif
1090  return res;
1091  } /* decNumberExp  */
1092
1093/* ------------------------------------------------------------------ */
1094/* decNumberFMA -- fused multiply add                                 */
1095/*                                                                    */
1096/*   This computes D = (A * B) + C with only one rounding             */
1097/*                                                                    */
1098/*   res is D, the result.  D may be A or B or C (e.g., X=FMA(X,X,X)) */
1099/*   lhs is A                                                         */
1100/*   rhs is B                                                         */
1101/*   fhs is C [far hand side]                                         */
1102/*   set is the context                                               */
1103/*                                                                    */
1104/* Mathematical function restrictions apply (see above); a NaN is     */
1105/* returned with Invalid_operation if a restriction is violated.      */
1106/*                                                                    */
1107/* C must have space for set->digits digits.                          */
1108/* ------------------------------------------------------------------ */
1109U_CAPI decNumber * U_EXPORT2 uprv_decNumberFMA(decNumber *res, const decNumber *lhs,
1110                         const decNumber *rhs, const decNumber *fhs,
1111                         decContext *set) {
1112  uInt status=0;                   /* accumulator  */
1113  decContext dcmul;                /* context for the multiplication  */
1114  uInt needbytes;                  /* for space calculations  */
1115  decNumber bufa[D2N(DECBUFFER*2+1)];
1116  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1117  decNumber *acc;                  /* accumulator pointer  */
1118  decNumber dzero;                 /* work  */
1119
1120  #if DECCHECK
1121  if (decCheckOperands(res, lhs, rhs, set)) return res;
1122  if (decCheckOperands(res, fhs, DECUNUSED, set)) return res;
1123  #endif
1124
1125  do {                                  /* protect allocated storage  */
1126    #if DECSUBSET
1127    if (!set->extended) {               /* [undefined if subset]  */
1128      status|=DEC_Invalid_operation;
1129      break;}
1130    #endif
1131    /* Check math restrictions [these ensure no overflow or underflow]  */
1132    if ((!decNumberIsSpecial(lhs) && decCheckMath(lhs, set, &status))
1133     || (!decNumberIsSpecial(rhs) && decCheckMath(rhs, set, &status))
1134     || (!decNumberIsSpecial(fhs) && decCheckMath(fhs, set, &status))) break;
1135    /* set up context for multiply  */
1136    dcmul=*set;
1137    dcmul.digits=lhs->digits+rhs->digits; /* just enough  */
1138    /* [The above may be an over-estimate for subset arithmetic, but that's OK]  */
1139    dcmul.emax=DEC_MAX_EMAX;            /* effectively unbounded ..  */
1140    dcmul.emin=DEC_MIN_EMIN;            /* [thanks to Math restrictions]  */
1141    /* set up decNumber space to receive the result of the multiply  */
1142    acc=bufa;                           /* may fit  */
1143    needbytes=sizeof(decNumber)+(D2U(dcmul.digits)-1)*sizeof(Unit);
1144    if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1145      allocbufa=(decNumber *)malloc(needbytes);
1146      if (allocbufa==NULL) {            /* hopeless -- abandon  */
1147        status|=DEC_Insufficient_storage;
1148        break;}
1149      acc=allocbufa;                    /* use the allocated space  */
1150      }
1151    /* multiply with extended range and necessary precision  */
1152    /*printf("emin=%ld\n", dcmul.emin);  */
1153    decMultiplyOp(acc, lhs, rhs, &dcmul, &status);
1154    /* Only Invalid operation (from sNaN or Inf * 0) is possible in  */
1155    /* status; if either is seen than ignore fhs (in case it is  */
1156    /* another sNaN) and set acc to NaN unless we had an sNaN  */
1157    /* [decMultiplyOp leaves that to caller]  */
1158    /* Note sNaN has to go through addOp to shorten payload if  */
1159    /* necessary  */
1160    if ((status&DEC_Invalid_operation)!=0) {
1161      if (!(status&DEC_sNaN)) {         /* but be true invalid  */
1162        uprv_decNumberZero(res);             /* acc not yet set  */
1163        res->bits=DECNAN;
1164        break;
1165        }
1166      uprv_decNumberZero(&dzero);            /* make 0 (any non-NaN would do)  */
1167      fhs=&dzero;                       /* use that  */
1168      }
1169    #if DECCHECK
1170     else { /* multiply was OK  */
1171      if (status!=0) printf("Status=%08lx after FMA multiply\n", (LI)status);
1172      }
1173    #endif
1174    /* add the third operand and result -> res, and all is done  */
1175    decAddOp(res, acc, fhs, set, 0, &status);
1176    } while(0);                         /* end protected  */
1177
1178  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1179  if (status!=0) decStatus(res, status, set);
1180  #if DECCHECK
1181  decCheckInexact(res, set);
1182  #endif
1183  return res;
1184  } /* decNumberFMA  */
1185
1186/* ------------------------------------------------------------------ */
1187/* decNumberInvert -- invert a Number, digitwise                      */
1188/*                                                                    */
1189/*   This computes C = ~A                                             */
1190/*                                                                    */
1191/*   res is C, the result.  C may be A (e.g., X=~X)                   */
1192/*   rhs is A                                                         */
1193/*   set is the context (used for result length and error report)     */
1194/*                                                                    */
1195/* C must have space for set->digits digits.                          */
1196/*                                                                    */
1197/* Logical function restrictions apply (see above); a NaN is          */
1198/* returned with Invalid_operation if a restriction is violated.      */
1199/* ------------------------------------------------------------------ */
1200U_CAPI decNumber * U_EXPORT2 uprv_decNumberInvert(decNumber *res, const decNumber *rhs,
1201                            decContext *set) {
1202  const Unit *ua, *msua;                /* -> operand and its msu  */
1203  Unit  *uc, *msuc;                     /* -> result and its msu  */
1204  Int   msudigs;                        /* digits in res msu  */
1205  #if DECCHECK
1206  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1207  #endif
1208
1209  if (rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1210    decStatus(res, DEC_Invalid_operation, set);
1211    return res;
1212    }
1213  /* operand is valid  */
1214  ua=rhs->lsu;                          /* bottom-up  */
1215  uc=res->lsu;                          /* ..  */
1216  msua=ua+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1217  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1218  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1219  for (; uc<=msuc; ua++, uc++) {        /* Unit loop  */
1220    Unit a;                             /* extract unit  */
1221    Int  i, j;                          /* work  */
1222    if (ua>msua) a=0;
1223     else a=*ua;
1224    *uc=0;                              /* can now write back  */
1225    /* always need to examine all bits in rhs  */
1226    /* This loop could be unrolled and/or use BIN2BCD tables  */
1227    for (i=0; i<DECDPUN; i++) {
1228      if ((~a)&1) *uc=*uc+(Unit)powers[i];   /* effect INVERT  */
1229      j=a%10;
1230      a=a/10;
1231      if (j>1) {
1232        decStatus(res, DEC_Invalid_operation, set);
1233        return res;
1234        }
1235      if (uc==msuc && i==msudigs-1) break;   /* just did final digit  */
1236      } /* each digit  */
1237    } /* each unit  */
1238  /* [here uc-1 is the msu of the result]  */
1239  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1240  res->exponent=0;                      /* integer  */
1241  res->bits=0;                          /* sign=0  */
1242  return res;  /* [no status to set]  */
1243  } /* decNumberInvert  */
1244
1245/* ------------------------------------------------------------------ */
1246/* decNumberLn -- natural logarithm                                   */
1247/*                                                                    */
1248/*   This computes C = ln(A)                                          */
1249/*                                                                    */
1250/*   res is C, the result.  C may be A                                */
1251/*   rhs is A                                                         */
1252/*   set is the context; note that rounding mode has no effect        */
1253/*                                                                    */
1254/* C must have space for set->digits digits.                          */
1255/*                                                                    */
1256/* Notable cases:                                                     */
1257/*   A<0 -> Invalid                                                   */
1258/*   A=0 -> -Infinity (Exact)                                         */
1259/*   A=+Infinity -> +Infinity (Exact)                                 */
1260/*   A=1 exactly -> 0 (Exact)                                         */
1261/*                                                                    */
1262/* Mathematical function restrictions apply (see above); a NaN is     */
1263/* returned with Invalid_operation if a restriction is violated.      */
1264/*                                                                    */
1265/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1266/* almost always be correctly rounded, but may be up to 1 ulp in      */
1267/* error in rare cases.                                               */
1268/* ------------------------------------------------------------------ */
1269/* This is a wrapper for decLnOp which can handle the slightly wider  */
1270/* (+11) range needed by Ln, Log10, etc. (which may have to be able   */
1271/* to calculate at p+e+2).                                            */
1272/* ------------------------------------------------------------------ */
1273U_CAPI decNumber * U_EXPORT2 uprv_decNumberLn(decNumber *res, const decNumber *rhs,
1274                        decContext *set) {
1275  uInt status=0;                   /* accumulator  */
1276  #if DECSUBSET
1277  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1278  #endif
1279
1280  #if DECCHECK
1281  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1282  #endif
1283
1284  /* Check restrictions; this is a math function; if not violated  */
1285  /* then carry out the operation.  */
1286  if (!decCheckMath(rhs, set, &status)) do { /* protect allocation  */
1287    #if DECSUBSET
1288    if (!set->extended) {
1289      /* reduce operand and set lostDigits status, as needed  */
1290      if (rhs->digits>set->digits) {
1291        allocrhs=decRoundOperand(rhs, set, &status);
1292        if (allocrhs==NULL) break;
1293        rhs=allocrhs;
1294        }
1295      /* special check in subset for rhs=0  */
1296      if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1297        status|=DEC_Invalid_operation;
1298        break;}
1299      } /* extended=0  */
1300    #endif
1301    decLnOp(res, rhs, set, &status);
1302    } while(0);                         /* end protected  */
1303
1304  #if DECSUBSET
1305  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
1306  #endif
1307  /* apply significant status  */
1308  if (status!=0) decStatus(res, status, set);
1309  #if DECCHECK
1310  decCheckInexact(res, set);
1311  #endif
1312  return res;
1313  } /* decNumberLn  */
1314
1315/* ------------------------------------------------------------------ */
1316/* decNumberLogB - get adjusted exponent, by 754 rules                */
1317/*                                                                    */
1318/*   This computes C = adjustedexponent(A)                            */
1319/*                                                                    */
1320/*   res is C, the result.  C may be A                                */
1321/*   rhs is A                                                         */
1322/*   set is the context, used only for digits and status              */
1323/*                                                                    */
1324/* C must have space for 10 digits (A might have 10**9 digits and     */
1325/* an exponent of +999999999, or one digit and an exponent of         */
1326/* -1999999999).                                                      */
1327/*                                                                    */
1328/* This returns the adjusted exponent of A after (in theory) padding  */
1329/* with zeros on the right to set->digits digits while keeping the    */
1330/* same value.  The exponent is not limited by emin/emax.             */
1331/*                                                                    */
1332/* Notable cases:                                                     */
1333/*   A<0 -> Use |A|                                                   */
1334/*   A=0 -> -Infinity (Division by zero)                              */
1335/*   A=Infinite -> +Infinity (Exact)                                  */
1336/*   A=1 exactly -> 0 (Exact)                                         */
1337/*   NaNs are propagated as usual                                     */
1338/* ------------------------------------------------------------------ */
1339U_CAPI decNumber * U_EXPORT2 uprv_decNumberLogB(decNumber *res, const decNumber *rhs,
1340                          decContext *set) {
1341  uInt status=0;                   /* accumulator  */
1342
1343  #if DECCHECK
1344  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1345  #endif
1346
1347  /* NaNs as usual; Infinities return +Infinity; 0->oops  */
1348  if (decNumberIsNaN(rhs)) decNaNs(res, rhs, NULL, set, &status);
1349   else if (decNumberIsInfinite(rhs)) uprv_decNumberCopyAbs(res, rhs);
1350   else if (decNumberIsZero(rhs)) {
1351    uprv_decNumberZero(res);                 /* prepare for Infinity  */
1352    res->bits=DECNEG|DECINF;            /* -Infinity  */
1353    status|=DEC_Division_by_zero;       /* as per 754  */
1354    }
1355   else { /* finite non-zero  */
1356    Int ae=rhs->exponent+rhs->digits-1; /* adjusted exponent  */
1357    uprv_decNumberFromInt32(res, ae);        /* lay it out  */
1358    }
1359
1360  if (status!=0) decStatus(res, status, set);
1361  return res;
1362  } /* decNumberLogB  */
1363
1364/* ------------------------------------------------------------------ */
1365/* decNumberLog10 -- logarithm in base 10                             */
1366/*                                                                    */
1367/*   This computes C = log10(A)                                       */
1368/*                                                                    */
1369/*   res is C, the result.  C may be A                                */
1370/*   rhs is A                                                         */
1371/*   set is the context; note that rounding mode has no effect        */
1372/*                                                                    */
1373/* C must have space for set->digits digits.                          */
1374/*                                                                    */
1375/* Notable cases:                                                     */
1376/*   A<0 -> Invalid                                                   */
1377/*   A=0 -> -Infinity (Exact)                                         */
1378/*   A=+Infinity -> +Infinity (Exact)                                 */
1379/*   A=10**n (if n is an integer) -> n (Exact)                        */
1380/*                                                                    */
1381/* Mathematical function restrictions apply (see above); a NaN is     */
1382/* returned with Invalid_operation if a restriction is violated.      */
1383/*                                                                    */
1384/* An Inexact result is rounded using DEC_ROUND_HALF_EVEN; it will    */
1385/* almost always be correctly rounded, but may be up to 1 ulp in      */
1386/* error in rare cases.                                               */
1387/* ------------------------------------------------------------------ */
1388/* This calculates ln(A)/ln(10) using appropriate precision.  For     */
1389/* ln(A) this is the max(p, rhs->digits + t) + 3, where p is the      */
1390/* requested digits and t is the number of digits in the exponent     */
1391/* (maximum 6).  For ln(10) it is p + 3; this is often handled by the */
1392/* fastpath in decLnOp.  The final division is done to the requested  */
1393/* precision.                                                         */
1394/* ------------------------------------------------------------------ */
1395#pragma clang diagnostic push
1396#pragma clang diagnostic ignored "-Warray-bounds"
1397U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1398                          decContext *set) {
1399  uInt status=0, ignore=0;         /* status accumulators  */
1400  uInt needbytes;                  /* for space calculations  */
1401  Int p;                           /* working precision  */
1402  Int t;                           /* digits in exponent of A  */
1403
1404  /* buffers for a and b working decimals  */
1405  /* (adjustment calculator, same size)  */
1406  decNumber bufa[D2N(DECBUFFER+2)];
1407  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1408  decNumber *a=bufa;               /* temporary a  */
1409  decNumber bufb[D2N(DECBUFFER+2)];
1410  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
1411  decNumber *b=bufb;               /* temporary b  */
1412  decNumber bufw[D2N(10)];         /* working 2-10 digit number  */
1413  decNumber *w=bufw;               /* ..  */
1414  #if DECSUBSET
1415  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1416  #endif
1417
1418  decContext aset;                 /* working context  */
1419
1420  #if DECCHECK
1421  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1422  #endif
1423
1424  /* Check restrictions; this is a math function; if not violated  */
1425  /* then carry out the operation.  */
1426  if (!decCheckMath(rhs, set, &status)) do { /* protect malloc  */
1427    #if DECSUBSET
1428    if (!set->extended) {
1429      /* reduce operand and set lostDigits status, as needed  */
1430      if (rhs->digits>set->digits) {
1431        allocrhs=decRoundOperand(rhs, set, &status);
1432        if (allocrhs==NULL) break;
1433        rhs=allocrhs;
1434        }
1435      /* special check in subset for rhs=0  */
1436      if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1437        status|=DEC_Invalid_operation;
1438        break;}
1439      } /* extended=0  */
1440    #endif
1441
1442    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
1443
1444    /* handle exact powers of 10; only check if +ve finite  */
1445    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1446      Int residue=0;               /* (no residue)  */
1447      uInt copystat=0;             /* clean status  */
1448
1449      /* round to a single digit...  */
1450      aset.digits=1;
1451      decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten  */
1452      /* if exact and the digit is 1, rhs is a power of 10  */
1453      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1454        /* the exponent, conveniently, is the power of 10; making  */
1455        /* this the result needs a little care as it might not fit,  */
1456        /* so first convert it into the working number, and then move  */
1457        /* to res  */
1458        uprv_decNumberFromInt32(w, w->exponent);
1459        residue=0;
1460        decCopyFit(res, w, set, &residue, &status); /* copy & round  */
1461        decFinish(res, set, &residue, &status);     /* cleanup/set flags  */
1462        break;
1463        } /* not a power of 10  */
1464      } /* not a candidate for exact  */
1465
1466    /* simplify the information-content calculation to use 'total  */
1467    /* number of digits in a, including exponent' as compared to the  */
1468    /* requested digits, as increasing this will only rarely cost an  */
1469    /* iteration in ln(a) anyway  */
1470    t=6;                                /* it can never be >6  */
1471
1472    /* allocate space when needed...  */
1473    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1474    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1475    if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1476      allocbufa=(decNumber *)malloc(needbytes);
1477      if (allocbufa==NULL) {            /* hopeless -- abandon  */
1478        status|=DEC_Insufficient_storage;
1479        break;}
1480      a=allocbufa;                      /* use the allocated space  */
1481      }
1482    aset.digits=p;                      /* as calculated  */
1483    aset.emax=DEC_MAX_MATH;             /* usual bounds  */
1484    aset.emin=-DEC_MAX_MATH;            /* ..  */
1485    aset.clamp=0;                       /* and no concrete format  */
1486    decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs)  */
1487
1488    /* skip the division if the result so far is infinite, NaN, or  */
1489    /* zero, or there was an error; note NaN from sNaN needs copy  */
1490    if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1491    if (a->bits&DECSPECIAL || ISZERO(a)) {
1492      uprv_decNumberCopy(res, a);            /* [will fit]  */
1493      break;}
1494
1495    /* for ln(10) an extra 3 digits of precision are needed  */
1496    p=set->digits+3;
1497    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1498    if (needbytes>sizeof(bufb)) {       /* need malloc space  */
1499      allocbufb=(decNumber *)malloc(needbytes);
1500      if (allocbufb==NULL) {            /* hopeless -- abandon  */
1501        status|=DEC_Insufficient_storage;
1502        break;}
1503      b=allocbufb;                      /* use the allocated space  */
1504      }
1505    uprv_decNumberZero(w);                   /* set up 10...  */
1506    #if DECDPUN==1
1507    w->lsu[1]=1; w->lsu[0]=0;           /* ..  */
1508    #else
1509    w->lsu[0]=10;                       /* ..  */
1510    #endif
1511    w->digits=2;                        /* ..  */
1512
1513    aset.digits=p;
1514    decLnOp(b, w, &aset, &ignore);      /* b=ln(10)  */
1515
1516    aset.digits=set->digits;            /* for final divide  */
1517    decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result  */
1518    } while(0);                         /* [for break]  */
1519
1520  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1521  if (allocbufb!=NULL) free(allocbufb); /* ..  */
1522  #if DECSUBSET
1523  if (allocrhs !=NULL) free(allocrhs);  /* ..  */
1524  #endif
1525  /* apply significant status  */
1526  if (status!=0) decStatus(res, status, set);
1527  #if DECCHECK
1528  decCheckInexact(res, set);
1529  #endif
1530  return res;
1531  } /* decNumberLog10  */
1532#pragma clang diagnostic pop
1533
1534/* ------------------------------------------------------------------ */
1535/* decNumberMax -- compare two Numbers and return the maximum         */
1536/*                                                                    */
1537/*   This computes C = A ? B, returning the maximum by 754 rules      */
1538/*                                                                    */
1539/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1540/*   lhs is A                                                         */
1541/*   rhs is B                                                         */
1542/*   set is the context                                               */
1543/*                                                                    */
1544/* C must have space for set->digits digits.                          */
1545/* ------------------------------------------------------------------ */
1546U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1547                         const decNumber *rhs, decContext *set) {
1548  uInt status=0;                        /* accumulator  */
1549  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1550  if (status!=0) decStatus(res, status, set);
1551  #if DECCHECK
1552  decCheckInexact(res, set);
1553  #endif
1554  return res;
1555  } /* decNumberMax  */
1556
1557/* ------------------------------------------------------------------ */
1558/* decNumberMaxMag -- compare and return the maximum by magnitude     */
1559/*                                                                    */
1560/*   This computes C = A ? B, returning the maximum by 754 rules      */
1561/*                                                                    */
1562/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1563/*   lhs is A                                                         */
1564/*   rhs is B                                                         */
1565/*   set is the context                                               */
1566/*                                                                    */
1567/* C must have space for set->digits digits.                          */
1568/* ------------------------------------------------------------------ */
1569U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1570                         const decNumber *rhs, decContext *set) {
1571  uInt status=0;                        /* accumulator  */
1572  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1573  if (status!=0) decStatus(res, status, set);
1574  #if DECCHECK
1575  decCheckInexact(res, set);
1576  #endif
1577  return res;
1578  } /* decNumberMaxMag  */
1579
1580/* ------------------------------------------------------------------ */
1581/* decNumberMin -- compare two Numbers and return the minimum         */
1582/*                                                                    */
1583/*   This computes C = A ? B, returning the minimum by 754 rules      */
1584/*                                                                    */
1585/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1586/*   lhs is A                                                         */
1587/*   rhs is B                                                         */
1588/*   set is the context                                               */
1589/*                                                                    */
1590/* C must have space for set->digits digits.                          */
1591/* ------------------------------------------------------------------ */
1592U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1593                         const decNumber *rhs, decContext *set) {
1594  uInt status=0;                        /* accumulator  */
1595  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1596  if (status!=0) decStatus(res, status, set);
1597  #if DECCHECK
1598  decCheckInexact(res, set);
1599  #endif
1600  return res;
1601  } /* decNumberMin  */
1602
1603/* ------------------------------------------------------------------ */
1604/* decNumberMinMag -- compare and return the minimum by magnitude     */
1605/*                                                                    */
1606/*   This computes C = A ? B, returning the minimum by 754 rules      */
1607/*                                                                    */
1608/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1609/*   lhs is A                                                         */
1610/*   rhs is B                                                         */
1611/*   set is the context                                               */
1612/*                                                                    */
1613/* C must have space for set->digits digits.                          */
1614/* ------------------------------------------------------------------ */
1615U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1616                         const decNumber *rhs, decContext *set) {
1617  uInt status=0;                        /* accumulator  */
1618  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1619  if (status!=0) decStatus(res, status, set);
1620  #if DECCHECK
1621  decCheckInexact(res, set);
1622  #endif
1623  return res;
1624  } /* decNumberMinMag  */
1625
1626/* ------------------------------------------------------------------ */
1627/* decNumberMinus -- prefix minus operator                            */
1628/*                                                                    */
1629/*   This computes C = 0 - A                                          */
1630/*                                                                    */
1631/*   res is C, the result.  C may be A                                */
1632/*   rhs is A                                                         */
1633/*   set is the context                                               */
1634/*                                                                    */
1635/* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1636/* C must have space for set->digits digits.                          */
1637/* ------------------------------------------------------------------ */
1638/* Simply use AddOp for the subtract, which will do the necessary.    */
1639/* ------------------------------------------------------------------ */
1640U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1641                           decContext *set) {
1642  decNumber dzero;
1643  uInt status=0;                        /* accumulator  */
1644
1645  #if DECCHECK
1646  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1647  #endif
1648
1649  uprv_decNumberZero(&dzero);                /* make 0  */
1650  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1651  decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1652  if (status!=0) decStatus(res, status, set);
1653  #if DECCHECK
1654  decCheckInexact(res, set);
1655  #endif
1656  return res;
1657  } /* decNumberMinus  */
1658
1659/* ------------------------------------------------------------------ */
1660/* decNumberNextMinus -- next towards -Infinity                       */
1661/*                                                                    */
1662/*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1663/*                                                                    */
1664/*   res is C, the result.  C may be A                                */
1665/*   rhs is A                                                         */
1666/*   set is the context                                               */
1667/*                                                                    */
1668/* This is a generalization of 754 NextDown.                          */
1669/* ------------------------------------------------------------------ */
1670U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1671                               decContext *set) {
1672  decNumber dtiny;                           /* constant  */
1673  decContext workset=*set;                   /* work  */
1674  uInt status=0;                             /* accumulator  */
1675  #if DECCHECK
1676  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1677  #endif
1678
1679  /* +Infinity is the special case  */
1680  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1681    decSetMaxValue(res, set);                /* is +ve  */
1682    /* there is no status to set  */
1683    return res;
1684    }
1685  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1686  dtiny.lsu[0]=1;                            /* make number that is ..  */
1687  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1688  workset.round=DEC_ROUND_FLOOR;
1689  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1690  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1691  if (status!=0) decStatus(res, status, set);
1692  return res;
1693  } /* decNumberNextMinus  */
1694
1695/* ------------------------------------------------------------------ */
1696/* decNumberNextPlus -- next towards +Infinity                        */
1697/*                                                                    */
1698/*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1699/*                                                                    */
1700/*   res is C, the result.  C may be A                                */
1701/*   rhs is A                                                         */
1702/*   set is the context                                               */
1703/*                                                                    */
1704/* This is a generalization of 754 NextUp.                            */
1705/* ------------------------------------------------------------------ */
1706U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1707                              decContext *set) {
1708  decNumber dtiny;                           /* constant  */
1709  decContext workset=*set;                   /* work  */
1710  uInt status=0;                             /* accumulator  */
1711  #if DECCHECK
1712  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1713  #endif
1714
1715  /* -Infinity is the special case  */
1716  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1717    decSetMaxValue(res, set);
1718    res->bits=DECNEG;                        /* negative  */
1719    /* there is no status to set  */
1720    return res;
1721    }
1722  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1723  dtiny.lsu[0]=1;                            /* make number that is ..  */
1724  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1725  workset.round=DEC_ROUND_CEILING;
1726  decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1727  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1728  if (status!=0) decStatus(res, status, set);
1729  return res;
1730  } /* decNumberNextPlus  */
1731
1732/* ------------------------------------------------------------------ */
1733/* decNumberNextToward -- next towards rhs                            */
1734/*                                                                    */
1735/*   This computes C = A +/- infinitesimal, rounded towards           */
1736/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1737/*   modified during revision but dropped from 754-2008.              */
1738/*                                                                    */
1739/*   res is C, the result.  C may be A or B.                          */
1740/*   lhs is A                                                         */
1741/*   rhs is B                                                         */
1742/*   set is the context                                               */
1743/*                                                                    */
1744/* This is a generalization of 754-1985 NextAfter.                    */
1745/* ------------------------------------------------------------------ */
1746U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1747                                const decNumber *rhs, decContext *set) {
1748  decNumber dtiny;                           /* constant  */
1749  decContext workset=*set;                   /* work  */
1750  Int result;                                /* ..  */
1751  uInt status=0;                             /* accumulator  */
1752  #if DECCHECK
1753  if (decCheckOperands(res, lhs, rhs, set)) return res;
1754  #endif
1755
1756  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1757    decNaNs(res, lhs, rhs, set, &status);
1758    }
1759   else { /* Is numeric, so no chance of sNaN Invalid, etc.  */
1760    result=decCompare(lhs, rhs, 0);     /* sign matters  */
1761    if (result==BADINT) status|=DEC_Insufficient_storage; /* rare  */
1762     else { /* valid compare  */
1763      if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy  */
1764       else { /* differ: need NextPlus or NextMinus  */
1765        uByte sub;                      /* add or subtract  */
1766        if (result<0) {                 /* lhs<rhs, do nextplus  */
1767          /* -Infinity is the special case  */
1768          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1769            decSetMaxValue(res, set);
1770            res->bits=DECNEG;           /* negative  */
1771            return res;                 /* there is no status to set  */
1772            }
1773          workset.round=DEC_ROUND_CEILING;
1774          sub=0;                        /* add, please  */
1775          } /* plus  */
1776         else {                         /* lhs>rhs, do nextminus  */
1777          /* +Infinity is the special case  */
1778          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1779            decSetMaxValue(res, set);
1780            return res;                 /* there is no status to set  */
1781            }
1782          workset.round=DEC_ROUND_FLOOR;
1783          sub=DECNEG;                   /* subtract, please  */
1784          } /* minus  */
1785        uprv_decNumberZero(&dtiny);          /* start with 0  */
1786        dtiny.lsu[0]=1;                 /* make number that is ..  */
1787        dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest  */
1788        decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or -  */
1789        /* turn off exceptions if the result is a normal number  */
1790        /* (including Nmin), otherwise let all status through  */
1791        if (uprv_decNumberIsNormal(res, set)) status=0;
1792        } /* unequal  */
1793      } /* compare OK  */
1794    } /* numeric  */
1795  if (status!=0) decStatus(res, status, set);
1796  return res;
1797  } /* decNumberNextToward  */
1798
1799/* ------------------------------------------------------------------ */
1800/* decNumberOr -- OR two Numbers, digitwise                           */
1801/*                                                                    */
1802/*   This computes C = A | B                                          */
1803/*                                                                    */
1804/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1805/*   lhs is A                                                         */
1806/*   rhs is B                                                         */
1807/*   set is the context (used for result length and error report)     */
1808/*                                                                    */
1809/* C must have space for set->digits digits.                          */
1810/*                                                                    */
1811/* Logical function restrictions apply (see above); a NaN is          */
1812/* returned with Invalid_operation if a restriction is violated.      */
1813/* ------------------------------------------------------------------ */
1814U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1815                        const decNumber *rhs, decContext *set) {
1816  const Unit *ua, *ub;                  /* -> operands  */
1817  const Unit *msua, *msub;              /* -> operand msus  */
1818  Unit  *uc, *msuc;                     /* -> result and its msu  */
1819  Int   msudigs;                        /* digits in res msu  */
1820  #if DECCHECK
1821  if (decCheckOperands(res, lhs, rhs, set)) return res;
1822  #endif
1823
1824  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1825   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1826    decStatus(res, DEC_Invalid_operation, set);
1827    return res;
1828    }
1829  /* operands are valid  */
1830  ua=lhs->lsu;                          /* bottom-up  */
1831  ub=rhs->lsu;                          /* ..  */
1832  uc=res->lsu;                          /* ..  */
1833  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
1834  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1835  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1836  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1837  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
1838    Unit a, b;                          /* extract units  */
1839    if (ua>msua) a=0;
1840     else a=*ua;
1841    if (ub>msub) b=0;
1842     else b=*ub;
1843    *uc=0;                              /* can now write back  */
1844    if (a|b) {                          /* maybe 1 bits to examine  */
1845      Int i, j;
1846      /* This loop could be unrolled and/or use BIN2BCD tables  */
1847      for (i=0; i<DECDPUN; i++) {
1848        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR  */
1849        j=a%10;
1850        a=a/10;
1851        j|=b%10;
1852        b=b/10;
1853        if (j>1) {
1854          decStatus(res, DEC_Invalid_operation, set);
1855          return res;
1856          }
1857        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
1858        } /* each digit  */
1859      } /* non-zero  */
1860    } /* each unit  */
1861  /* [here uc-1 is the msu of the result]  */
1862  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1863  res->exponent=0;                      /* integer  */
1864  res->bits=0;                          /* sign=0  */
1865  return res;  /* [no status to set]  */
1866  } /* decNumberOr  */
1867
1868/* ------------------------------------------------------------------ */
1869/* decNumberPlus -- prefix plus operator                              */
1870/*                                                                    */
1871/*   This computes C = 0 + A                                          */
1872/*                                                                    */
1873/*   res is C, the result.  C may be A                                */
1874/*   rhs is A                                                         */
1875/*   set is the context                                               */
1876/*                                                                    */
1877/* See also decNumberCopy for a quiet bitwise version of this.        */
1878/* C must have space for set->digits digits.                          */
1879/* ------------------------------------------------------------------ */
1880/* This simply uses AddOp; Add will take fast path after preparing A. */
1881/* Performance is a concern here, as this routine is often used to    */
1882/* check operands and apply rounding and overflow/underflow testing.  */
1883/* ------------------------------------------------------------------ */
1884U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1885                          decContext *set) {
1886  decNumber dzero;
1887  uInt status=0;                        /* accumulator  */
1888  #if DECCHECK
1889  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1890  #endif
1891
1892  uprv_decNumberZero(&dzero);                /* make 0  */
1893  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1894  decAddOp(res, &dzero, rhs, set, 0, &status);
1895  if (status!=0) decStatus(res, status, set);
1896  #if DECCHECK
1897  decCheckInexact(res, set);
1898  #endif
1899  return res;
1900  } /* decNumberPlus  */
1901
1902/* ------------------------------------------------------------------ */
1903/* decNumberMultiply -- multiply two Numbers                          */
1904/*                                                                    */
1905/*   This computes C = A x B                                          */
1906/*                                                                    */
1907/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1908/*   lhs is A                                                         */
1909/*   rhs is B                                                         */
1910/*   set is the context                                               */
1911/*                                                                    */
1912/* C must have space for set->digits digits.                          */
1913/* ------------------------------------------------------------------ */
1914U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1915                              const decNumber *rhs, decContext *set) {
1916  uInt status=0;                   /* accumulator  */
1917  decMultiplyOp(res, lhs, rhs, set, &status);
1918  if (status!=0) decStatus(res, status, set);
1919  #if DECCHECK
1920  decCheckInexact(res, set);
1921  #endif
1922  return res;
1923  } /* decNumberMultiply  */
1924
1925/* ------------------------------------------------------------------ */
1926/* decNumberPower -- raise a number to a power                        */
1927/*                                                                    */
1928/*   This computes C = A ** B                                         */
1929/*                                                                    */
1930/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1931/*   lhs is A                                                         */
1932/*   rhs is B                                                         */
1933/*   set is the context                                               */
1934/*                                                                    */
1935/* C must have space for set->digits digits.                          */
1936/*                                                                    */
1937/* Mathematical function restrictions apply (see above); a NaN is     */
1938/* returned with Invalid_operation if a restriction is violated.      */
1939/*                                                                    */
1940/* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1941/* restrictions on A and the context are relaxed to the usual bounds, */
1942/* for compatibility with the earlier (integer power only) version    */
1943/* of this function.                                                  */
1944/*                                                                    */
1945/* When B is an integer, the result may be exact, even if rounded.    */
1946/*                                                                    */
1947/* The final result is rounded according to the context; it will      */
1948/* almost always be correctly rounded, but may be up to 1 ulp in      */
1949/* error in rare cases.                                               */
1950/* ------------------------------------------------------------------ */
1951U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1952                           const decNumber *rhs, decContext *set) {
1953  #if DECSUBSET
1954  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
1955  decNumber *allocrhs=NULL;        /* .., rhs  */
1956  #endif
1957  decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used  */
1958  decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used  */
1959  Int   reqdigits=set->digits;     /* requested DIGITS  */
1960  Int   n;                         /* rhs in binary  */
1961  Flag  rhsint=0;                  /* 1 if rhs is an integer  */
1962  Flag  useint=0;                  /* 1 if can use integer calculation  */
1963  Flag  isoddint=0;                /* 1 if rhs is an integer and odd  */
1964  Int   i;                         /* work  */
1965  #if DECSUBSET
1966  Int   dropped;                   /* ..  */
1967  #endif
1968  uInt  needbytes;                 /* buffer size needed  */
1969  Flag  seenbit;                   /* seen a bit while powering  */
1970  Int   residue=0;                 /* rounding residue  */
1971  uInt  status=0;                  /* accumulators  */
1972  uByte bits=0;                    /* result sign if errors  */
1973  decContext aset;                 /* working context  */
1974  decNumber dnOne;                 /* work value 1...  */
1975  /* local accumulator buffer [a decNumber, with digits+elength+1 digits]  */
1976  decNumber dacbuff[D2N(DECBUFFER+9)];
1977  decNumber *dac=dacbuff;          /* -> result accumulator  */
1978  /* same again for possible 1/lhs calculation  */
1979  decNumber invbuff[D2N(DECBUFFER+9)];
1980
1981  #if DECCHECK
1982  if (decCheckOperands(res, lhs, rhs, set)) return res;
1983  #endif
1984
1985  do {                             /* protect allocated storage  */
1986    #if DECSUBSET
1987    if (!set->extended) { /* reduce operands and set status, as needed  */
1988      if (lhs->digits>reqdigits) {
1989        alloclhs=decRoundOperand(lhs, set, &status);
1990        if (alloclhs==NULL) break;
1991        lhs=alloclhs;
1992        }
1993      if (rhs->digits>reqdigits) {
1994        allocrhs=decRoundOperand(rhs, set, &status);
1995        if (allocrhs==NULL) break;
1996        rhs=allocrhs;
1997        }
1998      }
1999    #endif
2000    /* [following code does not require input rounding]  */
2001
2002    /* handle NaNs and rhs Infinity (lhs infinity is harder)  */
2003    if (SPECIALARGS) {
2004      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs  */
2005        decNaNs(res, lhs, rhs, set, &status);
2006        break;}
2007      if (decNumberIsInfinite(rhs)) {   /* rhs Infinity  */
2008        Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign  */
2009        if (decNumberIsNegative(lhs)    /* lhs<0  */
2010         && !decNumberIsZero(lhs))      /* ..  */
2011          status|=DEC_Invalid_operation;
2012         else {                         /* lhs >=0  */
2013          uprv_decNumberZero(&dnOne);        /* set up 1  */
2014          dnOne.lsu[0]=1;
2015          uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1  */
2016          uprv_decNumberZero(res);           /* prepare for 0/1/Infinity  */
2017          if (decNumberIsNegative(dac)) {    /* lhs<1  */
2018            if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0]  */
2019            }
2020           else if (dac->lsu[0]==0) {        /* lhs=1  */
2021            /* 1**Infinity is inexact, so return fully-padded 1.0000  */
2022            Int shift=set->digits-1;
2023            *res->lsu=1;                     /* was 0, make int 1  */
2024            res->digits=decShiftToMost(res->lsu, 1, shift);
2025            res->exponent=-shift;            /* make 1.0000...  */
2026            status|=DEC_Inexact|DEC_Rounded; /* deemed inexact  */
2027            }
2028           else {                            /* lhs>1  */
2029            if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0]  */
2030            }
2031          } /* lhs>=0  */
2032        break;}
2033      /* [lhs infinity drops through]  */
2034      } /* specials  */
2035
2036    /* Original rhs may be an integer that fits and is in range  */
2037    n=decGetInt(rhs);
2038    if (n!=BADINT) {                    /* it is an integer  */
2039      rhsint=1;                         /* record the fact for 1**n  */
2040      isoddint=(Flag)n&1;               /* [works even if big]  */
2041      if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path?  */
2042        useint=1;                       /* looks good  */
2043      }
2044
2045    if (decNumberIsNegative(lhs)        /* -x ..  */
2046      && isoddint) bits=DECNEG;         /* .. to an odd power  */
2047
2048    /* handle LHS infinity  */
2049    if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled]  */
2050      uByte rbits=rhs->bits;            /* save  */
2051      uprv_decNumberZero(res);               /* prepare  */
2052      if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1  */
2053       else {
2054        /* -Inf**nonint -> error  */
2055        if (!rhsint && decNumberIsNegative(lhs)) {
2056          status|=DEC_Invalid_operation;     /* -Inf**nonint is error  */
2057          break;}
2058        if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n  */
2059        /* [otherwise will be 0 or -0]  */
2060        res->bits=bits;
2061        }
2062      break;}
2063
2064    /* similarly handle LHS zero  */
2065    if (decNumberIsZero(lhs)) {
2066      if (n==0) {                            /* 0**0 => Error  */
2067        #if DECSUBSET
2068        if (!set->extended) {                /* [unless subset]  */
2069          uprv_decNumberZero(res);
2070          *res->lsu=1;                       /* return 1  */
2071          break;}
2072        #endif
2073        status|=DEC_Invalid_operation;
2074        }
2075       else {                                /* 0**x  */
2076        uByte rbits=rhs->bits;               /* save  */
2077        if (rbits & DECNEG) {                /* was a 0**(-n)  */
2078          #if DECSUBSET
2079          if (!set->extended) {              /* [bad if subset]  */
2080            status|=DEC_Invalid_operation;
2081            break;}
2082          #endif
2083          bits|=DECINF;
2084          }
2085        uprv_decNumberZero(res);                  /* prepare  */
2086        /* [otherwise will be 0 or -0]  */
2087        res->bits=bits;
2088        }
2089      break;}
2090
2091    /* here both lhs and rhs are finite; rhs==0 is handled in the  */
2092    /* integer path.  Next handle the non-integer cases  */
2093    if (!useint) {                      /* non-integral rhs  */
2094      /* any -ve lhs is bad, as is either operand or context out of  */
2095      /* bounds  */
2096      if (decNumberIsNegative(lhs)) {
2097        status|=DEC_Invalid_operation;
2098        break;}
2099      if (decCheckMath(lhs, set, &status)
2100       || decCheckMath(rhs, set, &status)) break; /* variable status  */
2101
2102      uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
2103      aset.emax=DEC_MAX_MATH;           /* usual bounds  */
2104      aset.emin=-DEC_MAX_MATH;          /* ..  */
2105      aset.clamp=0;                     /* and no concrete format  */
2106
2107      /* calculate the result using exp(ln(lhs)*rhs), which can  */
2108      /* all be done into the accumulator, dac.  The precision needed  */
2109      /* is enough to contain the full information in the lhs (which  */
2110      /* is the total digits, including exponent), or the requested  */
2111      /* precision, if larger, + 4; 6 is used for the exponent  */
2112      /* maximum length, and this is also used when it is shorter  */
2113      /* than the requested digits as it greatly reduces the >0.5 ulp  */
2114      /* cases at little cost (because Ln doubles digits each  */
2115      /* iteration so a few extra digits rarely causes an extra  */
2116      /* iteration)  */
2117      aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2118      } /* non-integer rhs  */
2119
2120     else { /* rhs is in-range integer  */
2121      if (n==0) {                       /* x**0 = 1  */
2122        /* (0**0 was handled above)  */
2123        uprv_decNumberZero(res);             /* result=1  */
2124        *res->lsu=1;                    /* ..  */
2125        break;}
2126      /* rhs is a non-zero integer  */
2127      if (n<0) n=-n;                    /* use abs(n)  */
2128
2129      aset=*set;                        /* clone the context  */
2130      aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced  */
2131      /* calculate the working DIGITS  */
2132      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2133      #if DECSUBSET
2134      if (!set->extended) aset.digits--;     /* use classic precision  */
2135      #endif
2136      /* it's an error if this is more than can be handled  */
2137      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2138      } /* integer path  */
2139
2140    /* aset.digits is the count of digits for the accumulator needed  */
2141    /* if accumulator is too long for local storage, then allocate  */
2142    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2143    /* [needbytes also used below if 1/lhs needed]  */
2144    if (needbytes>sizeof(dacbuff)) {
2145      allocdac=(decNumber *)malloc(needbytes);
2146      if (allocdac==NULL) {   /* hopeless -- abandon  */
2147        status|=DEC_Insufficient_storage;
2148        break;}
2149      dac=allocdac;           /* use the allocated space  */
2150      }
2151    /* here, aset is set up and accumulator is ready for use  */
2152
2153    if (!useint) {                           /* non-integral rhs  */
2154      /* x ** y; special-case x=1 here as it will otherwise always  */
2155      /* reduce to integer 1; decLnOp has a fastpath which detects  */
2156      /* the case of x=1  */
2157      decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs)  */
2158      /* [no error possible, as lhs 0 already handled]  */
2159      if (ISZERO(dac)) {                     /* x==1, 1.0, etc.  */
2160        /* need to return fully-padded 1.0000 etc., but rhsint->1  */
2161        *dac->lsu=1;                         /* was 0, make int 1  */
2162        if (!rhsint) {                       /* add padding  */
2163          Int shift=set->digits-1;
2164          dac->digits=decShiftToMost(dac->lsu, 1, shift);
2165          dac->exponent=-shift;              /* make 1.0000...  */
2166          status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact  */
2167          }
2168        }
2169       else {
2170        decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs  */
2171        decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac)  */
2172        }
2173      /* and drop through for final rounding  */
2174      } /* non-integer rhs  */
2175
2176     else {                             /* carry on with integer  */
2177      uprv_decNumberZero(dac);               /* acc=1  */
2178      *dac->lsu=1;                      /* ..  */
2179
2180      /* if a negative power the constant 1 is needed, and if not subset  */
2181      /* invert the lhs now rather than inverting the result later  */
2182      if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0]  */
2183        decNumber *inv=invbuff;         /* asssume use fixed buffer  */
2184        uprv_decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later]  */
2185        #if DECSUBSET
2186        if (set->extended) {            /* need to calculate 1/lhs  */
2187        #endif
2188          /* divide lhs into 1, putting result in dac [dac=1/dac]  */
2189          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2190          /* now locate or allocate space for the inverted lhs  */
2191          if (needbytes>sizeof(invbuff)) {
2192            allocinv=(decNumber *)malloc(needbytes);
2193            if (allocinv==NULL) {       /* hopeless -- abandon  */
2194              status|=DEC_Insufficient_storage;
2195              break;}
2196            inv=allocinv;               /* use the allocated space  */
2197            }
2198          /* [inv now points to big-enough buffer or allocated storage]  */
2199          uprv_decNumberCopy(inv, dac);      /* copy the 1/lhs  */
2200          uprv_decNumberCopy(dac, &dnOne);   /* restore acc=1  */
2201          lhs=inv;                      /* .. and go forward with new lhs  */
2202        #if DECSUBSET
2203          }
2204        #endif
2205        }
2206
2207      /* Raise-to-the-power loop...  */
2208      seenbit=0;                   /* set once a 1-bit is encountered  */
2209      for (i=1;;i++){              /* for each bit [top bit ignored]  */
2210        /* abandon if had overflow or terminal underflow  */
2211        if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
2212          if (status&DEC_Overflow || ISZERO(dac)) break;
2213          }
2214        /* [the following two lines revealed an optimizer bug in a C++  */
2215        /* compiler, with symptom: 5**3 -> 25, when n=n+n was used]  */
2216        n=n<<1;                    /* move next bit to testable position  */
2217        if (n<0) {                 /* top bit is set  */
2218          seenbit=1;               /* OK, significant bit seen  */
2219          decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x  */
2220          }
2221        if (i==31) break;          /* that was the last bit  */
2222        if (!seenbit) continue;    /* no need to square 1  */
2223        decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square]  */
2224        } /*i*/ /* 32 bits  */
2225
2226      /* complete internal overflow or underflow processing  */
2227      if (status & (DEC_Overflow|DEC_Underflow)) {
2228        #if DECSUBSET
2229        /* If subset, and power was negative, reverse the kind of -erflow  */
2230        /* [1/x not yet done]  */
2231        if (!set->extended && decNumberIsNegative(rhs)) {
2232          if (status & DEC_Overflow)
2233            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2234           else { /* trickier -- Underflow may or may not be set  */
2235            status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both]  */
2236            status|=DEC_Overflow;
2237            }
2238          }
2239        #endif
2240        dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign  */
2241        /* round subnormals [to set.digits rather than aset.digits]  */
2242        /* or set overflow result similarly as required  */
2243        decFinalize(dac, set, &residue, &status);
2244        uprv_decNumberCopy(res, dac);   /* copy to result (is now OK length)  */
2245        break;
2246        }
2247
2248      #if DECSUBSET
2249      if (!set->extended &&                  /* subset math  */
2250          decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0]  */
2251        /* so divide result into 1 [dac=1/dac]  */
2252        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2253        }
2254      #endif
2255      } /* rhs integer path  */
2256
2257    /* reduce result to the requested length and copy to result  */
2258    decCopyFit(res, dac, set, &residue, &status);
2259    decFinish(res, set, &residue, &status);  /* final cleanup  */
2260    #if DECSUBSET
2261    if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros  */
2262    #endif
2263    } while(0);                         /* end protected  */
2264
2265  if (allocdac!=NULL) free(allocdac);   /* drop any storage used  */
2266  if (allocinv!=NULL) free(allocinv);   /* ..  */
2267  #if DECSUBSET
2268  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
2269  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
2270  #endif
2271  if (status!=0) decStatus(res, status, set);
2272  #if DECCHECK
2273  decCheckInexact(res, set);
2274  #endif
2275  return res;
2276  } /* decNumberPower  */
2277
2278/* ------------------------------------------------------------------ */
2279/* decNumberQuantize -- force exponent to requested value             */
2280/*                                                                    */
2281/*   This computes C = op(A, B), where op adjusts the coefficient     */
2282/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2283/*   of C has exponent of B.  The numerical value of C will equal A,  */
2284/*   except for the effects of any rounding that occurred.            */
2285/*                                                                    */
2286/*   res is C, the result.  C may be A or B                           */
2287/*   lhs is A, the number to adjust                                   */
2288/*   rhs is B, the number with exponent to match                      */
2289/*   set is the context                                               */
2290/*                                                                    */
2291/* C must have space for set->digits digits.                          */
2292/*                                                                    */
2293/* Unless there is an error or the result is infinite, the exponent   */
2294/* after the operation is guaranteed to be equal to that of B.        */
2295/* ------------------------------------------------------------------ */
2296U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2297                              const decNumber *rhs, decContext *set) {
2298  uInt status=0;                        /* accumulator  */
2299  decQuantizeOp(res, lhs, rhs, set, 1, &status);
2300  if (status!=0) decStatus(res, status, set);
2301  return res;
2302  } /* decNumberQuantize  */
2303
2304/* ------------------------------------------------------------------ */
2305/* decNumberReduce -- remove trailing zeros                           */
2306/*                                                                    */
2307/*   This computes C = 0 + A, and normalizes the result               */
2308/*                                                                    */
2309/*   res is C, the result.  C may be A                                */
2310/*   rhs is A                                                         */
2311/*   set is the context                                               */
2312/*                                                                    */
2313/* C must have space for set->digits digits.                          */
2314/* ------------------------------------------------------------------ */
2315/* Previously known as Normalize  */
2316U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2317                               decContext *set) {
2318  return uprv_decNumberReduce(res, rhs, set);
2319  } /* decNumberNormalize  */
2320
2321U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2322                            decContext *set) {
2323  #if DECSUBSET
2324  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2325  #endif
2326  uInt status=0;                   /* as usual  */
2327  Int  residue=0;                  /* as usual  */
2328  Int  dropped;                    /* work  */
2329
2330  #if DECCHECK
2331  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2332  #endif
2333
2334  do {                             /* protect allocated storage  */
2335    #if DECSUBSET
2336    if (!set->extended) {
2337      /* reduce operand and set lostDigits status, as needed  */
2338      if (rhs->digits>set->digits) {
2339        allocrhs=decRoundOperand(rhs, set, &status);
2340        if (allocrhs==NULL) break;
2341        rhs=allocrhs;
2342        }
2343      }
2344    #endif
2345    /* [following code does not require input rounding]  */
2346
2347    /* Infinities copy through; NaNs need usual treatment  */
2348    if (decNumberIsNaN(rhs)) {
2349      decNaNs(res, rhs, NULL, set, &status);
2350      break;
2351      }
2352
2353    /* reduce result to the requested length and copy to result  */
2354    decCopyFit(res, rhs, set, &residue, &status); /* copy & round  */
2355    decFinish(res, set, &residue, &status);       /* cleanup/set flags  */
2356    decTrim(res, set, 1, 0, &dropped);            /* normalize in place  */
2357                                                  /* [may clamp]  */
2358    } while(0);                              /* end protected  */
2359
2360  #if DECSUBSET
2361  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
2362  #endif
2363  if (status!=0) decStatus(res, status, set);/* then report status  */
2364  return res;
2365  } /* decNumberReduce  */
2366
2367/* ------------------------------------------------------------------ */
2368/* decNumberRescale -- force exponent to requested value              */
2369/*                                                                    */
2370/*   This computes C = op(A, B), where op adjusts the coefficient     */
2371/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2372/*   of C has the value B.  The numerical value of C will equal A,    */
2373/*   except for the effects of any rounding that occurred.            */
2374/*                                                                    */
2375/*   res is C, the result.  C may be A or B                           */
2376/*   lhs is A, the number to adjust                                   */
2377/*   rhs is B, the requested exponent                                 */
2378/*   set is the context                                               */
2379/*                                                                    */
2380/* C must have space for set->digits digits.                          */
2381/*                                                                    */
2382/* Unless there is an error or the result is infinite, the exponent   */
2383/* after the operation is guaranteed to be equal to B.                */
2384/* ------------------------------------------------------------------ */
2385U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2386                             const decNumber *rhs, decContext *set) {
2387  uInt status=0;                        /* accumulator  */
2388  decQuantizeOp(res, lhs, rhs, set, 0, &status);
2389  if (status!=0) decStatus(res, status, set);
2390  return res;
2391  } /* decNumberRescale  */
2392
2393/* ------------------------------------------------------------------ */
2394/* decNumberRemainder -- divide and return remainder                  */
2395/*                                                                    */
2396/*   This computes C = A % B                                          */
2397/*                                                                    */
2398/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2399/*   lhs is A                                                         */
2400/*   rhs is B                                                         */
2401/*   set is the context                                               */
2402/*                                                                    */
2403/* C must have space for set->digits digits.                          */
2404/* ------------------------------------------------------------------ */
2405U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2406                               const decNumber *rhs, decContext *set) {
2407  uInt status=0;                        /* accumulator  */
2408  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2409  if (status!=0) decStatus(res, status, set);
2410  #if DECCHECK
2411  decCheckInexact(res, set);
2412  #endif
2413  return res;
2414  } /* decNumberRemainder  */
2415
2416/* ------------------------------------------------------------------ */
2417/* decNumberRemainderNear -- divide and return remainder from nearest */
2418/*                                                                    */
2419/*   This computes C = A % B, where % is the IEEE remainder operator  */
2420/*                                                                    */
2421/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2422/*   lhs is A                                                         */
2423/*   rhs is B                                                         */
2424/*   set is the context                                               */
2425/*                                                                    */
2426/* C must have space for set->digits digits.                          */
2427/* ------------------------------------------------------------------ */
2428U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2429                                   const decNumber *rhs, decContext *set) {
2430  uInt status=0;                        /* accumulator  */
2431  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2432  if (status!=0) decStatus(res, status, set);
2433  #if DECCHECK
2434  decCheckInexact(res, set);
2435  #endif
2436  return res;
2437  } /* decNumberRemainderNear  */
2438
2439/* ------------------------------------------------------------------ */
2440/* decNumberRotate -- rotate the coefficient of a Number left/right   */
2441/*                                                                    */
2442/*   This computes C = A rot B  (in base ten and rotating set->digits */
2443/*   digits).                                                         */
2444/*                                                                    */
2445/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2446/*   lhs is A                                                         */
2447/*   rhs is B, the number of digits to rotate (-ve to right)          */
2448/*   set is the context                                               */
2449/*                                                                    */
2450/* The digits of the coefficient of A are rotated to the left (if B   */
2451/* is positive) or to the right (if B is negative) without adjusting  */
2452/* the exponent or the sign of A.  If lhs->digits is less than        */
2453/* set->digits the coefficient is padded with zeros on the left       */
2454/* before the rotate.  Any leading zeros in the result are removed    */
2455/* as usual.                                                          */
2456/*                                                                    */
2457/* B must be an integer (q=0) and in the range -set->digits through   */
2458/* +set->digits.                                                      */
2459/* C must have space for set->digits digits.                          */
2460/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2461/* B must be valid).  No status is set unless B is invalid or an      */
2462/* operand is an sNaN.                                                */
2463/* ------------------------------------------------------------------ */
2464U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2465                           const decNumber *rhs, decContext *set) {
2466  uInt status=0;              /* accumulator  */
2467  Int  rotate;                /* rhs as an Int  */
2468
2469  #if DECCHECK
2470  if (decCheckOperands(res, lhs, rhs, set)) return res;
2471  #endif
2472
2473  /* NaNs propagate as normal  */
2474  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2475    decNaNs(res, lhs, rhs, set, &status);
2476   /* rhs must be an integer  */
2477   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2478    status=DEC_Invalid_operation;
2479   else { /* both numeric, rhs is an integer  */
2480    rotate=decGetInt(rhs);                   /* [cannot fail]  */
2481    if (rotate==BADINT                       /* something bad ..  */
2482     || rotate==BIGODD || rotate==BIGEVEN    /* .. very big ..  */
2483     || abs(rotate)>set->digits)             /* .. or out of range  */
2484      status=DEC_Invalid_operation;
2485     else {                                  /* rhs is OK  */
2486      uprv_decNumberCopy(res, lhs);
2487      /* convert -ve rotate to equivalent positive rotation  */
2488      if (rotate<0) rotate=set->digits+rotate;
2489      if (rotate!=0 && rotate!=set->digits   /* zero or full rotation  */
2490       && !decNumberIsInfinite(res)) {       /* lhs was infinite  */
2491        /* left-rotate to do; 0 < rotate < set->digits  */
2492        uInt units, shift;                   /* work  */
2493        uInt msudigits;                      /* digits in result msu  */
2494        Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu  */
2495        Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu  */
2496        for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0  */
2497        res->digits=set->digits;                  /* now full-length  */
2498        msudigits=MSUDIGITS(res->digits);         /* actual digits in msu  */
2499
2500        /* rotation here is done in-place, in three steps  */
2501        /* 1. shift all to least up to one unit to unit-align final  */
2502        /*    lsd [any digits shifted out are rotated to the left,  */
2503        /*    abutted to the original msd (which may require split)]  */
2504        /*  */
2505        /*    [if there are no whole units left to rotate, the  */
2506        /*    rotation is now complete]  */
2507        /*  */
2508        /* 2. shift to least, from below the split point only, so that  */
2509        /*    the final msd is in the right place in its Unit [any  */
2510        /*    digits shifted out will fit exactly in the current msu,  */
2511        /*    left aligned, no split required]  */
2512        /*  */
2513        /* 3. rotate all the units by reversing left part, right  */
2514        /*    part, and then whole  */
2515        /*  */
2516        /* example: rotate right 8 digits (2 units + 2), DECDPUN=3.  */
2517        /*  */
2518        /*   start: 00a bcd efg hij klm npq  */
2519        /*  */
2520        /*      1a  000 0ab cde fgh|ijk lmn [pq saved]  */
2521        /*      1b  00p qab cde fgh|ijk lmn  */
2522        /*  */
2523        /*      2a  00p qab cde fgh|00i jkl [mn saved]  */
2524        /*      2b  mnp qab cde fgh|00i jkl  */
2525        /*  */
2526        /*      3a  fgh cde qab mnp|00i jkl  */
2527        /*      3b  fgh cde qab mnp|jkl 00i  */
2528        /*      3c  00i jkl mnp qab cde fgh  */
2529
2530        /* Step 1: amount to shift is the partial right-rotate count  */
2531        rotate=set->digits-rotate;      /* make it right-rotate  */
2532        units=rotate/DECDPUN;           /* whole units to rotate  */
2533        shift=rotate%DECDPUN;           /* left-over digits count  */
2534        if (shift>0) {                  /* not an exact number of units  */
2535          uInt save=res->lsu[0]%powers[shift];    /* save low digit(s)  */
2536          decShiftToLeast(res->lsu, D2U(res->digits), shift);
2537          if (shift>msudigits) {        /* msumax-1 needs >0 digits  */
2538            uInt rem=save%powers[shift-msudigits];/* split save  */
2539            *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert  */
2540            *(msumax-1)=*(msumax-1)
2541                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* ..  */
2542            }
2543           else { /* all fits in msumax  */
2544            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1]  */
2545            }
2546          } /* digits shift needed  */
2547
2548        /* If whole units to rotate...  */
2549        if (units>0) {                  /* some to do  */
2550          /* Step 2: the units to touch are the whole ones in rotate,  */
2551          /*   if any, and the shift is DECDPUN-msudigits (which may be  */
2552          /*   0, again)  */
2553          shift=DECDPUN-msudigits;
2554          if (shift>0) {                /* not an exact number of units  */
2555            uInt save=res->lsu[0]%powers[shift];  /* save low digit(s)  */
2556            decShiftToLeast(res->lsu, units, shift);
2557            *msumax=*msumax+(Unit)(save*powers[msudigits]);
2558            } /* partial shift needed  */
2559
2560          /* Step 3: rotate the units array using triple reverse  */
2561          /* (reversing is easy and fast)  */
2562          decReverse(res->lsu+units, msumax);     /* left part  */
2563          decReverse(res->lsu, res->lsu+units-1); /* right part  */
2564          decReverse(res->lsu, msumax);           /* whole  */
2565          } /* whole units to rotate  */
2566        /* the rotation may have left an undetermined number of zeros  */
2567        /* on the left, so true length needs to be calculated  */
2568        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2569        } /* rotate needed  */
2570      } /* rhs OK  */
2571    } /* numerics  */
2572  if (status!=0) decStatus(res, status, set);
2573  return res;
2574  } /* decNumberRotate  */
2575
2576/* ------------------------------------------------------------------ */
2577/* decNumberSameQuantum -- test for equal exponents                   */
2578/*                                                                    */
2579/*   res is the result number, which will contain either 0 or 1       */
2580/*   lhs is a number to test                                          */
2581/*   rhs is the second (usually a pattern)                            */
2582/*                                                                    */
2583/* No errors are possible and no context is needed.                   */
2584/* ------------------------------------------------------------------ */
2585U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2586                                 const decNumber *rhs) {
2587  Unit ret=0;                      /* return value  */
2588
2589  #if DECCHECK
2590  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2591  #endif
2592
2593  if (SPECIALARGS) {
2594    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2595     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2596     /* [anything else with a special gives 0]  */
2597    }
2598   else if (lhs->exponent==rhs->exponent) ret=1;
2599
2600  uprv_decNumberZero(res);              /* OK to overwrite an operand now  */
2601  *res->lsu=ret;
2602  return res;
2603  } /* decNumberSameQuantum  */
2604
2605/* ------------------------------------------------------------------ */
2606/* decNumberScaleB -- multiply by a power of 10                       */
2607/*                                                                    */
2608/* This computes C = A x 10**B where B is an integer (q=0) with       */
2609/* maximum magnitude 2*(emax+digits)                                  */
2610/*                                                                    */
2611/*   res is C, the result.  C may be A or B                           */
2612/*   lhs is A, the number to adjust                                   */
2613/*   rhs is B, the requested power of ten to use                      */
2614/*   set is the context                                               */
2615/*                                                                    */
2616/* C must have space for set->digits digits.                          */
2617/*                                                                    */
2618/* The result may underflow or overflow.                              */
2619/* ------------------------------------------------------------------ */
2620U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2621                            const decNumber *rhs, decContext *set) {
2622  Int  reqexp;                /* requested exponent change [B]  */
2623  uInt status=0;              /* accumulator  */
2624  Int  residue;               /* work  */
2625
2626  #if DECCHECK
2627  if (decCheckOperands(res, lhs, rhs, set)) return res;
2628  #endif
2629
2630  /* Handle special values except lhs infinite  */
2631  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2632    decNaNs(res, lhs, rhs, set, &status);
2633    /* rhs must be an integer  */
2634   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2635    status=DEC_Invalid_operation;
2636   else {
2637    /* lhs is a number; rhs is a finite with q==0  */
2638    reqexp=decGetInt(rhs);                   /* [cannot fail]  */
2639    if (reqexp==BADINT                       /* something bad ..  */
2640     || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big ..  */
2641     || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range  */
2642      status=DEC_Invalid_operation;
2643     else {                                  /* rhs is OK  */
2644      uprv_decNumberCopy(res, lhs);               /* all done if infinite lhs  */
2645      if (!decNumberIsInfinite(res)) {       /* prepare to scale  */
2646        res->exponent+=reqexp;               /* adjust the exponent  */
2647        residue=0;
2648        decFinalize(res, set, &residue, &status); /* .. and check  */
2649        } /* finite LHS  */
2650      } /* rhs OK  */
2651    } /* rhs finite  */
2652  if (status!=0) decStatus(res, status, set);
2653  return res;
2654  } /* decNumberScaleB  */
2655
2656/* ------------------------------------------------------------------ */
2657/* decNumberShift -- shift the coefficient of a Number left or right  */
2658/*                                                                    */
2659/*   This computes C = A << B or C = A >> -B  (in base ten).          */
2660/*                                                                    */
2661/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2662/*   lhs is A                                                         */
2663/*   rhs is B, the number of digits to shift (-ve to right)           */
2664/*   set is the context                                               */
2665/*                                                                    */
2666/* The digits of the coefficient of A are shifted to the left (if B   */
2667/* is positive) or to the right (if B is negative) without adjusting  */
2668/* the exponent or the sign of A.                                     */
2669/*                                                                    */
2670/* B must be an integer (q=0) and in the range -set->digits through   */
2671/* +set->digits.                                                      */
2672/* C must have space for set->digits digits.                          */
2673/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2674/* B must be valid).  No status is set unless B is invalid or an      */
2675/* operand is an sNaN.                                                */
2676/* ------------------------------------------------------------------ */
2677U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2678                           const decNumber *rhs, decContext *set) {
2679  uInt status=0;              /* accumulator  */
2680  Int  shift;                 /* rhs as an Int  */
2681
2682  #if DECCHECK
2683  if (decCheckOperands(res, lhs, rhs, set)) return res;
2684  #endif
2685
2686  /* NaNs propagate as normal  */
2687  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2688    decNaNs(res, lhs, rhs, set, &status);
2689   /* rhs must be an integer  */
2690   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2691    status=DEC_Invalid_operation;
2692   else { /* both numeric, rhs is an integer  */
2693    shift=decGetInt(rhs);                    /* [cannot fail]  */
2694    if (shift==BADINT                        /* something bad ..  */
2695     || shift==BIGODD || shift==BIGEVEN      /* .. very big ..  */
2696     || abs(shift)>set->digits)              /* .. or out of range  */
2697      status=DEC_Invalid_operation;
2698     else {                                  /* rhs is OK  */
2699      uprv_decNumberCopy(res, lhs);
2700      if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do  */
2701        if (shift>0) {                       /* to left  */
2702          if (shift==set->digits) {          /* removing all  */
2703            *res->lsu=0;                     /* so place 0  */
2704            res->digits=1;                   /* ..  */
2705            }
2706           else {                            /*  */
2707            /* first remove leading digits if necessary  */
2708            if (res->digits+shift>set->digits) {
2709              decDecap(res, res->digits+shift-set->digits);
2710              /* that updated res->digits; may have gone to 1 (for a  */
2711              /* single digit or for zero  */
2712              }
2713            if (res->digits>1 || *res->lsu)  /* if non-zero..  */
2714              res->digits=decShiftToMost(res->lsu, res->digits, shift);
2715            } /* partial left  */
2716          } /* left  */
2717         else { /* to right  */
2718          if (-shift>=res->digits) {         /* discarding all  */
2719            *res->lsu=0;                     /* so place 0  */
2720            res->digits=1;                   /* ..  */
2721            }
2722           else {
2723            decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2724            res->digits-=(-shift);
2725            }
2726          } /* to right  */
2727        } /* non-0 non-Inf shift  */
2728      } /* rhs OK  */
2729    } /* numerics  */
2730  if (status!=0) decStatus(res, status, set);
2731  return res;
2732  } /* decNumberShift  */
2733
2734/* ------------------------------------------------------------------ */
2735/* decNumberSquareRoot -- square root operator                        */
2736/*                                                                    */
2737/*   This computes C = squareroot(A)                                  */
2738/*                                                                    */
2739/*   res is C, the result.  C may be A                                */
2740/*   rhs is A                                                         */
2741/*   set is the context; note that rounding mode has no effect        */
2742/*                                                                    */
2743/* C must have space for set->digits digits.                          */
2744/* ------------------------------------------------------------------ */
2745/* This uses the following varying-precision algorithm in:            */
2746/*                                                                    */
2747/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2748/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2749/*   pp229-237, ACM, September 1985.                                  */
2750/*                                                                    */
2751/* The square-root is calculated using Newton's method, after which   */
2752/* a check is made to ensure the result is correctly rounded.         */
2753/*                                                                    */
2754/* % [Reformatted original Numerical Turing source code follows.]     */
2755/* function sqrt(x : real) : real                                     */
2756/* % sqrt(x) returns the properly rounded approximation to the square */
2757/* % root of x, in the precision of the calling environment, or it    */
2758/* % fails if x < 0.                                                  */
2759/* % t e hull and a abrham, august, 1984                              */
2760/* if x <= 0 then                                                     */
2761/*   if x < 0 then                                                    */
2762/*     assert false                                                   */
2763/*   else                                                             */
2764/*     result 0                                                       */
2765/*   end if                                                           */
2766/* end if                                                             */
2767/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2768/* var e := getexp(x)     % exponent part of x                        */
2769/* var approx : real                                                  */
2770/* if e mod 2 = 0  then                                               */
2771/*   approx := .259 + .819 * f   % approx to root of f                */
2772/* else                                                               */
2773/*   f := f/l0                   % adjustments                        */
2774/*   e := e + 1                  %   for odd                          */
2775/*   approx := .0819 + 2.59 * f  %   exponent                         */
2776/* end if                                                             */
2777/*                                                                    */
2778/* var p:= 3                                                          */
2779/* const maxp := currentprecision + 2                                 */
2780/* loop                                                               */
2781/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2782/*   precision p                                                      */
2783/*   approx := .5 * (approx + f/approx)                               */
2784/*   exit when p = maxp                                               */
2785/* end loop                                                           */
2786/*                                                                    */
2787/* % approx is now within 1 ulp of the properly rounded square root   */
2788/* % of f; to ensure proper rounding, compare squares of (approx -    */
2789/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2790/* p := currentprecision                                              */
2791/* begin                                                              */
2792/*   precision p + 2                                                  */
2793/*   const approxsubhalf := approx - setexp(.5, -p)                   */
2794/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2795/*     approx := approx - setexp(.l, -p + 1)                          */
2796/*   else                                                             */
2797/*     const approxaddhalf := approx + setexp(.5, -p)                 */
2798/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2799/*       approx := approx + setexp(.l, -p + 1)                        */
2800/*     end if                                                         */
2801/*   end if                                                           */
2802/* end                                                                */
2803/* result setexp(approx, e div 2)  % fix exponent                     */
2804/* end sqrt                                                           */
2805/* ------------------------------------------------------------------ */
2806#pragma clang diagnostic push
2807#pragma clang diagnostic ignored "-Warray-bounds"
2808U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2809                                decContext *set) {
2810  decContext workset, approxset;   /* work contexts  */
2811  decNumber dzero;                 /* used for constant zero  */
2812  Int  maxp;                       /* largest working precision  */
2813  Int  workp;                      /* working precision  */
2814  Int  residue=0;                  /* rounding residue  */
2815  uInt status=0, ignore=0;         /* status accumulators  */
2816  uInt rstatus;                    /* ..  */
2817  Int  exp;                        /* working exponent  */
2818  Int  ideal;                      /* ideal (preferred) exponent  */
2819  Int  needbytes;                  /* work  */
2820  Int  dropped;                    /* ..  */
2821
2822  #if DECSUBSET
2823  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2824  #endif
2825  /* buffer for f [needs +1 in case DECBUFFER 0]  */
2826  decNumber buff[D2N(DECBUFFER+1)];
2827  /* buffer for a [needs +2 to match likely maxp]  */
2828  decNumber bufa[D2N(DECBUFFER+2)];
2829  /* buffer for temporary, b [must be same size as a]  */
2830  decNumber bufb[D2N(DECBUFFER+2)];
2831  decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated  */
2832  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
2833  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
2834  decNumber *f=buff;               /* reduced fraction  */
2835  decNumber *a=bufa;               /* approximation to result  */
2836  decNumber *b=bufb;               /* intermediate result  */
2837  /* buffer for temporary variable, up to 3 digits  */
2838  decNumber buft[D2N(3)];
2839  decNumber *t=buft;               /* up-to-3-digit constant or work  */
2840
2841  #if DECCHECK
2842  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2843  #endif
2844
2845  do {                             /* protect allocated storage  */
2846    #if DECSUBSET
2847    if (!set->extended) {
2848      /* reduce operand and set lostDigits status, as needed  */
2849      if (rhs->digits>set->digits) {
2850        allocrhs=decRoundOperand(rhs, set, &status);
2851        if (allocrhs==NULL) break;
2852        /* [Note: 'f' allocation below could reuse this buffer if  */
2853        /* used, but as this is rare they are kept separate for clarity.]  */
2854        rhs=allocrhs;
2855        }
2856      }
2857    #endif
2858    /* [following code does not require input rounding]  */
2859
2860    /* handle infinities and NaNs  */
2861    if (SPECIALARG) {
2862      if (decNumberIsInfinite(rhs)) {         /* an infinity  */
2863        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2864         else uprv_decNumberCopy(res, rhs);        /* +Infinity  */
2865        }
2866       else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
2867      break;
2868      }
2869
2870    /* calculate the ideal (preferred) exponent [floor(exp/2)]  */
2871    /* [It would be nicer to write: ideal=rhs->exponent>>1, but this  */
2872    /* generates a compiler warning.  Generated code is the same.]  */
2873    ideal=(rhs->exponent&~1)/2;         /* target  */
2874
2875    /* handle zeros  */
2876    if (ISZERO(rhs)) {
2877      uprv_decNumberCopy(res, rhs);          /* could be 0 or -0  */
2878      res->exponent=ideal;              /* use the ideal [safe]  */
2879      /* use decFinish to clamp any out-of-range exponent, etc.  */
2880      decFinish(res, set, &residue, &status);
2881      break;
2882      }
2883
2884    /* any other -x is an oops  */
2885    if (decNumberIsNegative(rhs)) {
2886      status|=DEC_Invalid_operation;
2887      break;
2888      }
2889
2890    /* space is needed for three working variables  */
2891    /*   f -- the same precision as the RHS, reduced to 0.01->0.99...  */
2892    /*   a -- Hull's approximation -- precision, when assigned, is  */
2893    /*        currentprecision+1 or the input argument precision,  */
2894    /*        whichever is larger (+2 for use as temporary)  */
2895    /*   b -- intermediate temporary result (same size as a)  */
2896    /* if any is too long for local storage, then allocate  */
2897    workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision  */
2898    workp=MAXI(workp, 7);                    /* at least 7 for low cases  */
2899    maxp=workp+2;                            /* largest working precision  */
2900
2901    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2902    if (needbytes>(Int)sizeof(buff)) {
2903      allocbuff=(decNumber *)malloc(needbytes);
2904      if (allocbuff==NULL) {  /* hopeless -- abandon  */
2905        status|=DEC_Insufficient_storage;
2906        break;}
2907      f=allocbuff;            /* use the allocated space  */
2908      }
2909    /* a and b both need to be able to hold a maxp-length number  */
2910    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2911    if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b]  */
2912      allocbufa=(decNumber *)malloc(needbytes);
2913      allocbufb=(decNumber *)malloc(needbytes);
2914      if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless  */
2915        status|=DEC_Insufficient_storage;
2916        break;}
2917      a=allocbufa;            /* use the allocated spaces  */
2918      b=allocbufb;            /* ..  */
2919      }
2920
2921    /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1  */
2922    uprv_decNumberCopy(f, rhs);
2923    exp=f->exponent+f->digits;               /* adjusted to Hull rules  */
2924    f->exponent=-(f->digits);                /* to range  */
2925
2926    /* set up working context  */
2927    uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2928    workset.emax=DEC_MAX_EMAX;
2929    workset.emin=DEC_MIN_EMIN;
2930
2931    /* [Until further notice, no error is possible and status bits  */
2932    /* (Rounded, etc.) should be ignored, not accumulated.]  */
2933
2934    /* Calculate initial approximation, and allow for odd exponent  */
2935    workset.digits=workp;                    /* p for initial calculation  */
2936    t->bits=0; t->digits=3;
2937    a->bits=0; a->digits=3;
2938    if ((exp & 1)==0) {                      /* even exponent  */
2939      /* Set t=0.259, a=0.819  */
2940      t->exponent=-3;
2941      a->exponent=-3;
2942      #if DECDPUN>=3
2943        t->lsu[0]=259;
2944        a->lsu[0]=819;
2945      #elif DECDPUN==2
2946        t->lsu[0]=59; t->lsu[1]=2;
2947        a->lsu[0]=19; a->lsu[1]=8;
2948      #else
2949        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2950        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2951      #endif
2952      }
2953     else {                                  /* odd exponent  */
2954      /* Set t=0.0819, a=2.59  */
2955      f->exponent--;                         /* f=f/10  */
2956      exp++;                                 /* e=e+1  */
2957      t->exponent=-4;
2958      a->exponent=-2;
2959      #if DECDPUN>=3
2960        t->lsu[0]=819;
2961        a->lsu[0]=259;
2962      #elif DECDPUN==2
2963        t->lsu[0]=19; t->lsu[1]=8;
2964        a->lsu[0]=59; a->lsu[1]=2;
2965      #else
2966        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2967        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2968      #endif
2969      }
2970
2971    decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f  */
2972    decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t  */
2973    /* [a is now the initial approximation for sqrt(f), calculated with  */
2974    /* currentprecision, which is also a's precision.]  */
2975
2976    /* the main calculation loop  */
2977    uprv_decNumberZero(&dzero);                   /* make 0  */
2978    uprv_decNumberZero(t);                        /* set t = 0.5  */
2979    t->lsu[0]=5;                             /* ..  */
2980    t->exponent=-1;                          /* ..  */
2981    workset.digits=3;                        /* initial p  */
2982    for (; workset.digits<maxp;) {
2983      /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]  */
2984      workset.digits=MINI(workset.digits*2-2, maxp);
2985      /* a = 0.5 * (a + f/a)  */
2986      /* [calculated at p then rounded to currentprecision]  */
2987      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a  */
2988      decAddOp(b, b, a, &workset, 0, &ignore);         /* b=b+a  */
2989      decMultiplyOp(a, b, t, &workset, &ignore);       /* a=b*0.5  */
2990      } /* loop  */
2991
2992    /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits  */
2993    /* now reduce to length, etc.; this needs to be done with a  */
2994    /* having the correct exponent so as to handle subnormals  */
2995    /* correctly  */
2996    approxset=*set;                          /* get emin, emax, etc.  */
2997    approxset.round=DEC_ROUND_HALF_EVEN;
2998    a->exponent+=exp/2;                      /* set correct exponent  */
2999    rstatus=0;                               /* clear status  */
3000    residue=0;                               /* .. and accumulator  */
3001    decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed)  */
3002    decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize  */
3003
3004    /* Overflow was possible if the input exponent was out-of-range,  */
3005    /* in which case quit  */
3006    if (rstatus&DEC_Overflow) {
3007      status=rstatus;                        /* use the status as-is  */
3008      uprv_decNumberCopy(res, a);                 /* copy to result  */
3009      break;
3010      }
3011
3012    /* Preserve status except Inexact/Rounded  */
3013    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3014
3015    /* Carry out the Hull correction  */
3016    a->exponent-=exp/2;                      /* back to 0.1->1  */
3017
3018    /* a is now at final precision and within 1 ulp of the properly  */
3019    /* rounded square root of f; to ensure proper rounding, compare  */
3020    /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f.  */
3021    /* Here workset.digits=maxp and t=0.5, and a->digits determines  */
3022    /* the ulp  */
3023    workset.digits--;                             /* maxp-1 is OK now  */
3024    t->exponent=-a->digits-1;                     /* make 0.5 ulp  */
3025    decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp  */
3026    workset.round=DEC_ROUND_UP;
3027    decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b)  */
3028    decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed  */
3029    if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f]  */
3030      /* this is the more common adjustment, though both are rare  */
3031      t->exponent++;                              /* make 1.0 ulp  */
3032      t->lsu[0]=1;                                /* ..  */
3033      decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp  */
3034      /* assign to approx [round to length]  */
3035      approxset.emin-=exp/2;                      /* adjust to match a  */
3036      approxset.emax-=exp/2;
3037      decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3038      }
3039     else {
3040      decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp  */
3041      workset.round=DEC_ROUND_DOWN;
3042      decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b)  */
3043      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f  */
3044      if (decNumberIsNegative(b)) {               /* b < f  */
3045        t->exponent++;                            /* make 1.0 ulp  */
3046        t->lsu[0]=1;                              /* ..  */
3047        decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp  */
3048        /* assign to approx [round to length]  */
3049        approxset.emin-=exp/2;                    /* adjust to match a  */
3050        approxset.emax-=exp/2;
3051        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3052        }
3053      }
3054    /* [no errors are possible in the above, and rounding/inexact during  */
3055    /* estimation are irrelevant, so status was not accumulated]  */
3056
3057    /* Here, 0.1 <= a < 1  (still), so adjust back  */
3058    a->exponent+=exp/2;                      /* set correct exponent  */
3059
3060    /* count droppable zeros [after any subnormal rounding] by  */
3061    /* trimming a copy  */
3062    uprv_decNumberCopy(b, a);
3063    decTrim(b, set, 1, 1, &dropped);         /* [drops trailing zeros]  */
3064
3065    /* Set Inexact and Rounded.  The answer can only be exact if  */
3066    /* it is short enough so that squaring it could fit in workp  */
3067    /* digits, so this is the only (relatively rare) condition that  */
3068    /* a careful check is needed  */
3069    if (b->digits*2-1 > workp) {             /* cannot fit  */
3070      status|=DEC_Inexact|DEC_Rounded;
3071      }
3072     else {                                  /* could be exact/unrounded  */
3073      uInt mstatus=0;                        /* local status  */
3074      decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply  */
3075      if (mstatus&DEC_Overflow) {            /* result just won't fit  */
3076        status|=DEC_Inexact|DEC_Rounded;
3077        }
3078       else {                                /* plausible  */
3079        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs  */
3080        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal  */
3081         else {                              /* is Exact  */
3082          /* here, dropped is the count of trailing zeros in 'a'  */
3083          /* use closest exponent to ideal...  */
3084          Int todrop=ideal-a->exponent;      /* most that can be dropped  */
3085          if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s  */
3086           else {                            /* unrounded  */
3087            /* there are some to drop, but emax may not allow all  */
3088            Int maxexp=set->emax-set->digits+1;
3089            Int maxdrop=maxexp-a->exponent;
3090            if (todrop>maxdrop && set->clamp) { /* apply clamping  */
3091              todrop=maxdrop;
3092              status|=DEC_Clamped;
3093              }
3094            if (dropped<todrop) {            /* clamp to those available  */
3095              todrop=dropped;
3096              status|=DEC_Clamped;
3097              }
3098            if (todrop>0) {                  /* have some to drop  */
3099              decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3100              a->exponent+=todrop;           /* maintain numerical value  */
3101              a->digits-=todrop;             /* new length  */
3102              }
3103            }
3104          }
3105        }
3106      }
3107
3108    /* double-check Underflow, as perhaps the result could not have  */
3109    /* been subnormal (initial argument too big), or it is now Exact  */
3110    if (status&DEC_Underflow) {
3111      Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent  */
3112      /* check if truly subnormal  */
3113      #if DECEXTFLAG                         /* DEC_Subnormal too  */
3114        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3115      #else
3116        if (ae>=set->emin*2) status&=~DEC_Underflow;
3117      #endif
3118      /* check if truly inexact  */
3119      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3120      }
3121
3122    uprv_decNumberCopy(res, a);                   /* a is now the result  */
3123    } while(0);                              /* end protected  */
3124
3125  if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used  */
3126  if (allocbufa!=NULL) free(allocbufa);      /* ..  */
3127  if (allocbufb!=NULL) free(allocbufb);      /* ..  */
3128  #if DECSUBSET
3129  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
3130  #endif
3131  if (status!=0) decStatus(res, status, set);/* then report status  */
3132  #if DECCHECK
3133  decCheckInexact(res, set);
3134  #endif
3135  return res;
3136  } /* decNumberSquareRoot  */
3137#pragma clang diagnostic pop
3138
3139/* ------------------------------------------------------------------ */
3140/* decNumberSubtract -- subtract two Numbers                          */
3141/*                                                                    */
3142/*   This computes C = A - B                                          */
3143/*                                                                    */
3144/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3145/*   lhs is A                                                         */
3146/*   rhs is B                                                         */
3147/*   set is the context                                               */
3148/*                                                                    */
3149/* C must have space for set->digits digits.                          */
3150/* ------------------------------------------------------------------ */
3151U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3152                              const decNumber *rhs, decContext *set) {
3153  uInt status=0;                        /* accumulator  */
3154
3155  decAddOp(res, lhs, rhs, set, DECNEG, &status);
3156  if (status!=0) decStatus(res, status, set);
3157  #if DECCHECK
3158  decCheckInexact(res, set);
3159  #endif
3160  return res;
3161  } /* decNumberSubtract  */
3162
3163/* ------------------------------------------------------------------ */
3164/* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3165/* decNumberToIntegralValue -- round-to-integral-value                */
3166/*                                                                    */
3167/*   res is the result                                                */
3168/*   rhs is input number                                              */
3169/*   set is the context                                               */
3170/*                                                                    */
3171/* res must have space for any value of rhs.                          */
3172/*                                                                    */
3173/* This implements the IEEE special operators and therefore treats    */
3174/* special values as valid.  For finite numbers it returns            */
3175/* rescale(rhs, 0) if rhs->exponent is <0.                            */
3176/* Otherwise the result is rhs (so no error is possible, except for   */
3177/* sNaN).                                                             */
3178/*                                                                    */
3179/* The context is used for rounding mode and status after sNaN, but   */
3180/* the digits setting is ignored.  The Exact version will signal      */
3181/* Inexact if the result differs numerically from rhs; the other      */
3182/* never signals Inexact.                                             */
3183/* ------------------------------------------------------------------ */
3184U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3185                                     decContext *set) {
3186  decNumber dn;
3187  decContext workset;              /* working context  */
3188  uInt status=0;                   /* accumulator  */
3189
3190  #if DECCHECK
3191  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3192  #endif
3193
3194  /* handle infinities and NaNs  */
3195  if (SPECIALARG) {
3196    if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity  */
3197     else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
3198    }
3199   else { /* finite  */
3200    /* have a finite number; no error possible (res must be big enough)  */
3201    if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3202    /* that was easy, but if negative exponent there is work to do...  */
3203    workset=*set;                  /* clone rounding, etc.  */
3204    workset.digits=rhs->digits;    /* no length rounding  */
3205    workset.traps=0;               /* no traps  */
3206    uprv_decNumberZero(&dn);            /* make a number with exponent 0  */
3207    uprv_decNumberQuantize(res, rhs, &dn, &workset);
3208    status|=workset.status;
3209    }
3210  if (status!=0) decStatus(res, status, set);
3211  return res;
3212  } /* decNumberToIntegralExact  */
3213
3214U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3215                                     decContext *set) {
3216  decContext workset=*set;         /* working context  */
3217  workset.traps=0;                 /* no traps  */
3218  uprv_decNumberToIntegralExact(res, rhs, &workset);
3219  /* this never affects set, except for sNaNs; NaN will have been set  */
3220  /* or propagated already, so no need to call decStatus  */
3221  set->status|=workset.status&DEC_Invalid_operation;
3222  return res;
3223  } /* decNumberToIntegralValue  */
3224
3225/* ------------------------------------------------------------------ */
3226/* decNumberXor -- XOR two Numbers, digitwise                         */
3227/*                                                                    */
3228/*   This computes C = A ^ B                                          */
3229/*                                                                    */
3230/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3231/*   lhs is A                                                         */
3232/*   rhs is B                                                         */
3233/*   set is the context (used for result length and error report)     */
3234/*                                                                    */
3235/* C must have space for set->digits digits.                          */
3236/*                                                                    */
3237/* Logical function restrictions apply (see above); a NaN is          */
3238/* returned with Invalid_operation if a restriction is violated.      */
3239/* ------------------------------------------------------------------ */
3240U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3241                         const decNumber *rhs, decContext *set) {
3242  const Unit *ua, *ub;                  /* -> operands  */
3243  const Unit *msua, *msub;              /* -> operand msus  */
3244  Unit  *uc, *msuc;                     /* -> result and its msu  */
3245  Int   msudigs;                        /* digits in res msu  */
3246  #if DECCHECK
3247  if (decCheckOperands(res, lhs, rhs, set)) return res;
3248  #endif
3249
3250  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3251   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3252    decStatus(res, DEC_Invalid_operation, set);
3253    return res;
3254    }
3255  /* operands are valid  */
3256  ua=lhs->lsu;                          /* bottom-up  */
3257  ub=rhs->lsu;                          /* ..  */
3258  uc=res->lsu;                          /* ..  */
3259  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
3260  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
3261  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
3262  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
3263  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
3264    Unit a, b;                          /* extract units  */
3265    if (ua>msua) a=0;
3266     else a=*ua;
3267    if (ub>msub) b=0;
3268     else b=*ub;
3269    *uc=0;                              /* can now write back  */
3270    if (a|b) {                          /* maybe 1 bits to examine  */
3271      Int i, j;
3272      /* This loop could be unrolled and/or use BIN2BCD tables  */
3273      for (i=0; i<DECDPUN; i++) {
3274        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR  */
3275        j=a%10;
3276        a=a/10;
3277        j|=b%10;
3278        b=b/10;
3279        if (j>1) {
3280          decStatus(res, DEC_Invalid_operation, set);
3281          return res;
3282          }
3283        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
3284        } /* each digit  */
3285      } /* non-zero  */
3286    } /* each unit  */
3287  /* [here uc-1 is the msu of the result]  */
3288  res->digits=decGetDigits(res->lsu, uc-res->lsu);
3289  res->exponent=0;                      /* integer  */
3290  res->bits=0;                          /* sign=0  */
3291  return res;  /* [no status to set]  */
3292  } /* decNumberXor  */
3293
3294
3295/* ================================================================== */
3296/* Utility routines                                                   */
3297/* ================================================================== */
3298
3299/* ------------------------------------------------------------------ */
3300/* decNumberClass -- return the decClass of a decNumber               */
3301/*   dn -- the decNumber to test                                      */
3302/*   set -- the context to use for Emin                               */
3303/*   returns the decClass enum                                        */
3304/* ------------------------------------------------------------------ */
3305enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3306  if (decNumberIsSpecial(dn)) {
3307    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3308    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3309    /* must be an infinity  */
3310    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3311    return DEC_CLASS_POS_INF;
3312    }
3313  /* is finite  */
3314  if (uprv_decNumberIsNormal(dn, set)) { /* most common  */
3315    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3316    return DEC_CLASS_POS_NORMAL;
3317    }
3318  /* is subnormal or zero  */
3319  if (decNumberIsZero(dn)) {    /* most common  */
3320    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3321    return DEC_CLASS_POS_ZERO;
3322    }
3323  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3324  return DEC_CLASS_POS_SUBNORMAL;
3325  } /* decNumberClass  */
3326
3327/* ------------------------------------------------------------------ */
3328/* decNumberClassToString -- convert decClass to a string             */
3329/*                                                                    */
3330/*  eclass is a valid decClass                                        */
3331/*  returns a constant string describing the class (max 13+1 chars)   */
3332/* ------------------------------------------------------------------ */
3333const char *uprv_decNumberClassToString(enum decClass eclass) {
3334  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3335  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3336  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3337  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3338  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3339  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3340  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3341  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3342  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3343  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3344  return DEC_ClassString_UN;           /* Unknown  */
3345  } /* decNumberClassToString  */
3346
3347/* ------------------------------------------------------------------ */
3348/* decNumberCopy -- copy a number                                     */
3349/*                                                                    */
3350/*   dest is the target decNumber                                     */
3351/*   src  is the source decNumber                                     */
3352/*   returns dest                                                     */
3353/*                                                                    */
3354/* (dest==src is allowed and is a no-op)                              */
3355/* All fields are updated as required.  This is a utility operation,  */
3356/* so special values are unchanged and no error is possible.          */
3357/* ------------------------------------------------------------------ */
3358U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3359
3360  #if DECCHECK
3361  if (src==NULL) return uprv_decNumberZero(dest);
3362  #endif
3363
3364  if (dest==src) return dest;                /* no copy required  */
3365
3366  /* Use explicit assignments here as structure assignment could copy  */
3367  /* more than just the lsu (for small DECDPUN).  This would not affect  */
3368  /* the value of the results, but could disturb test harness spill  */
3369  /* checking.  */
3370  dest->bits=src->bits;
3371  dest->exponent=src->exponent;
3372  dest->digits=src->digits;
3373  dest->lsu[0]=src->lsu[0];
3374  if (src->digits>DECDPUN) {                 /* more Units to come  */
3375    const Unit *smsup, *s;                   /* work  */
3376    Unit  *d;                                /* ..  */
3377    /* memcpy for the remaining Units would be safe as they cannot  */
3378    /* overlap.  However, this explicit loop is faster in short cases.  */
3379    d=dest->lsu+1;                           /* -> first destination  */
3380    smsup=src->lsu+D2U(src->digits);         /* -> source msu+1  */
3381    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3382    }
3383  return dest;
3384  } /* decNumberCopy  */
3385
3386/* ------------------------------------------------------------------ */
3387/* decNumberCopyAbs -- quiet absolute value operator                  */
3388/*                                                                    */
3389/*   This sets C = abs(A)                                             */
3390/*                                                                    */
3391/*   res is C, the result.  C may be A                                */
3392/*   rhs is A                                                         */
3393/*                                                                    */
3394/* C must have space for set->digits digits.                          */
3395/* No exception or error can occur; this is a quiet bitwise operation.*/
3396/* See also decNumberAbs for a checking version of this.              */
3397/* ------------------------------------------------------------------ */
3398U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3399  #if DECCHECK
3400  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3401  #endif
3402  uprv_decNumberCopy(res, rhs);
3403  res->bits&=~DECNEG;                   /* turn off sign  */
3404  return res;
3405  } /* decNumberCopyAbs  */
3406
3407/* ------------------------------------------------------------------ */
3408/* decNumberCopyNegate -- quiet negate value operator                 */
3409/*                                                                    */
3410/*   This sets C = negate(A)                                          */
3411/*                                                                    */
3412/*   res is C, the result.  C may be A                                */
3413/*   rhs is A                                                         */
3414/*                                                                    */
3415/* C must have space for set->digits digits.                          */
3416/* No exception or error can occur; this is a quiet bitwise operation.*/
3417/* See also decNumberMinus for a checking version of this.            */
3418/* ------------------------------------------------------------------ */
3419U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3420  #if DECCHECK
3421  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3422  #endif
3423  uprv_decNumberCopy(res, rhs);
3424  res->bits^=DECNEG;                    /* invert the sign  */
3425  return res;
3426  } /* decNumberCopyNegate  */
3427
3428/* ------------------------------------------------------------------ */
3429/* decNumberCopySign -- quiet copy and set sign operator              */
3430/*                                                                    */
3431/*   This sets C = A with the sign of B                               */
3432/*                                                                    */
3433/*   res is C, the result.  C may be A                                */
3434/*   lhs is A                                                         */
3435/*   rhs is B                                                         */
3436/*                                                                    */
3437/* C must have space for set->digits digits.                          */
3438/* No exception or error can occur; this is a quiet bitwise operation.*/
3439/* ------------------------------------------------------------------ */
3440U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3441                              const decNumber *rhs) {
3442  uByte sign;                           /* rhs sign  */
3443  #if DECCHECK
3444  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3445  #endif
3446  sign=rhs->bits & DECNEG;              /* save sign bit  */
3447  uprv_decNumberCopy(res, lhs);
3448  res->bits&=~DECNEG;                   /* clear the sign  */
3449  res->bits|=sign;                      /* set from rhs  */
3450  return res;
3451  } /* decNumberCopySign  */
3452
3453/* ------------------------------------------------------------------ */
3454/* decNumberGetBCD -- get the coefficient in BCD8                     */
3455/*   dn is the source decNumber                                       */
3456/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3457/*     most-significant at offset 0                                   */
3458/*   returns bcd                                                      */
3459/*                                                                    */
3460/* bcd must have at least dn->digits bytes.  No error is possible; if */
3461/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3462/* ------------------------------------------------------------------ */
3463U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3464  uByte *ub=bcd+dn->digits-1;      /* -> lsd  */
3465  const Unit *up=dn->lsu;          /* Unit pointer, -> lsu  */
3466
3467  #if DECDPUN==1                   /* trivial simple copy  */
3468    for (; ub>=bcd; ub--, up++) *ub=*up;
3469  #else                            /* chopping needed  */
3470    uInt u=*up;                    /* work  */
3471    uInt cut=DECDPUN;              /* downcounter through unit  */
3472    for (; ub>=bcd; ub--) {
3473      *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here]  */
3474      u=u/10;
3475      cut--;
3476      if (cut>0) continue;         /* more in this unit  */
3477      up++;
3478      u=*up;
3479      cut=DECDPUN;
3480      }
3481  #endif
3482  return bcd;
3483  } /* decNumberGetBCD  */
3484
3485/* ------------------------------------------------------------------ */
3486/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3487/*   dn is the target decNumber                                       */
3488/*   bcd is the uInt array that will source n BCD bytes, most-        */
3489/*     significant at offset 0                                        */
3490/*   n is the number of digits in the source BCD array (bcd)          */
3491/*   returns dn                                                       */
3492/*                                                                    */
3493/* dn must have space for at least n digits.  No error is possible;   */
3494/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3495/* and bcd[0] zero.                                                   */
3496/* ------------------------------------------------------------------ */
3497U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3498  Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer]  */
3499  const uByte *ub=bcd;                  /* -> source msd  */
3500
3501  #if DECDPUN==1                        /* trivial simple copy  */
3502    for (; ub<bcd+n; ub++, up--) *up=*ub;
3503  #else                                 /* some assembly needed  */
3504    /* calculate how many digits in msu, and hence first cut  */
3505    Int cut=MSUDIGITS(n);               /* [faster than remainder]  */
3506    for (;up>=dn->lsu; up--) {          /* each Unit from msu  */
3507      *up=0;                            /* will take <=DECDPUN digits  */
3508      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3509      cut=DECDPUN;                      /* next Unit has all digits  */
3510      }
3511  #endif
3512  dn->digits=n;                         /* set digit count  */
3513  return dn;
3514  } /* decNumberSetBCD  */
3515
3516/* ------------------------------------------------------------------ */
3517/* decNumberIsNormal -- test normality of a decNumber                 */
3518/*   dn is the decNumber to test                                      */
3519/*   set is the context to use for Emin                               */
3520/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3521/* ------------------------------------------------------------------ */
3522Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3523  Int ae;                               /* adjusted exponent  */
3524  #if DECCHECK
3525  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3526  #endif
3527
3528  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3529  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3530
3531  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3532  if (ae<set->emin) return 0;           /* is subnormal  */
3533  return 1;
3534  } /* decNumberIsNormal  */
3535
3536/* ------------------------------------------------------------------ */
3537/* decNumberIsSubnormal -- test subnormality of a decNumber           */
3538/*   dn is the decNumber to test                                      */
3539/*   set is the context to use for Emin                               */
3540/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3541/* ------------------------------------------------------------------ */
3542Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3543  Int ae;                               /* adjusted exponent  */
3544  #if DECCHECK
3545  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3546  #endif
3547
3548  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3549  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3550
3551  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3552  if (ae<set->emin) return 1;           /* is subnormal  */
3553  return 0;
3554  } /* decNumberIsSubnormal  */
3555
3556/* ------------------------------------------------------------------ */
3557/* decNumberTrim -- remove insignificant zeros                        */
3558/*                                                                    */
3559/*   dn is the number to trim                                         */
3560/*   returns dn                                                       */
3561/*                                                                    */
3562/* All fields are updated as required.  This is a utility operation,  */
3563/* so special values are unchanged and no error is possible.  The     */
3564/* zeros are removed unconditionally.                                 */
3565/* ------------------------------------------------------------------ */
3566U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3567  Int  dropped;                    /* work  */
3568  decContext set;                  /* ..  */
3569  #if DECCHECK
3570  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3571  #endif
3572  uprv_decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0  */
3573  return decTrim(dn, &set, 0, 1, &dropped);
3574  } /* decNumberTrim  */
3575
3576/* ------------------------------------------------------------------ */
3577/* decNumberVersion -- return the name and version of this module     */
3578/*                                                                    */
3579/* No error is possible.                                              */
3580/* ------------------------------------------------------------------ */
3581const char * uprv_decNumberVersion(void) {
3582  return DECVERSION;
3583  } /* decNumberVersion  */
3584
3585/* ------------------------------------------------------------------ */
3586/* decNumberZero -- set a number to 0                                 */
3587/*                                                                    */
3588/*   dn is the number to set, with space for one digit                */
3589/*   returns dn                                                       */
3590/*                                                                    */
3591/* No error is possible.                                              */
3592/* ------------------------------------------------------------------ */
3593/* Memset is not used as it is much slower in some environments.  */
3594U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3595
3596  #if DECCHECK
3597  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3598  #endif
3599
3600  dn->bits=0;
3601  dn->exponent=0;
3602  dn->digits=1;
3603  dn->lsu[0]=0;
3604  return dn;
3605  } /* decNumberZero  */
3606
3607/* ================================================================== */
3608/* Local routines                                                     */
3609/* ================================================================== */
3610
3611/* ------------------------------------------------------------------ */
3612/* decToString -- lay out a number into a string                      */
3613/*                                                                    */
3614/*   dn     is the number to lay out                                  */
3615/*   string is where to lay out the number                            */
3616/*   eng    is 1 if Engineering, 0 if Scientific                      */
3617/*                                                                    */
3618/* string must be at least dn->digits+14 characters long              */
3619/* No error is possible.                                              */
3620/*                                                                    */
3621/* Note that this routine can generate a -0 or 0.000.  These are      */
3622/* never generated in subset to-number or arithmetic, but can occur   */
3623/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3624/* ------------------------------------------------------------------ */
3625/* If DECCHECK is enabled the string "?" is returned if a number is  */
3626/* invalid.  */
3627static void decToString(const decNumber *dn, char *string, Flag eng) {
3628  Int exp=dn->exponent;       /* local copy  */
3629  Int e;                      /* E-part value  */
3630  Int pre;                    /* digits before the '.'  */
3631  Int cut;                    /* for counting digits in a Unit  */
3632  char *c=string;             /* work [output pointer]  */
3633  const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer]  */
3634  uInt u, pow;                /* work  */
3635
3636  #if DECCHECK
3637  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3638    strcpy(string, "?");
3639    return;}
3640  #endif
3641
3642  if (decNumberIsNegative(dn)) {   /* Negatives get a minus  */
3643    *c='-';
3644    c++;
3645    }
3646  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
3647    if (decNumberIsInfinite(dn)) {
3648      strcpy(c,   "Inf");
3649      strcpy(c+3, "inity");
3650      return;}
3651    /* a NaN  */
3652    if (dn->bits&DECSNAN) {        /* signalling NaN  */
3653      *c='s';
3654      c++;
3655      }
3656    strcpy(c, "NaN");
3657    c+=3;                          /* step past  */
3658    /* if not a clean non-zero coefficient, that's all there is in a  */
3659    /* NaN string  */
3660    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3661    /* [drop through to add integer]  */
3662    }
3663
3664  /* calculate how many digits in msu, and hence first cut  */
3665  cut=MSUDIGITS(dn->digits);       /* [faster than remainder]  */
3666  cut--;                           /* power of ten for digit  */
3667
3668  if (exp==0) {                    /* simple integer [common fastpath]  */
3669    for (;up>=dn->lsu; up--) {     /* each Unit from msu  */
3670      u=*up;                       /* contains DECDPUN digits to lay out  */
3671      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3672      cut=DECDPUN-1;               /* next Unit has all digits  */
3673      }
3674    *c='\0';                       /* terminate the string  */
3675    return;}
3676
3677  /* non-0 exponent -- assume plain form */
3678  pre=dn->digits+exp;              /* digits before '.'  */
3679  e=0;                             /* no E  */
3680  if ((exp>0) || (pre<-5)) {       /* need exponential form  */
3681    e=exp+dn->digits-1;            /* calculate E value  */
3682    pre=1;                         /* assume one digit before '.'  */
3683    if (eng && (e!=0)) {           /* engineering: may need to adjust  */
3684      Int adj;                     /* adjustment  */
3685      /* The C remainder operator is undefined for negative numbers, so  */
3686      /* a positive remainder calculation must be used here  */
3687      if (e<0) {
3688        adj=(-e)%3;
3689        if (adj!=0) adj=3-adj;
3690        }
3691       else { /* e>0  */
3692        adj=e%3;
3693        }
3694      e=e-adj;
3695      /* if dealing with zero still produce an exponent which is a  */
3696      /* multiple of three, as expected, but there will only be the  */
3697      /* one zero before the E, still.  Otherwise note the padding.  */
3698      if (!ISZERO(dn)) pre+=adj;
3699       else {  /* is zero  */
3700        if (adj!=0) {              /* 0.00Esnn needed  */
3701          e=e+3;
3702          pre=-(2-adj);
3703          }
3704        } /* zero  */
3705      } /* eng  */
3706    } /* need exponent  */
3707
3708  /* lay out the digits of the coefficient, adding 0s and . as needed */
3709  u=*up;
3710  if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form  */
3711    Int n=pre;
3712    for (; pre>0; pre--, c++, cut--) {
3713      if (cut<0) {                 /* need new Unit  */
3714        if (up==dn->lsu) break;    /* out of input digits (pre>digits)  */
3715        up--;
3716        cut=DECDPUN-1;
3717        u=*up;
3718        }
3719      TODIGIT(u, cut, c, pow);
3720      }
3721    if (n<dn->digits) {            /* more to come, after '.'  */
3722      *c='.'; c++;
3723      for (;; c++, cut--) {
3724        if (cut<0) {               /* need new Unit  */
3725          if (up==dn->lsu) break;  /* out of input digits  */
3726          up--;
3727          cut=DECDPUN-1;
3728          u=*up;
3729          }
3730        TODIGIT(u, cut, c, pow);
3731        }
3732      }
3733     else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed  */
3734    }
3735   else {                          /* 0.xxx or 0.000xxx form  */
3736    *c='0'; c++;
3737    *c='.'; c++;
3738    for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.'  */
3739    for (; ; c++, cut--) {
3740      if (cut<0) {                 /* need new Unit  */
3741        if (up==dn->lsu) break;    /* out of input digits  */
3742        up--;
3743        cut=DECDPUN-1;
3744        u=*up;
3745        }
3746      TODIGIT(u, cut, c, pow);
3747      }
3748    }
3749
3750  /* Finally add the E-part, if needed.  It will never be 0, has a
3751     base maximum and minimum of +999999999 through -999999999, but
3752     could range down to -1999999998 for anormal numbers */
3753  if (e!=0) {
3754    Flag had=0;               /* 1=had non-zero  */
3755    *c='E'; c++;
3756    *c='+'; c++;              /* assume positive  */
3757    u=e;                      /* ..  */
3758    if (e<0) {
3759      *(c-1)='-';             /* oops, need -  */
3760      u=-e;                   /* uInt, please  */
3761      }
3762    /* lay out the exponent [_itoa or equivalent is not ANSI C]  */
3763    for (cut=9; cut>=0; cut--) {
3764      TODIGIT(u, cut, c, pow);
3765      if (*c=='0' && !had) continue;    /* skip leading zeros  */
3766      had=1;                            /* had non-0  */
3767      c++;                              /* step for next  */
3768      } /* cut  */
3769    }
3770  *c='\0';          /* terminate the string (all paths)  */
3771  return;
3772  } /* decToString  */
3773
3774/* ------------------------------------------------------------------ */
3775/* decAddOp -- add/subtract operation                                 */
3776/*                                                                    */
3777/*   This computes C = A + B                                          */
3778/*                                                                    */
3779/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3780/*   lhs is A                                                         */
3781/*   rhs is B                                                         */
3782/*   set is the context                                               */
3783/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3784/*   status accumulates status for the caller                         */
3785/*                                                                    */
3786/* C must have space for set->digits digits.                          */
3787/* Inexact in status must be 0 for correct Exact zero sign in result  */
3788/* ------------------------------------------------------------------ */
3789/* If possible, the coefficient is calculated directly into C.        */
3790/* However, if:                                                       */
3791/*   -- a digits+1 calculation is needed because the numbers are      */
3792/*      unaligned and span more than set->digits digits               */
3793/*   -- a carry to digits+1 digits looks possible                     */
3794/*   -- C is the same as A or B, and the result would destructively   */
3795/*      overlap the A or B coefficient                                */
3796/* then the result must be calculated into a temporary buffer.  In    */
3797/* this case a local (stack) buffer is used if possible, and only if  */
3798/* too long for that does malloc become the final resort.             */
3799/*                                                                    */
3800/* Misalignment is handled as follows:                                */
3801/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3802/*   BPad: Apply the padding by a combination of shifting (whole      */
3803/*         units) and multiplication (part units).                    */
3804/*                                                                    */
3805/* Addition, especially x=x+1, is speed-critical.                     */
3806/* The static buffer is larger than might be expected to allow for    */
3807/* calls from higher-level funtions (notable exp).                    */
3808/* ------------------------------------------------------------------ */
3809static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3810                            const decNumber *rhs, decContext *set,
3811                            uByte negate, uInt *status) {
3812  #if DECSUBSET
3813  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
3814  decNumber *allocrhs=NULL;        /* .., rhs  */
3815  #endif
3816  Int   rhsshift;                  /* working shift (in Units)  */
3817  Int   maxdigits;                 /* longest logical length  */
3818  Int   mult;                      /* multiplier  */
3819  Int   residue;                   /* rounding accumulator  */
3820  uByte bits;                      /* result bits  */
3821  Flag  diffsign;                  /* non-0 if arguments have different sign  */
3822  Unit  *acc;                      /* accumulator for result  */
3823  Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many  */
3824                                   /* allocations when called from  */
3825                                   /* other operations, notable exp]  */
3826  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
3827  Int   reqdigits=set->digits;     /* local copy; requested DIGITS  */
3828  Int   padding;                   /* work  */
3829
3830  #if DECCHECK
3831  if (decCheckOperands(res, lhs, rhs, set)) return res;
3832  #endif
3833
3834  do {                             /* protect allocated storage  */
3835    #if DECSUBSET
3836    if (!set->extended) {
3837      /* reduce operands and set lostDigits status, as needed  */
3838      if (lhs->digits>reqdigits) {
3839        alloclhs=decRoundOperand(lhs, set, status);
3840        if (alloclhs==NULL) break;
3841        lhs=alloclhs;
3842        }
3843      if (rhs->digits>reqdigits) {
3844        allocrhs=decRoundOperand(rhs, set, status);
3845        if (allocrhs==NULL) break;
3846        rhs=allocrhs;
3847        }
3848      }
3849    #endif
3850    /* [following code does not require input rounding]  */
3851
3852    /* note whether signs differ [used all paths]  */
3853    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3854
3855    /* handle infinities and NaNs  */
3856    if (SPECIALARGS) {                  /* a special bit set  */
3857      if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN  */
3858        decNaNs(res, lhs, rhs, set, status);
3859       else { /* one or two infinities  */
3860        if (decNumberIsInfinite(lhs)) { /* LHS is infinity  */
3861          /* two infinities with different signs is invalid  */
3862          if (decNumberIsInfinite(rhs) && diffsign) {
3863            *status|=DEC_Invalid_operation;
3864            break;
3865            }
3866          bits=lhs->bits & DECNEG;      /* get sign from LHS  */
3867          }
3868         else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity  */
3869        bits|=DECINF;
3870        uprv_decNumberZero(res);
3871        res->bits=bits;                 /* set +/- infinity  */
3872        } /* an infinity  */
3873      break;
3874      }
3875
3876    /* Quick exit for add 0s; return the non-0, modified as need be  */
3877    if (ISZERO(lhs)) {
3878      Int adjust;                       /* work  */
3879      Int lexp=lhs->exponent;           /* save in case LHS==RES  */
3880      bits=lhs->bits;                   /* ..  */
3881      residue=0;                        /* clear accumulator  */
3882      decCopyFit(res, rhs, set, &residue, status); /* copy (as needed)  */
3883      res->bits^=negate;                /* flip if rhs was negated  */
3884      #if DECSUBSET
3885      if (set->extended) {              /* exponents on zeros count  */
3886      #endif
3887        /* exponent will be the lower of the two  */
3888        adjust=lexp-res->exponent;      /* adjustment needed [if -ve]  */
3889        if (ISZERO(res)) {              /* both 0: special IEEE 754 rules  */
3890          if (adjust<0) res->exponent=lexp;  /* set exponent  */
3891          /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0  */
3892          if (diffsign) {
3893            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3894             else res->bits=DECNEG;     /* preserve 0 sign  */
3895            }
3896          }
3897         else { /* non-0 res  */
3898          if (adjust<0) {     /* 0-padding needed  */
3899            if ((res->digits-adjust)>set->digits) {
3900              adjust=res->digits-set->digits;     /* to fit exactly  */
3901              *status|=DEC_Rounded;               /* [but exact]  */
3902              }
3903            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3904            res->exponent+=adjust;                /* set the exponent.  */
3905            }
3906          } /* non-0 res  */
3907      #if DECSUBSET
3908        } /* extended  */
3909      #endif
3910      decFinish(res, set, &residue, status);      /* clean and finalize  */
3911      break;}
3912
3913    if (ISZERO(rhs)) {                  /* [lhs is non-zero]  */
3914      Int adjust;                       /* work  */
3915      Int rexp=rhs->exponent;           /* save in case RHS==RES  */
3916      bits=rhs->bits;                   /* be clean  */
3917      residue=0;                        /* clear accumulator  */
3918      decCopyFit(res, lhs, set, &residue, status); /* copy (as needed)  */
3919      #if DECSUBSET
3920      if (set->extended) {              /* exponents on zeros count  */
3921      #endif
3922        /* exponent will be the lower of the two  */
3923        /* [0-0 case handled above]  */
3924        adjust=rexp-res->exponent;      /* adjustment needed [if -ve]  */
3925        if (adjust<0) {     /* 0-padding needed  */
3926          if ((res->digits-adjust)>set->digits) {
3927            adjust=res->digits-set->digits;     /* to fit exactly  */
3928            *status|=DEC_Rounded;               /* [but exact]  */
3929            }
3930          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3931          res->exponent+=adjust;                /* set the exponent.  */
3932          }
3933      #if DECSUBSET
3934        } /* extended  */
3935      #endif
3936      decFinish(res, set, &residue, status);      /* clean and finalize  */
3937      break;}
3938
3939    /* [NB: both fastpath and mainpath code below assume these cases  */
3940    /* (notably 0-0) have already been handled]  */
3941
3942    /* calculate the padding needed to align the operands  */
3943    padding=rhs->exponent-lhs->exponent;
3944
3945    /* Fastpath cases where the numbers are aligned and normal, the RHS  */
3946    /* is all in one unit, no operand rounding is needed, and no carry,  */
3947    /* lengthening, or borrow is needed  */
3948    if (padding==0
3949        && rhs->digits<=DECDPUN
3950        && rhs->exponent>=set->emin     /* [some normals drop through]  */
3951        && rhs->exponent<=set->emax-set->digits+1 /* [could clamp]  */
3952        && rhs->digits<=reqdigits
3953        && lhs->digits<=reqdigits) {
3954      Int partial=*lhs->lsu;
3955      if (!diffsign) {                  /* adding  */
3956        partial+=*rhs->lsu;
3957        if ((partial<=DECDPUNMAX)       /* result fits in unit  */
3958         && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change  */
3959             partial<(Int)powers[lhs->digits])) { /* ..  */
3960          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3961          *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS]  */
3962          break;
3963          }
3964        /* else drop out for careful add  */
3965        }
3966       else {                           /* signs differ  */
3967        partial-=*rhs->lsu;
3968        if (partial>0) { /* no borrow needed, and non-0 result  */
3969          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3970          *res->lsu=(Unit)partial;
3971          /* this could have reduced digits [but result>0]  */
3972          res->digits=decGetDigits(res->lsu, D2U(res->digits));
3973          break;
3974          }
3975        /* else drop out for careful subtract  */
3976        }
3977      }
3978
3979    /* Now align (pad) the lhs or rhs so they can be added or  */
3980    /* subtracted, as necessary.  If one number is much larger than  */
3981    /* the other (that is, if in plain form there is a least one  */
3982    /* digit between the lowest digit of one and the highest of the  */
3983    /* other) padding with up to DIGITS-1 trailing zeros may be  */
3984    /* needed; then apply rounding (as exotic rounding modes may be  */
3985    /* affected by the residue).  */
3986    rhsshift=0;               /* rhs shift to left (padding) in Units  */
3987    bits=lhs->bits;           /* assume sign is that of LHS  */
3988    mult=1;                   /* likely multiplier  */
3989
3990    /* [if padding==0 the operands are aligned; no padding is needed]  */
3991    if (padding!=0) {
3992      /* some padding needed; always pad the RHS, as any required  */
3993      /* padding can then be effected by a simple combination of  */
3994      /* shifts and a multiply  */
3995      Flag swapped=0;
3996      if (padding<0) {                  /* LHS needs the padding  */
3997        const decNumber *t;
3998        padding=-padding;               /* will be +ve  */
3999        bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS  */
4000        t=lhs; lhs=rhs; rhs=t;
4001        swapped=1;
4002        }
4003
4004      /* If, after pad, rhs would be longer than lhs by digits+1 or  */
4005      /* more then lhs cannot affect the answer, except as a residue,  */
4006      /* so only need to pad up to a length of DIGITS+1.  */
4007      if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4008        /* The RHS is sufficient  */
4009        /* for residue use the relative sign indication...  */
4010        Int shift=reqdigits-rhs->digits;     /* left shift needed  */
4011        residue=1;                           /* residue for rounding  */
4012        if (diffsign) residue=-residue;      /* signs differ  */
4013        /* copy, shortening if necessary  */
4014        decCopyFit(res, rhs, set, &residue, status);
4015        /* if it was already shorter, then need to pad with zeros  */
4016        if (shift>0) {
4017          res->digits=decShiftToMost(res->lsu, res->digits, shift);
4018          res->exponent-=shift;              /* adjust the exponent.  */
4019          }
4020        /* flip the result sign if unswapped and rhs was negated  */
4021        if (!swapped) res->bits^=negate;
4022        decFinish(res, set, &residue, status);    /* done  */
4023        break;}
4024
4025      /* LHS digits may affect result  */
4026      rhsshift=D2U(padding+1)-1;        /* this much by Unit shift ..  */
4027      mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication  */
4028      } /* padding needed  */
4029
4030    if (diffsign) mult=-mult;           /* signs differ  */
4031
4032    /* determine the longer operand  */
4033    maxdigits=rhs->digits+padding;      /* virtual length of RHS  */
4034    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4035
4036    /* Decide on the result buffer to use; if possible place directly  */
4037    /* into result.  */
4038    acc=res->lsu;                       /* assume add direct to result  */
4039    /* If destructive overlap, or the number is too long, or a carry or  */
4040    /* borrow to DIGITS+1 might be possible, a buffer must be used.  */
4041    /* [Might be worth more sophisticated tests when maxdigits==reqdigits]  */
4042    if ((maxdigits>=reqdigits)          /* is, or could be, too large  */
4043     || (res==rhs && rhsshift>0)) {     /* destructive overlap  */
4044      /* buffer needed, choose it; units for maxdigits digits will be  */
4045      /* needed, +1 Unit for carry or borrow  */
4046      Int need=D2U(maxdigits)+1;
4047      acc=accbuff;                      /* assume use local buffer  */
4048      if (need*sizeof(Unit)>sizeof(accbuff)) {
4049        /* printf("malloc add %ld %ld\n", need, sizeof(accbuff));  */
4050        allocacc=(Unit *)malloc(need*sizeof(Unit));
4051        if (allocacc==NULL) {           /* hopeless -- abandon  */
4052          *status|=DEC_Insufficient_storage;
4053          break;}
4054        acc=allocacc;
4055        }
4056      }
4057
4058    res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite..  */
4059    res->exponent=lhs->exponent;        /* .. operands (even if aliased)  */
4060
4061    #if DECTRACE
4062      decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4063      decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4064      printf("  :h: %ld %ld\n", rhsshift, mult);
4065    #endif
4066
4067    /* add [A+B*m] or subtract [A+B*(-m)]  */
4068    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4069                              rhs->lsu, D2U(rhs->digits),
4070                              rhsshift, acc, mult)
4071               *DECDPUN;           /* [units -> digits]  */
4072    if (res->digits<0) {           /* borrowed...  */
4073      res->digits=-res->digits;
4074      res->bits^=DECNEG;           /* flip the sign  */
4075      }
4076    #if DECTRACE
4077      decDumpAr('+', acc, D2U(res->digits));
4078    #endif
4079
4080    /* If a buffer was used the result must be copied back, possibly  */
4081    /* shortening.  (If no buffer was used then the result must have  */
4082    /* fit, so can't need rounding and residue must be 0.)  */
4083    residue=0;                     /* clear accumulator  */
4084    if (acc!=res->lsu) {
4085      #if DECSUBSET
4086      if (set->extended) {         /* round from first significant digit  */
4087      #endif
4088        /* remove leading zeros that were added due to rounding up to  */
4089        /* integral Units -- before the test for rounding.  */
4090        if (res->digits>reqdigits)
4091          res->digits=decGetDigits(acc, D2U(res->digits));
4092        decSetCoeff(res, set, acc, res->digits, &residue, status);
4093      #if DECSUBSET
4094        }
4095       else { /* subset arithmetic rounds from original significant digit  */
4096        /* May have an underestimate.  This only occurs when both  */
4097        /* numbers fit in DECDPUN digits and are padding with a  */
4098        /* negative multiple (-10, -100...) and the top digit(s) become  */
4099        /* 0.  (This only matters when using X3.274 rules where the  */
4100        /* leading zero could be included in the rounding.)  */
4101        if (res->digits<maxdigits) {
4102          *(acc+D2U(res->digits))=0; /* ensure leading 0 is there  */
4103          res->digits=maxdigits;
4104          }
4105         else {
4106          /* remove leading zeros that added due to rounding up to  */
4107          /* integral Units (but only those in excess of the original  */
4108          /* maxdigits length, unless extended) before test for rounding.  */
4109          if (res->digits>reqdigits) {
4110            res->digits=decGetDigits(acc, D2U(res->digits));
4111            if (res->digits<maxdigits) res->digits=maxdigits;
4112            }
4113          }
4114        decSetCoeff(res, set, acc, res->digits, &residue, status);
4115        /* Now apply rounding if needed before removing leading zeros.  */
4116        /* This is safe because subnormals are not a possibility  */
4117        if (residue!=0) {
4118          decApplyRound(res, set, residue, status);
4119          residue=0;                 /* did what needed to be done  */
4120          }
4121        } /* subset  */
4122      #endif
4123      } /* used buffer  */
4124
4125    /* strip leading zeros [these were left on in case of subset subtract]  */
4126    res->digits=decGetDigits(res->lsu, D2U(res->digits));
4127
4128    /* apply checks and rounding  */
4129    decFinish(res, set, &residue, status);
4130
4131    /* "When the sum of two operands with opposite signs is exactly  */
4132    /* zero, the sign of that sum shall be '+' in all rounding modes  */
4133    /* except round toward -Infinity, in which mode that sign shall be  */
4134    /* '-'."  [Subset zeros also never have '-', set by decFinish.]  */
4135    if (ISZERO(res) && diffsign
4136     #if DECSUBSET
4137     && set->extended
4138     #endif
4139     && (*status&DEC_Inexact)==0) {
4140      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign -  */
4141                                  else res->bits&=~DECNEG;  /* sign +  */
4142      }
4143    } while(0);                              /* end protected  */
4144
4145  if (allocacc!=NULL) free(allocacc);        /* drop any storage used  */
4146  #if DECSUBSET
4147  if (allocrhs!=NULL) free(allocrhs);        /* ..  */
4148  if (alloclhs!=NULL) free(alloclhs);        /* ..  */
4149  #endif
4150  return res;
4151  } /* decAddOp  */
4152
4153/* ------------------------------------------------------------------ */
4154/* decDivideOp -- division operation                                  */
4155/*                                                                    */
4156/*  This routine performs the calculations for all four division      */
4157/*  operators (divide, divideInteger, remainder, remainderNear).      */
4158/*                                                                    */
4159/*  C=A op B                                                          */
4160/*                                                                    */
4161/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4162/*   lhs is A                                                         */
4163/*   rhs is B                                                         */
4164/*   set is the context                                               */
4165/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4166/*   status is the usual accumulator                                  */
4167/*                                                                    */
4168/* C must have space for set->digits digits.                          */
4169/*                                                                    */
4170/* ------------------------------------------------------------------ */
4171/*   The underlying algorithm of this routine is the same as in the   */
4172/*   1981 S/370 implementation, that is, non-restoring long division  */
4173/*   with bi-unit (rather than bi-digit) estimation for each unit     */
4174/*   multiplier.  In this pseudocode overview, complications for the  */
4175/*   Remainder operators and division residues for exact rounding are */
4176/*   omitted for clarity.                                             */
4177/*                                                                    */
4178/*     Prepare operands and handle special values                     */
4179/*     Test for x/0 and then 0/x                                      */
4180/*     Exp =Exp1 - Exp2                                               */
4181/*     Exp =Exp +len(var1) -len(var2)                                 */
4182/*     Sign=Sign1 * Sign2                                             */
4183/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4184/*     Pad Var2 to same length as Var1                                */
4185/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4186/*     have=0                                                         */
4187/*     Do until (have=digits+1 OR residue=0)                          */
4188/*       if exp<0 then if integer divide/residue then leave           */
4189/*       this_unit=0                                                  */
4190/*       Do forever                                                   */
4191/*          compare numbers                                           */
4192/*          if <0 then leave inner_loop                               */
4193/*          if =0 then (* quick exit without subtract *) do           */
4194/*             this_unit=this_unit+1; output this_unit                */
4195/*             leave outer_loop; end                                  */
4196/*          Compare lengths of numbers (mantissae):                   */
4197/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4198/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4199/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4200/*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4201/*          if mult=0 then mult=1                                     */
4202/*          this_unit=this_unit+mult                                  */
4203/*          subtract                                                  */
4204/*          end inner_loop                                            */
4205/*        if have\=0 | this_unit\=0 then do                           */
4206/*          output this_unit                                          */
4207/*          have=have+1; end                                          */
4208/*        var2=var2/10                                                */
4209/*        exp=exp-1                                                   */
4210/*        end outer_loop                                              */
4211/*     exp=exp+1   -- set the proper exponent                         */
4212/*     if have=0 then generate answer=0                               */
4213/*     Return (Result is defined by Var1)                             */
4214/*                                                                    */
4215/* ------------------------------------------------------------------ */
4216/* Two working buffers are needed during the division; one (digits+   */
4217/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4218/* long subtractions.  These are acc and var1 respectively.           */
4219/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4220/* The static buffers may be larger than might be expected to allow   */
4221/* for calls from higher-level funtions (notable exp).                */
4222/* ------------------------------------------------------------------ */
4223static decNumber * decDivideOp(decNumber *res,
4224                               const decNumber *lhs, const decNumber *rhs,
4225                               decContext *set, Flag op, uInt *status) {
4226  #if DECSUBSET
4227  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
4228  decNumber *allocrhs=NULL;        /* .., rhs  */
4229  #endif
4230  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer  */
4231  Unit  *acc=accbuff;              /* -> accumulator array for result  */
4232  Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated  */
4233  Unit  *accnext;                  /* -> where next digit will go  */
4234  Int   acclength;                 /* length of acc needed [Units]  */
4235  Int   accunits;                  /* count of units accumulated  */
4236  Int   accdigits;                 /* count of digits accumulated  */
4237
4238  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  /* buffer for var1  */
4239  Unit  *var1=varbuff;             /* -> var1 array for long subtraction  */
4240  Unit  *varalloc=NULL;            /* -> allocated buffer, iff used  */
4241  Unit  *msu1;                     /* -> msu of var1  */
4242
4243  const Unit *var2;                /* -> var2 array  */
4244  const Unit *msu2;                /* -> msu of var2  */
4245  Int   msu2plus;                  /* msu2 plus one [does not vary]  */
4246  eInt  msu2pair;                  /* msu2 pair plus one [does not vary]  */
4247
4248  Int   var1units, var2units;      /* actual lengths  */
4249  Int   var2ulen;                  /* logical length (units)  */
4250  Int   var1initpad=0;             /* var1 initial padding (digits)  */
4251  Int   maxdigits;                 /* longest LHS or required acc length  */
4252  Int   mult;                      /* multiplier for subtraction  */
4253  Unit  thisunit;                  /* current unit being accumulated  */
4254  Int   residue;                   /* for rounding  */
4255  Int   reqdigits=set->digits;     /* requested DIGITS  */
4256  Int   exponent;                  /* working exponent  */
4257  Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded  */
4258  uByte bits;                      /* working sign  */
4259  Unit  *target;                   /* work  */
4260  const Unit *source;              /* ..  */
4261  uInt  const *pow;                /* ..  */
4262  Int   shift, cut;                /* ..  */
4263  #if DECSUBSET
4264  Int   dropped;                   /* work  */
4265  #endif
4266
4267  #if DECCHECK
4268  if (decCheckOperands(res, lhs, rhs, set)) return res;
4269  #endif
4270
4271  do {                             /* protect allocated storage  */
4272    #if DECSUBSET
4273    if (!set->extended) {
4274      /* reduce operands and set lostDigits status, as needed  */
4275      if (lhs->digits>reqdigits) {
4276        alloclhs=decRoundOperand(lhs, set, status);
4277        if (alloclhs==NULL) break;
4278        lhs=alloclhs;
4279        }
4280      if (rhs->digits>reqdigits) {
4281        allocrhs=decRoundOperand(rhs, set, status);
4282        if (allocrhs==NULL) break;
4283        rhs=allocrhs;
4284        }
4285      }
4286    #endif
4287    /* [following code does not require input rounding]  */
4288
4289    bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions  */
4290
4291    /* handle infinities and NaNs  */
4292    if (SPECIALARGS) {                  /* a special bit set  */
4293      if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4294        decNaNs(res, lhs, rhs, set, status);
4295        break;
4296        }
4297      /* one or two infinities  */
4298      if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite  */
4299        if (decNumberIsInfinite(rhs) || /* two infinities are invalid ..  */
4300            op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity  */
4301          *status|=DEC_Invalid_operation;
4302          break;
4303          }
4304        /* [Note that infinity/0 raises no exceptions]  */
4305        uprv_decNumberZero(res);
4306        res->bits=bits|DECINF;          /* set +/- infinity  */
4307        break;
4308        }
4309       else {                           /* RHS (divisor) is infinite  */
4310        residue=0;
4311        if (op&(REMAINDER|REMNEAR)) {
4312          /* result is [finished clone of] lhs  */
4313          decCopyFit(res, lhs, set, &residue, status);
4314          }
4315         else {  /* a division  */
4316          uprv_decNumberZero(res);
4317          res->bits=bits;               /* set +/- zero  */
4318          /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result  */
4319          /* is a 0 with infinitely negative exponent, clamped to minimum  */
4320          if (op&DIVIDE) {
4321            res->exponent=set->emin-set->digits+1;
4322            *status|=DEC_Clamped;
4323            }
4324          }
4325        decFinish(res, set, &residue, status);
4326        break;
4327        }
4328      }
4329
4330    /* handle 0 rhs (x/0)  */
4331    if (ISZERO(rhs)) {                  /* x/0 is always exceptional  */
4332      if (ISZERO(lhs)) {
4333        uprv_decNumberZero(res);             /* [after lhs test]  */
4334        *status|=DEC_Division_undefined;/* 0/0 will become NaN  */
4335        }
4336       else {
4337        uprv_decNumberZero(res);
4338        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4339         else {
4340          *status|=DEC_Division_by_zero; /* x/0  */
4341          res->bits=bits|DECINF;         /* .. is +/- Infinity  */
4342          }
4343        }
4344      break;}
4345
4346    /* handle 0 lhs (0/x)  */
4347    if (ISZERO(lhs)) {                  /* 0/x [x!=0]  */
4348      #if DECSUBSET
4349      if (!set->extended) uprv_decNumberZero(res);
4350       else {
4351      #endif
4352        if (op&DIVIDE) {
4353          residue=0;
4354          exponent=lhs->exponent-rhs->exponent; /* ideal exponent  */
4355          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4356          res->bits=bits;               /* sign as computed  */
4357          res->exponent=exponent;       /* exponent, too  */
4358          decFinalize(res, set, &residue, status);   /* check exponent  */
4359          }
4360         else if (op&DIVIDEINT) {
4361          uprv_decNumberZero(res);           /* integer 0  */
4362          res->bits=bits;               /* sign as computed  */
4363          }
4364         else {                         /* a remainder  */
4365          exponent=rhs->exponent;       /* [save in case overwrite]  */
4366          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4367          if (exponent<res->exponent) res->exponent=exponent; /* use lower  */
4368          }
4369      #if DECSUBSET
4370        }
4371      #endif
4372      break;}
4373
4374    /* Precalculate exponent.  This starts off adjusted (and hence fits  */
4375    /* in 31 bits) and becomes the usual unadjusted exponent as the  */
4376    /* division proceeds.  The order of evaluation is important, here,  */
4377    /* to avoid wrap.  */
4378    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4379
4380    /* If the working exponent is -ve, then some quick exits are  */
4381    /* possible because the quotient is known to be <1  */
4382    /* [for REMNEAR, it needs to be < -1, as -0.5 could need work]  */
4383    if (exponent<0 && !(op==DIVIDE)) {
4384      if (op&DIVIDEINT) {
4385        uprv_decNumberZero(res);                  /* integer part is 0  */
4386        #if DECSUBSET
4387        if (set->extended)
4388        #endif
4389          res->bits=bits;                    /* set +/- zero  */
4390        break;}
4391      /* fastpath remainders so long as the lhs has the smaller  */
4392      /* (or equal) exponent  */
4393      if (lhs->exponent<=rhs->exponent) {
4394        if (op&REMAINDER || exponent<-1) {
4395          /* It is REMAINDER or safe REMNEAR; result is [finished  */
4396          /* clone of] lhs  (r = x - 0*y)  */
4397          residue=0;
4398          decCopyFit(res, lhs, set, &residue, status);
4399          decFinish(res, set, &residue, status);
4400          break;
4401          }
4402        /* [unsafe REMNEAR drops through]  */
4403        }
4404      } /* fastpaths  */
4405
4406    /* Long (slow) division is needed; roll up the sleeves... */
4407
4408    /* The accumulator will hold the quotient of the division.  */
4409    /* If it needs to be too long for stack storage, then allocate.  */
4410    acclength=D2U(reqdigits+DECDPUN);   /* in Units  */
4411    if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4412      /* printf("malloc dvacc %ld units\n", acclength);  */
4413      allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4414      if (allocacc==NULL) {             /* hopeless -- abandon  */
4415        *status|=DEC_Insufficient_storage;
4416        break;}
4417      acc=allocacc;                     /* use the allocated space  */
4418      }
4419
4420    /* var1 is the padded LHS ready for subtractions.  */
4421    /* If it needs to be too long for stack storage, then allocate.  */
4422    /* The maximum units needed for var1 (long subtraction) is:  */
4423    /* Enough for  */
4424    /*     (rhs->digits+reqdigits-1) -- to allow full slide to right  */
4425    /* or  (lhs->digits)             -- to allow for long lhs  */
4426    /* whichever is larger  */
4427    /*   +1                -- for rounding of slide to right  */
4428    /*   +1                -- for leading 0s  */
4429    /*   +1                -- for pre-adjust if a remainder or DIVIDEINT  */
4430    /* [Note: unused units do not participate in decUnitAddSub data]  */
4431    maxdigits=rhs->digits+reqdigits-1;
4432    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4433    var1units=D2U(maxdigits)+2;
4434    /* allocate a guard unit above msu1 for REMAINDERNEAR  */
4435    if (!(op&DIVIDE)) var1units++;
4436    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4437      /* printf("malloc dvvar %ld units\n", var1units+1);  */
4438      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4439      if (varalloc==NULL) {             /* hopeless -- abandon  */
4440        *status|=DEC_Insufficient_storage;
4441        break;}
4442      var1=varalloc;                    /* use the allocated space  */
4443      }
4444
4445    /* Extend the lhs and rhs to full long subtraction length.  The lhs  */
4446    /* is truly extended into the var1 buffer, with 0 padding, so a  */
4447    /* subtract in place is always possible.  The rhs (var2) has  */
4448    /* virtual padding (implemented by decUnitAddSub).  */
4449    /* One guard unit was allocated above msu1 for rem=rem+rem in  */
4450    /* REMAINDERNEAR.  */
4451    msu1=var1+var1units-1;              /* msu of var1  */
4452    source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array  */
4453    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4454    for (; target>=var1; target--) *target=0;
4455
4456    /* rhs (var2) is left-aligned with var1 at the start  */
4457    var2ulen=var1units;                 /* rhs logical length (units)  */
4458    var2units=D2U(rhs->digits);         /* rhs actual length (units)  */
4459    var2=rhs->lsu;                      /* -> rhs array  */
4460    msu2=var2+var2units-1;              /* -> msu of var2 [never changes]  */
4461    /* now set up the variables which will be used for estimating the  */
4462    /* multiplication factor.  If these variables are not exact, add  */
4463    /* 1 to make sure that the multiplier is never overestimated.  */
4464    msu2plus=*msu2;                     /* it's value ..  */
4465    if (var2units>1) msu2plus++;        /* .. +1 if any more  */
4466    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair ..  */
4467    if (var2units>1) {                  /* .. [else treat 2nd as 0]  */
4468      msu2pair+=*(msu2-1);              /* ..  */
4469      if (var2units>2) msu2pair++;      /* .. +1 if any more  */
4470      }
4471
4472    /* The calculation is working in units, which may have leading zeros,  */
4473    /* but the exponent was calculated on the assumption that they are  */
4474    /* both left-aligned.  Adjust the exponent to compensate: add the  */
4475    /* number of leading zeros in var1 msu and subtract those in var2 msu.  */
4476    /* [This is actually done by counting the digits and negating, as  */
4477    /* lead1=DECDPUN-digits1, and similarly for lead2.]  */
4478    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4479    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4480
4481    /* Now, if doing an integer divide or remainder, ensure that  */
4482    /* the result will be Unit-aligned.  To do this, shift the var1  */
4483    /* accumulator towards least if need be.  (It's much easier to  */
4484    /* do this now than to reassemble the residue afterwards, if  */
4485    /* doing a remainder.)  Also ensure the exponent is not negative.  */
4486    if (!(op&DIVIDE)) {
4487      Unit *u;                          /* work  */
4488      /* save the initial 'false' padding of var1, in digits  */
4489      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4490      /* Determine the shift to do.  */
4491      if (exponent<0) cut=-exponent;
4492       else cut=DECDPUN-exponent%DECDPUN;
4493      decShiftToLeast(var1, var1units, cut);
4494      exponent+=cut;                    /* maintain numerical value  */
4495      var1initpad-=cut;                 /* .. and reduce padding  */
4496      /* clean any most-significant units which were just emptied  */
4497      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4498      } /* align  */
4499     else { /* is DIVIDE  */
4500      maxexponent=lhs->exponent-rhs->exponent;    /* save  */
4501      /* optimization: if the first iteration will just produce 0,  */
4502      /* preadjust to skip it [valid for DIVIDE only]  */
4503      if (*msu1<*msu2) {
4504        var2ulen--;                     /* shift down  */
4505        exponent-=DECDPUN;              /* update the exponent  */
4506        }
4507      }
4508
4509    /* ---- start the long-division loops ------------------------------  */
4510    accunits=0;                         /* no units accumulated yet  */
4511    accdigits=0;                        /* .. or digits  */
4512    accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1]  */
4513    for (;;) {                          /* outer forever loop  */
4514      thisunit=0;                       /* current unit assumed 0  */
4515      /* find the next unit  */
4516      for (;;) {                        /* inner forever loop  */
4517        /* strip leading zero units [from either pre-adjust or from  */
4518        /* subtract last time around].  Leave at least one unit.  */
4519        for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4520
4521        if (var1units<var2ulen) break;       /* var1 too low for subtract  */
4522        if (var1units==var2ulen) {           /* unit-by-unit compare needed  */
4523          /* compare the two numbers, from msu  */
4524          const Unit *pv1, *pv2;
4525          Unit v2;                           /* units to compare  */
4526          pv2=msu2;                          /* -> msu  */
4527          for (pv1=msu1; ; pv1--, pv2--) {
4528            /* v1=*pv1 -- always OK  */
4529            v2=0;                            /* assume in padding  */
4530            if (pv2>=var2) v2=*pv2;          /* in range  */
4531            if (*pv1!=v2) break;             /* no longer the same  */
4532            if (pv1==var1) break;            /* done; leave pv1 as is  */
4533            }
4534          /* here when all inspected or a difference seen  */
4535          if (*pv1<v2) break;                /* var1 too low to subtract  */
4536          if (*pv1==v2) {                    /* var1 == var2  */
4537            /* reach here if var1 and var2 are identical; subtraction  */
4538            /* would increase digit by one, and the residue will be 0 so  */
4539            /* the calculation is done; leave the loop with residue=0.  */
4540            thisunit++;                      /* as though subtracted  */
4541            *var1=0;                         /* set var1 to 0  */
4542            var1units=1;                     /* ..  */
4543            break;  /* from inner  */
4544            } /* var1 == var2  */
4545          /* *pv1>v2.  Prepare for real subtraction; the lengths are equal  */
4546          /* Estimate the multiplier (there's always a msu1-1)...  */
4547          /* Bring in two units of var2 to provide a good estimate.  */
4548          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4549          } /* lengths the same  */
4550         else { /* var1units > var2ulen, so subtraction is safe  */
4551          /* The var2 msu is one unit towards the lsu of the var1 msu,  */
4552          /* so only one unit for var2 can be used.  */
4553          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4554          }
4555        if (mult==0) mult=1;                 /* must always be at least 1  */
4556        /* subtraction needed; var1 is > var2  */
4557        thisunit=(Unit)(thisunit+mult);      /* accumulate  */
4558        /* subtract var1-var2, into var1; only the overlap needs  */
4559        /* processing, as this is an in-place calculation  */
4560        shift=var2ulen-var2units;
4561        #if DECTRACE
4562          decDumpAr('1', &var1[shift], var1units-shift);
4563          decDumpAr('2', var2, var2units);
4564          printf("m=%ld\n", -mult);
4565        #endif
4566        decUnitAddSub(&var1[shift], var1units-shift,
4567                      var2, var2units, 0,
4568                      &var1[shift], -mult);
4569        #if DECTRACE
4570          decDumpAr('#', &var1[shift], var1units-shift);
4571        #endif
4572        /* var1 now probably has leading zeros; these are removed at the  */
4573        /* top of the inner loop.  */
4574        } /* inner loop  */
4575
4576      /* The next unit has been calculated in full; unless it's a  */
4577      /* leading zero, add to acc  */
4578      if (accunits!=0 || thisunit!=0) {      /* is first or non-zero  */
4579        *accnext=thisunit;                   /* store in accumulator  */
4580        /* account exactly for the new digits  */
4581        if (accunits==0) {
4582          accdigits++;                       /* at least one  */
4583          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4584          }
4585         else accdigits+=DECDPUN;
4586        accunits++;                          /* update count  */
4587        accnext--;                           /* ready for next  */
4588        if (accdigits>reqdigits) break;      /* have enough digits  */
4589        }
4590
4591      /* if the residue is zero, the operation is done (unless divide  */
4592      /* or divideInteger and still not enough digits yet)  */
4593      if (*var1==0 && var1units==1) {        /* residue is 0  */
4594        if (op&(REMAINDER|REMNEAR)) break;
4595        if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4596        /* [drop through if divideInteger]  */
4597        }
4598      /* also done enough if calculating remainder or integer  */
4599      /* divide and just did the last ('units') unit  */
4600      if (exponent==0 && !(op&DIVIDE)) break;
4601
4602      /* to get here, var1 is less than var2, so divide var2 by the per-  */
4603      /* Unit power of ten and go for the next digit  */
4604      var2ulen--;                            /* shift down  */
4605      exponent-=DECDPUN;                     /* update the exponent  */
4606      } /* outer loop  */
4607
4608    /* ---- division is complete ---------------------------------------  */
4609    /* here: acc      has at least reqdigits+1 of good results (or fewer  */
4610    /*                if early stop), starting at accnext+1 (its lsu)  */
4611    /*       var1     has any residue at the stopping point  */
4612    /*       accunits is the number of digits collected in acc  */
4613    if (accunits==0) {             /* acc is 0  */
4614      accunits=1;                  /* show have a unit ..  */
4615      accdigits=1;                 /* ..  */
4616      *accnext=0;                  /* .. whose value is 0  */
4617      }
4618     else accnext++;               /* back to last placed  */
4619    /* accnext now -> lowest unit of result  */
4620
4621    residue=0;                     /* assume no residue  */
4622    if (op&DIVIDE) {
4623      /* record the presence of any residue, for rounding  */
4624      if (*var1!=0 || var1units>1) residue=1;
4625       else { /* no residue  */
4626        /* Had an exact division; clean up spurious trailing 0s.  */
4627        /* There will be at most DECDPUN-1, from the final multiply,  */
4628        /* and then only if the result is non-0 (and even) and the  */
4629        /* exponent is 'loose'.  */
4630        #if DECDPUN>1
4631        Unit lsu=*accnext;
4632        if (!(lsu&0x01) && (lsu!=0)) {
4633          /* count the trailing zeros  */
4634          Int drop=0;
4635          for (;; drop++) {    /* [will terminate because lsu!=0]  */
4636            if (exponent>=maxexponent) break;     /* don't chop real 0s  */
4637            #if DECDPUN<=4
4638              if ((lsu-QUOT10(lsu, drop+1)
4639                  *powers[drop+1])!=0) break;     /* found non-0 digit  */
4640            #else
4641              if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit  */
4642            #endif
4643            exponent++;
4644            }
4645          if (drop>0) {
4646            accunits=decShiftToLeast(accnext, accunits, drop);
4647            accdigits=decGetDigits(accnext, accunits);
4648            accunits=D2U(accdigits);
4649            /* [exponent was adjusted in the loop]  */
4650            }
4651          } /* neither odd nor 0  */
4652        #endif
4653        } /* exact divide  */
4654      } /* divide  */
4655     else /* op!=DIVIDE */ {
4656      /* check for coefficient overflow  */
4657      if (accdigits+exponent>reqdigits) {
4658        *status|=DEC_Division_impossible;
4659        break;
4660        }
4661      if (op & (REMAINDER|REMNEAR)) {
4662        /* [Here, the exponent will be 0, because var1 was adjusted  */
4663        /* appropriately.]  */
4664        Int postshift;                       /* work  */
4665        Flag wasodd=0;                       /* integer was odd  */
4666        Unit *quotlsu;                       /* for save  */
4667        Int  quotdigits;                     /* ..  */
4668
4669        bits=lhs->bits;                      /* remainder sign is always as lhs  */
4670
4671        /* Fastpath when residue is truly 0 is worthwhile [and  */
4672        /* simplifies the code below]  */
4673        if (*var1==0 && var1units==1) {      /* residue is 0  */
4674          Int exp=lhs->exponent;             /* save min(exponents)  */
4675          if (rhs->exponent<exp) exp=rhs->exponent;
4676          uprv_decNumberZero(res);                /* 0 coefficient  */
4677          #if DECSUBSET
4678          if (set->extended)
4679          #endif
4680          res->exponent=exp;                 /* .. with proper exponent  */
4681          res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4682          decFinish(res, set, &residue, status);   /* might clamp  */
4683          break;
4684          }
4685        /* note if the quotient was odd  */
4686        if (*accnext & 0x01) wasodd=1;       /* acc is odd  */
4687        quotlsu=accnext;                     /* save in case need to reinspect  */
4688        quotdigits=accdigits;                /* ..  */
4689
4690        /* treat the residue, in var1, as the value to return, via acc  */
4691        /* calculate the unused zero digits.  This is the smaller of:  */
4692        /*   var1 initial padding (saved above)  */
4693        /*   var2 residual padding, which happens to be given by:  */
4694        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4695        /* [the 'exponent' term accounts for the shifts during divide]  */
4696        if (var1initpad<postshift) postshift=var1initpad;
4697
4698        /* shift var1 the requested amount, and adjust its digits  */
4699        var1units=decShiftToLeast(var1, var1units, postshift);
4700        accnext=var1;
4701        accdigits=decGetDigits(var1, var1units);
4702        accunits=D2U(accdigits);
4703
4704        exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs  */
4705        if (rhs->exponent<exponent) exponent=rhs->exponent;
4706
4707        /* Now correct the result if doing remainderNear; if it  */
4708        /* (looking just at coefficients) is > rhs/2, or == rhs/2 and  */
4709        /* the integer was odd then the result should be rem-rhs.  */
4710        if (op&REMNEAR) {
4711          Int compare, tarunits;        /* work  */
4712          Unit *up;                     /* ..  */
4713          /* calculate remainder*2 into the var1 buffer (which has  */
4714          /* 'headroom' of an extra unit and hence enough space)  */
4715          /* [a dedicated 'double' loop would be faster, here]  */
4716          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4717                                 0, accnext, 1);
4718          /* decDumpAr('r', accnext, tarunits);  */
4719
4720          /* Here, accnext (var1) holds tarunits Units with twice the  */
4721          /* remainder's coefficient, which must now be compared to the  */
4722          /* RHS.  The remainder's exponent may be smaller than the RHS's.  */
4723          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4724                                 rhs->exponent-exponent);
4725          if (compare==BADINT) {             /* deep trouble  */
4726            *status|=DEC_Insufficient_storage;
4727            break;}
4728
4729          /* now restore the remainder by dividing by two; the lsu  */
4730          /* is known to be even.  */
4731          for (up=accnext; up<accnext+tarunits; up++) {
4732            Int half;              /* half to add to lower unit  */
4733            half=*up & 0x01;
4734            *up/=2;                /* [shift]  */
4735            if (!half) continue;
4736            *(up-1)+=(DECDPUNMAX+1)/2;
4737            }
4738          /* [accunits still describes the original remainder length]  */
4739
4740          if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed  */
4741            Int exp, expunits, exprem;       /* work  */
4742            /* This is effectively causing round-up of the quotient,  */
4743            /* so if it was the rare case where it was full and all  */
4744            /* nines, it would overflow and hence division-impossible  */
4745            /* should be raised  */
4746            Flag allnines=0;                 /* 1 if quotient all nines  */
4747            if (quotdigits==reqdigits) {     /* could be borderline  */
4748              for (up=quotlsu; ; up++) {
4749                if (quotdigits>DECDPUN) {
4750                  if (*up!=DECDPUNMAX) break;/* non-nines  */
4751                  }
4752                 else {                      /* this is the last Unit  */
4753                  if (*up==powers[quotdigits]-1) allnines=1;
4754                  break;
4755                  }
4756                quotdigits-=DECDPUN;         /* checked those digits  */
4757                } /* up  */
4758              } /* borderline check  */
4759            if (allnines) {
4760              *status|=DEC_Division_impossible;
4761              break;}
4762
4763            /* rem-rhs is needed; the sign will invert.  Again, var1  */
4764            /* can safely be used for the working Units array.  */
4765            exp=rhs->exponent-exponent;      /* RHS padding needed  */
4766            /* Calculate units and remainder from exponent.  */
4767            expunits=exp/DECDPUN;
4768            exprem=exp%DECDPUN;
4769            /* subtract [A+B*(-m)]; the result will always be negative  */
4770            accunits=-decUnitAddSub(accnext, accunits,
4771                                    rhs->lsu, D2U(rhs->digits),
4772                                    expunits, accnext, -(Int)powers[exprem]);
4773            accdigits=decGetDigits(accnext, accunits); /* count digits exactly  */
4774            accunits=D2U(accdigits);    /* and recalculate the units for copy  */
4775            /* [exponent is as for original remainder]  */
4776            bits^=DECNEG;               /* flip the sign  */
4777            }
4778          } /* REMNEAR  */
4779        } /* REMAINDER or REMNEAR  */
4780      } /* not DIVIDE  */
4781
4782    /* Set exponent and bits  */
4783    res->exponent=exponent;
4784    res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4785
4786    /* Now the coefficient.  */
4787    decSetCoeff(res, set, accnext, accdigits, &residue, status);
4788
4789    decFinish(res, set, &residue, status);   /* final cleanup  */
4790
4791    #if DECSUBSET
4792    /* If a divide then strip trailing zeros if subset [after round]  */
4793    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4794    #endif
4795    } while(0);                              /* end protected  */
4796
4797  if (varalloc!=NULL) free(varalloc);   /* drop any storage used  */
4798  if (allocacc!=NULL) free(allocacc);   /* ..  */
4799  #if DECSUBSET
4800  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
4801  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
4802  #endif
4803  return res;
4804  } /* decDivideOp  */
4805
4806/* ------------------------------------------------------------------ */
4807/* decMultiplyOp -- multiplication operation                          */
4808/*                                                                    */
4809/*  This routine performs the multiplication C=A x B.                 */
4810/*                                                                    */
4811/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4812/*   lhs is A                                                         */
4813/*   rhs is B                                                         */
4814/*   set is the context                                               */
4815/*   status is the usual accumulator                                  */
4816/*                                                                    */
4817/* C must have space for set->digits digits.                          */
4818/*                                                                    */
4819/* ------------------------------------------------------------------ */
4820/* 'Classic' multiplication is used rather than Karatsuba, as the     */
4821/* latter would give only a minor improvement for the short numbers   */
4822/* expected to be handled most (and uses much more memory).           */
4823/*                                                                    */
4824/* There are two major paths here: the general-purpose ('old code')   */
4825/* path which handles all DECDPUN values, and a fastpath version      */
4826/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4827/* than two calls to decUnitAddSub would be made.                     */
4828/*                                                                    */
4829/* The fastpath version lumps units together into 8-digit or 9-digit  */
4830/* chunks, and also uses a lazy carry strategy to minimise expensive  */
4831/* 64-bit divisions.  The chunks are then broken apart again into     */
4832/* units for continuing processing.  Despite this overhead, the       */
4833/* fastpath can speed up some 16-digit operations by 10x (and much    */
4834/* more for higher-precision calculations).                           */
4835/*                                                                    */
4836/* A buffer always has to be used for the accumulator; in the         */
4837/* fastpath, buffers are also always needed for the chunked copies of */
4838/* of the operand coefficients.                                       */
4839/* Static buffers are larger than needed just for multiply, to allow  */
4840/* for calls from other operations (notably exp).                     */
4841/* ------------------------------------------------------------------ */
4842#define FASTMUL (DECUSE64 && DECDPUN<5)
4843static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4844                                 const decNumber *rhs, decContext *set,
4845                                 uInt *status) {
4846  Int    accunits;                 /* Units of accumulator in use  */
4847  Int    exponent;                 /* work  */
4848  Int    residue=0;                /* rounding residue  */
4849  uByte  bits;                     /* result sign  */
4850  Unit  *acc;                      /* -> accumulator Unit array  */
4851  Int    needbytes;                /* size calculator  */
4852  void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated  */
4853  Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0,  */
4854                                   /* *4 for calls from other operations)  */
4855  const Unit *mer, *mermsup;       /* work  */
4856  Int   madlength;                 /* Units in multiplicand  */
4857  Int   shift;                     /* Units to shift multiplicand by  */
4858
4859  #if FASTMUL
4860    /* if DECDPUN is 1 or 3 work in base 10**9, otherwise  */
4861    /* (DECDPUN is 2 or 4) then work in base 10**8  */
4862    #if DECDPUN & 1                /* odd  */
4863      #define FASTBASE 1000000000  /* base  */
4864      #define FASTDIGS          9  /* digits in base  */
4865      #define FASTLAZY         18  /* carry resolution point [1->18]  */
4866    #else
4867      #define FASTBASE  100000000
4868      #define FASTDIGS          8
4869      #define FASTLAZY       1844  /* carry resolution point [1->1844]  */
4870    #endif
4871    /* three buffers are used, two for chunked copies of the operands  */
4872    /* (base 10**8 or base 10**9) and one base 2**64 accumulator with  */
4873    /* lazy carry evaluation  */
4874    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4875    uInt  *zlhi=zlhibuff;                 /* -> lhs array  */
4876    uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated  */
4877    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4878    uInt  *zrhi=zrhibuff;                 /* -> rhs array  */
4879    uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated  */
4880    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0)  */
4881    /* [allocacc is shared for both paths, as only one will run]  */
4882    uLong *zacc=zaccbuff;          /* -> accumulator array for exact result  */
4883    #if DECDPUN==1
4884    Int    zoff;                   /* accumulator offset  */
4885    #endif
4886    uInt  *lip, *rip;              /* item pointers  */
4887    uInt  *lmsi, *rmsi;            /* most significant items  */
4888    Int    ilhs, irhs, iacc;       /* item counts in the arrays  */
4889    Int    lazy;                   /* lazy carry counter  */
4890    uLong  lcarry;                 /* uLong carry  */
4891    uInt   carry;                  /* carry (NB not uLong)  */
4892    Int    count;                  /* work  */
4893    const  Unit *cup;              /* ..  */
4894    Unit  *up;                     /* ..  */
4895    uLong *lp;                     /* ..  */
4896    Int    p;                      /* ..  */
4897  #endif
4898
4899  #if DECSUBSET
4900    decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated  */
4901    decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated  */
4902  #endif
4903
4904  #if DECCHECK
4905  if (decCheckOperands(res, lhs, rhs, set)) return res;
4906  #endif
4907
4908  /* precalculate result sign  */
4909  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4910
4911  /* handle infinities and NaNs  */
4912  if (SPECIALARGS) {               /* a special bit set  */
4913    if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4914      decNaNs(res, lhs, rhs, set, status);
4915      return res;}
4916    /* one or two infinities; Infinity * 0 is invalid  */
4917    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4918      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4919      *status|=DEC_Invalid_operation;
4920      return res;}
4921    uprv_decNumberZero(res);
4922    res->bits=bits|DECINF;         /* infinity  */
4923    return res;}
4924
4925  /* For best speed, as in DMSRCN [the original Rexx numerics  */
4926  /* module], use the shorter number as the multiplier (rhs) and  */
4927  /* the longer as the multiplicand (lhs) to minimise the number of  */
4928  /* adds (partial products)  */
4929  if (lhs->digits<rhs->digits) {   /* swap...  */
4930    const decNumber *hold=lhs;
4931    lhs=rhs;
4932    rhs=hold;
4933    }
4934
4935  do {                             /* protect allocated storage  */
4936    #if DECSUBSET
4937    if (!set->extended) {
4938      /* reduce operands and set lostDigits status, as needed  */
4939      if (lhs->digits>set->digits) {
4940        alloclhs=decRoundOperand(lhs, set, status);
4941        if (alloclhs==NULL) break;
4942        lhs=alloclhs;
4943        }
4944      if (rhs->digits>set->digits) {
4945        allocrhs=decRoundOperand(rhs, set, status);
4946        if (allocrhs==NULL) break;
4947        rhs=allocrhs;
4948        }
4949      }
4950    #endif
4951    /* [following code does not require input rounding]  */
4952
4953    #if FASTMUL                    /* fastpath can be used  */
4954    /* use the fast path if there are enough digits in the shorter  */
4955    /* operand to make the setup and takedown worthwhile  */
4956    #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls  */
4957    if (rhs->digits>NEEDTWO) {     /* use fastpath...  */
4958      /* calculate the number of elements in each array  */
4959      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling]  */
4960      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* ..  */
4961      iacc=ilhs+irhs;
4962
4963      /* allocate buffers if required, as usual  */
4964      needbytes=ilhs*sizeof(uInt);
4965      if (needbytes>(Int)sizeof(zlhibuff)) {
4966        alloclhi=(uInt *)malloc(needbytes);
4967        zlhi=alloclhi;}
4968      needbytes=irhs*sizeof(uInt);
4969      if (needbytes>(Int)sizeof(zrhibuff)) {
4970        allocrhi=(uInt *)malloc(needbytes);
4971        zrhi=allocrhi;}
4972
4973      /* Allocating the accumulator space needs a special case when  */
4974      /* DECDPUN=1 because when converting the accumulator to Units  */
4975      /* after the multiplication each 8-byte item becomes 9 1-byte  */
4976      /* units.  Therefore iacc extra bytes are needed at the front  */
4977      /* (rounded up to a multiple of 8 bytes), and the uLong  */
4978      /* accumulator starts offset the appropriate number of units  */
4979      /* to the right to avoid overwrite during the unchunking.  */
4980      needbytes=iacc*sizeof(uLong);
4981      #if DECDPUN==1
4982      zoff=(iacc+7)/8;        /* items to offset by  */
4983      needbytes+=zoff*8;
4984      #endif
4985      if (needbytes>(Int)sizeof(zaccbuff)) {
4986        allocacc=(uLong *)malloc(needbytes);
4987        zacc=(uLong *)allocacc;}
4988      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4989        *status|=DEC_Insufficient_storage;
4990        break;}
4991
4992      acc=(Unit *)zacc;       /* -> target Unit array  */
4993      #if DECDPUN==1
4994      zacc+=zoff;             /* start uLong accumulator to right  */
4995      #endif
4996
4997      /* assemble the chunked copies of the left and right sides  */
4998      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
4999        for (p=0, *lip=0; p<FASTDIGS && count>0;
5000             p+=DECDPUN, cup++, count-=DECDPUN)
5001          *lip+=*cup*powers[p];
5002      lmsi=lip-1;     /* save -> msi  */
5003      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5004        for (p=0, *rip=0; p<FASTDIGS && count>0;
5005             p+=DECDPUN, cup++, count-=DECDPUN)
5006          *rip+=*cup*powers[p];
5007      rmsi=rip-1;     /* save -> msi  */
5008
5009      /* zero the accumulator  */
5010      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5011
5012      /* Start the multiplication */
5013      /* Resolving carries can dominate the cost of accumulating the  */
5014      /* partial products, so this is only done when necessary.  */
5015      /* Each uLong item in the accumulator can hold values up to  */
5016      /* 2**64-1, and each partial product can be as large as  */
5017      /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to  */
5018      /* itself 18.4 times in a uLong without overflowing, so during  */
5019      /* the main calculation resolution is carried out every 18th  */
5020      /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the  */
5021      /* partial products can be added to themselves 1844.6 times in  */
5022      /* a uLong without overflowing, so intermediate carry  */
5023      /* resolution occurs only every 14752 digits.  Hence for common  */
5024      /* short numbers usually only the one final carry resolution  */
5025      /* occurs.  */
5026      /* (The count is set via FASTLAZY to simplify experiments to  */
5027      /* measure the value of this approach: a 35% improvement on a  */
5028      /* [34x34] multiply.)  */
5029      lazy=FASTLAZY;                         /* carry delay count  */
5030      for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs  */
5031        lp=zacc+(rip-zrhi);                  /* where to add the lhs  */
5032        for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs  */
5033          *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line]  */
5034          } /* lip loop  */
5035        lazy--;
5036        if (lazy>0 && rip!=rmsi) continue;
5037        lazy=FASTLAZY;                       /* reset delay count  */
5038        /* spin up the accumulator resolving overflows  */
5039        for (lp=zacc; lp<zacc+iacc; lp++) {
5040          if (*lp<FASTBASE) continue;        /* it fits  */
5041          lcarry=*lp/FASTBASE;               /* top part [slow divide]  */
5042          /* lcarry can exceed 2**32-1, so check again; this check  */
5043          /* and occasional extra divide (slow) is well worth it, as  */
5044          /* it allows FASTLAZY to be increased to 18 rather than 4  */
5045          /* in the FASTDIGS=9 case  */
5046          if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual]  */
5047           else { /* two-place carry [fairly rare]  */
5048            uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part  */
5049            *(lp+2)+=carry2;                        /* add to item+2  */
5050            *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow]  */
5051            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline]  */
5052            }
5053          *(lp+1)+=carry;                    /* add to item above [inline]  */
5054          *lp-=((uLong)FASTBASE*carry);      /* [inline]  */
5055          } /* carry resolution  */
5056        } /* rip loop  */
5057
5058      /* The multiplication is complete; time to convert back into  */
5059      /* units.  This can be done in-place in the accumulator and in  */
5060      /* 32-bit operations, because carries were resolved after the  */
5061      /* final add.  This needs N-1 divides and multiplies for  */
5062      /* each item in the accumulator (which will become up to N  */
5063      /* units, where 2<=N<=9).  */
5064      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5065        uInt item=(uInt)*lp;                 /* decapitate to uInt  */
5066        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5067          uInt part=item/(DECDPUNMAX+1);
5068          *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5069          item=part;
5070          } /* p  */
5071        *up=(Unit)item; up++;                /* [final needs no division]  */
5072        } /* lp  */
5073      accunits=up-acc;                       /* count of units  */
5074      }
5075     else { /* here to use units directly, without chunking ['old code']  */
5076    #endif
5077
5078      /* if accumulator will be too long for local storage, then allocate  */
5079      acc=accbuff;                 /* -> assume buffer for accumulator  */
5080      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5081      if (needbytes>(Int)sizeof(accbuff)) {
5082        allocacc=(Unit *)malloc(needbytes);
5083        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5084        acc=(Unit *)allocacc;                /* use the allocated space  */
5085        }
5086
5087      /* Now the main long multiplication loop */
5088      /* Unlike the equivalent in the IBM Java implementation, there  */
5089      /* is no advantage in calculating from msu to lsu.  So, do it  */
5090      /* by the book, as it were.  */
5091      /* Each iteration calculates ACC=ACC+MULTAND*MULT  */
5092      accunits=1;                  /* accumulator starts at '0'  */
5093      *acc=0;                      /* .. (lsu=0)  */
5094      shift=0;                     /* no multiplicand shift at first  */
5095      madlength=D2U(lhs->digits);  /* this won't change  */
5096      mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier  */
5097
5098      for (mer=rhs->lsu; mer<mermsup; mer++) {
5099        /* Here, *mer is the next Unit in the multiplier to use  */
5100        /* If non-zero [optimization] add it...  */
5101        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5102                                            lhs->lsu, madlength, 0,
5103                                            &acc[shift], *mer)
5104                                            + shift;
5105         else { /* extend acc with a 0; it will be used shortly  */
5106          *(acc+accunits)=0;       /* [this avoids length of <=0 later]  */
5107          accunits++;
5108          }
5109        /* multiply multiplicand by 10**DECDPUN for next Unit to left  */
5110        shift++;                   /* add this for 'logical length'  */
5111        } /* n  */
5112    #if FASTMUL
5113      } /* unchunked units  */
5114    #endif
5115    /* common end-path  */
5116    #if DECTRACE
5117      decDumpAr('*', acc, accunits);         /* Show exact result  */
5118    #endif
5119
5120    /* acc now contains the exact result of the multiplication,  */
5121    /* possibly with a leading zero unit; build the decNumber from  */
5122    /* it, noting if any residue  */
5123    res->bits=bits;                          /* set sign  */
5124    res->digits=decGetDigits(acc, accunits); /* count digits exactly  */
5125
5126    /* There can be a 31-bit wrap in calculating the exponent.  */
5127    /* This can only happen if both input exponents are negative and  */
5128    /* both their magnitudes are large.  If there was a wrap, set a  */
5129    /* safe very negative exponent, from which decFinalize() will  */
5130    /* raise a hard underflow shortly.  */
5131    exponent=lhs->exponent+rhs->exponent;    /* calculate exponent  */
5132    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5133      exponent=-2*DECNUMMAXE;                /* force underflow  */
5134    res->exponent=exponent;                  /* OK to overwrite now  */
5135
5136
5137    /* Set the coefficient.  If any rounding, residue records  */
5138    decSetCoeff(res, set, acc, res->digits, &residue, status);
5139    decFinish(res, set, &residue, status);   /* final cleanup  */
5140    } while(0);                         /* end protected  */
5141
5142  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
5143  #if DECSUBSET
5144  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
5145  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5146  #endif
5147  #if FASTMUL
5148  if (allocrhi!=NULL) free(allocrhi);   /* ..  */
5149  if (alloclhi!=NULL) free(alloclhi);   /* ..  */
5150  #endif
5151  return res;
5152  } /* decMultiplyOp  */
5153
5154/* ------------------------------------------------------------------ */
5155/* decExpOp -- effect exponentiation                                  */
5156/*                                                                    */
5157/*   This computes C = exp(A)                                         */
5158/*                                                                    */
5159/*   res is C, the result.  C may be A                                */
5160/*   rhs is A                                                         */
5161/*   set is the context; note that rounding mode has no effect        */
5162/*                                                                    */
5163/* C must have space for set->digits digits. status is updated but    */
5164/* not set.                                                           */
5165/*                                                                    */
5166/* Restrictions:                                                      */
5167/*                                                                    */
5168/*   digits, emax, and -emin in the context must be less than         */
5169/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5170/*   bounds or a zero.  This is an internal routine, so these         */
5171/*   restrictions are contractual and not enforced.                   */
5172/*                                                                    */
5173/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5174/* almost always be correctly rounded, but may be up to 1 ulp in      */
5175/* error in rare cases.                                               */
5176/*                                                                    */
5177/* Finite results will always be full precision and Inexact, except   */
5178/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5179/* ------------------------------------------------------------------ */
5180/* This approach used here is similar to the algorithm described in   */
5181/*                                                                    */
5182/*   Variable Precision Exponential Function, T. E. Hull and          */
5183/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5184/*   pp79-91, ACM, June 1986.                                         */
5185/*                                                                    */
5186/* with the main difference being that the iterations in the series   */
5187/* evaluation are terminated dynamically (which does not require the  */
5188/* extra variable-precision variables which are expensive in this     */
5189/* context).                                                          */
5190/*                                                                    */
5191/* The error analysis in Hull & Abrham's paper applies except for the */
5192/* round-off error accumulation during the series evaluation.  This   */
5193/* code does not precalculate the number of iterations and so cannot  */
5194/* use Horner's scheme.  Instead, the accumulation is done at double- */
5195/* precision, which ensures that the additions of the terms are exact */
5196/* and do not accumulate round-off (and any round-off errors in the   */
5197/* terms themselves move 'to the right' faster than they can          */
5198/* accumulate).  This code also extends the calculation by allowing,  */
5199/* in the spirit of other decNumber operators, the input to be more   */
5200/* precise than the result (the precision used is based on the more   */
5201/* precise of the input or requested result).                         */
5202/*                                                                    */
5203/* Implementation notes:                                              */
5204/*                                                                    */
5205/* 1. This is separated out as decExpOp so it can be called from      */
5206/*    other Mathematical functions (notably Ln) with a wider range    */
5207/*    than normal.  In particular, it can handle the slightly wider   */
5208/*    (double) range needed by Ln (which has to be able to calculate  */
5209/*    exp(-x) where x can be the tiniest number (Ntiny).              */
5210/*                                                                    */
5211/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5212/*    iterations by appoximately a third with additional (although    */
5213/*    diminishing) returns as the range is reduced to even smaller    */
5214/*    fractions.  However, h (the power of 10 used to correct the     */
5215/*    result at the end, see below) must be kept <=8 as otherwise     */
5216/*    the final result cannot be computed.  Hence the leverage is a   */
5217/*    sliding value (8-h), where potentially the range is reduced     */
5218/*    more for smaller values.                                        */
5219/*                                                                    */
5220/*    The leverage that can be applied in this way is severely        */
5221/*    limited by the cost of the raise-to-the power at the end,       */
5222/*    which dominates when the number of iterations is small (less    */
5223/*    than ten) or when rhs is short.  As an example, the adjustment  */
5224/*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5225/*                                                                    */
5226/* 3. The restrictions (especially precision) could be raised with    */
5227/*    care, but the full decNumber range seems very hard within the   */
5228/*    32-bit limits.                                                  */
5229/*                                                                    */
5230/* 4. The working precisions for the static buffers are twice the     */
5231/*    obvious size to allow for calls from decNumberPower.            */
5232/* ------------------------------------------------------------------ */
5233decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5234                         decContext *set, uInt *status) {
5235  uInt ignore=0;                   /* working status  */
5236  Int h;                           /* adjusted exponent for 0.xxxx  */
5237  Int p;                           /* working precision  */
5238  Int residue;                     /* rounding residue  */
5239  uInt needbytes;                  /* for space calculations  */
5240  const decNumber *x=rhs;          /* (may point to safe copy later)  */
5241  decContext aset, tset, dset;     /* working contexts  */
5242  Int comp;                        /* work  */
5243
5244  /* the argument is often copied to normalize it, so (unusually) it  */
5245  /* is treated like other buffers, using DECBUFFER, +1 in case  */
5246  /* DECBUFFER is 0  */
5247  decNumber bufr[D2N(DECBUFFER*2+1)];
5248  decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated  */
5249
5250  /* the working precision will be no more than set->digits+8+1  */
5251  /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER  */
5252  /* is 0 (and twice that for the accumulator)  */
5253
5254  /* buffer for t, term (working precision plus)  */
5255  decNumber buft[D2N(DECBUFFER*2+9+1)];
5256  decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated  */
5257  decNumber *t=buft;               /* term  */
5258  /* buffer for a, accumulator (working precision * 2), at least 9  */
5259  decNumber bufa[D2N(DECBUFFER*4+18+1)];
5260  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5261  decNumber *a=bufa;               /* accumulator  */
5262  /* decNumber for the divisor term; this needs at most 9 digits  */
5263  /* and so can be fixed size [16 so can use standard context]  */
5264  decNumber bufd[D2N(16)];
5265  decNumber *d=bufd;               /* divisor  */
5266  decNumber numone;                /* constant 1  */
5267
5268  #if DECCHECK
5269  Int iterations=0;                /* for later sanity check  */
5270  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5271  #endif
5272
5273  do {                                  /* protect allocated storage  */
5274    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5275      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5276        if (decNumberIsNegative(rhs))   /* -Infinity -> +0  */
5277          uprv_decNumberZero(res);
5278         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5279        }
5280       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5281      break;}
5282
5283    if (ISZERO(rhs)) {                  /* zeros -> exact 1  */
5284      uprv_decNumberZero(res);               /* make clean 1  */
5285      *res->lsu=1;                      /* ..  */
5286      break;}                           /* [no status to set]  */
5287
5288    /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path  */
5289    /* positive and negative tiny cases which will result in inexact  */
5290    /* 1.  This also allows the later add-accumulate to always be  */
5291    /* exact (because its length will never be more than twice the  */
5292    /* working precision).  */
5293    /* The comparator (tiny) needs just one digit, so use the  */
5294    /* decNumber d for it (reused as the divisor, etc., below); its  */
5295    /* exponent is such that if x is positive it will have  */
5296    /* set->digits-1 zeros between the decimal point and the digit,  */
5297    /* which is 4, and if x is negative one more zero there as the  */
5298    /* more precise result will be of the form 0.9999999 rather than  */
5299    /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0  */
5300    /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than  */
5301    /* this then the result will be 1.000000  */
5302    uprv_decNumberZero(d);                   /* clean  */
5303    *d->lsu=4;                          /* set 4 ..  */
5304    d->exponent=-set->digits;           /* * 10**(-d)  */
5305    if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case  */
5306    comp=decCompare(d, rhs, 1);         /* signless compare  */
5307    if (comp==BADINT) {
5308      *status|=DEC_Insufficient_storage;
5309      break;}
5310    if (comp>=0) {                      /* rhs < d  */
5311      Int shift=set->digits-1;
5312      uprv_decNumberZero(res);               /* set 1  */
5313      *res->lsu=1;                      /* ..  */
5314      res->digits=decShiftToMost(res->lsu, 1, shift);
5315      res->exponent=-shift;                  /* make 1.0000...  */
5316      *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly  */
5317      break;} /* tiny  */
5318
5319    /* set up the context to be used for calculating a, as this is  */
5320    /* used on both paths below  */
5321    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5322    /* accumulator bounds are as requested (could underflow)  */
5323    aset.emax=set->emax;                /* usual bounds  */
5324    aset.emin=set->emin;                /* ..  */
5325    aset.clamp=0;                       /* and no concrete format  */
5326
5327    /* calculate the adjusted (Hull & Abrham) exponent (where the  */
5328    /* decimal point is just to the left of the coefficient msd)  */
5329    h=rhs->exponent+rhs->digits;
5330    /* if h>8 then 10**h cannot be calculated safely; however, when  */
5331    /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at  */
5332    /* least 6.59E+4342944, so (due to the restriction on Emax/Emin)  */
5333    /* overflow (or underflow to 0) is guaranteed -- so this case can  */
5334    /* be handled by simply forcing the appropriate excess  */
5335    if (h>8) {                          /* overflow/underflow  */
5336      /* set up here so Power call below will over or underflow to  */
5337      /* zero; set accumulator to either 2 or 0.02  */
5338      /* [stack buffer for a is always big enough for this]  */
5339      uprv_decNumberZero(a);
5340      *a->lsu=2;                        /* not 1 but < exp(1)  */
5341      if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02  */
5342      h=8;                              /* clamp so 10**h computable  */
5343      p=9;                              /* set a working precision  */
5344      }
5345     else {                             /* h<=8  */
5346      Int maxlever=(rhs->digits>8?1:0);
5347      /* [could/should increase this for precisions >40 or so, too]  */
5348
5349      /* if h is 8, cannot normalize to a lower upper limit because  */
5350      /* the final result will not be computable (see notes above),  */
5351      /* but leverage can be applied whenever h is less than 8.  */
5352      /* Apply as much as possible, up to a MAXLEVER digits, which  */
5353      /* sets the tradeoff against the cost of the later a**(10**h).  */
5354      /* As h is increased, the working precision below also  */
5355      /* increases to compensate for the "constant digits at the  */
5356      /* front" effect.  */
5357      Int lever=MINI(8-h, maxlever);    /* leverage attainable  */
5358      Int use=-rhs->digits-lever;       /* exponent to use for RHS  */
5359      h+=lever;                         /* apply leverage selected  */
5360      if (h<0) {                        /* clamp  */
5361        use+=h;                         /* [may end up subnormal]  */
5362        h=0;
5363        }
5364      /* Take a copy of RHS if it needs normalization (true whenever x>=1)  */
5365      if (rhs->exponent!=use) {
5366        decNumber *newrhs=bufr;         /* assume will fit on stack  */
5367        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5368        if (needbytes>sizeof(bufr)) {   /* need malloc space  */
5369          allocrhs=(decNumber *)malloc(needbytes);
5370          if (allocrhs==NULL) {         /* hopeless -- abandon  */
5371            *status|=DEC_Insufficient_storage;
5372            break;}
5373          newrhs=allocrhs;              /* use the allocated space  */
5374          }
5375        uprv_decNumberCopy(newrhs, rhs);     /* copy to safe space  */
5376        newrhs->exponent=use;           /* normalize; now <1  */
5377        x=newrhs;                       /* ready for use  */
5378        /* decNumberShow(x);  */
5379        }
5380
5381      /* Now use the usual power series to evaluate exp(x).  The  */
5382      /* series starts as 1 + x + x^2/2 ... so prime ready for the  */
5383      /* third term by setting the term variable t=x, the accumulator  */
5384      /* a=1, and the divisor d=2.  */
5385
5386      /* First determine the working precision.  From Hull & Abrham  */
5387      /* this is set->digits+h+2.  However, if x is 'over-precise' we  */
5388      /* need to allow for all its digits to potentially participate  */
5389      /* (consider an x where all the excess digits are 9s) so in  */
5390      /* this case use x->digits+h+2  */
5391      p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8]  */
5392
5393      /* a and t are variable precision, and depend on p, so space  */
5394      /* must be allocated for them if necessary  */
5395
5396      /* the accumulator needs to be able to hold 2p digits so that  */
5397      /* the additions on the second and subsequent iterations are  */
5398      /* sufficiently exact.  */
5399      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5400      if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5401        allocbufa=(decNumber *)malloc(needbytes);
5402        if (allocbufa==NULL) {          /* hopeless -- abandon  */
5403          *status|=DEC_Insufficient_storage;
5404          break;}
5405        a=allocbufa;                    /* use the allocated space  */
5406        }
5407      /* the term needs to be able to hold p digits (which is  */
5408      /* guaranteed to be larger than x->digits, so the initial copy  */
5409      /* is safe); it may also be used for the raise-to-power  */
5410      /* calculation below, which needs an extra two digits  */
5411      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5412      if (needbytes>sizeof(buft)) {     /* need malloc space  */
5413        allocbuft=(decNumber *)malloc(needbytes);
5414        if (allocbuft==NULL) {          /* hopeless -- abandon  */
5415          *status|=DEC_Insufficient_storage;
5416          break;}
5417        t=allocbuft;                    /* use the allocated space  */
5418        }
5419
5420      uprv_decNumberCopy(t, x);              /* term=x  */
5421      uprv_decNumberZero(a); *a->lsu=1;      /* accumulator=1  */
5422      uprv_decNumberZero(d); *d->lsu=2;      /* divisor=2  */
5423      uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment  */
5424
5425      /* set up the contexts for calculating a, t, and d  */
5426      uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5427      dset=tset;
5428      /* accumulator bounds are set above, set precision now  */
5429      aset.digits=p*2;                  /* double  */
5430      /* term bounds avoid any underflow or overflow  */
5431      tset.digits=p;
5432      tset.emin=DEC_MIN_EMIN;           /* [emax is plenty]  */
5433      /* [dset.digits=16, etc., are sufficient]  */
5434
5435      /* finally ready to roll  */
5436      for (;;) {
5437        #if DECCHECK
5438        iterations++;
5439        #endif
5440        /* only the status from the accumulation is interesting  */
5441        /* [but it should remain unchanged after first add]  */
5442        decAddOp(a, a, t, &aset, 0, status);           /* a=a+t  */
5443        decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x  */
5444        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d  */
5445        /* the iteration ends when the term cannot affect the result,  */
5446        /* if rounded to p digits, which is when its value is smaller  */
5447        /* than the accumulator by p+1 digits.  There must also be  */
5448        /* full precision in a.  */
5449        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5450            && (a->digits>=p)) break;
5451        decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1  */
5452        } /* iterate  */
5453
5454      #if DECCHECK
5455      /* just a sanity check; comment out test to show always  */
5456      if (iterations>p+3)
5457        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5458               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5459      #endif
5460      } /* h<=8  */
5461
5462    /* apply postconditioning: a=a**(10**h) -- this is calculated  */
5463    /* at a slightly higher precision than Hull & Abrham suggest  */
5464    if (h>0) {
5465      Int seenbit=0;               /* set once a 1-bit is seen  */
5466      Int i;                       /* counter  */
5467      Int n=powers[h];             /* always positive  */
5468      aset.digits=p+2;             /* sufficient precision  */
5469      /* avoid the overhead and many extra digits of decNumberPower  */
5470      /* as all that is needed is the short 'multipliers' loop; here  */
5471      /* accumulate the answer into t  */
5472      uprv_decNumberZero(t); *t->lsu=1; /* acc=1  */
5473      for (i=1;;i++){              /* for each bit [top bit ignored]  */
5474        /* abandon if have had overflow or terminal underflow  */
5475        if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
5476          if (*status&DEC_Overflow || ISZERO(t)) break;}
5477        n=n<<1;                    /* move next bit to testable position  */
5478        if (n<0) {                 /* top bit is set  */
5479          seenbit=1;               /* OK, have a significant bit  */
5480          decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x  */
5481          }
5482        if (i==31) break;          /* that was the last bit  */
5483        if (!seenbit) continue;    /* no need to square 1  */
5484        decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square]  */
5485        } /*i*/ /* 32 bits  */
5486      /* decNumberShow(t);  */
5487      a=t;                         /* and carry on using t instead of a  */
5488      }
5489
5490    /* Copy and round the result to res  */
5491    residue=1;                          /* indicate dirt to right ..  */
5492    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5493    aset.digits=set->digits;            /* [use default rounding]  */
5494    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5495    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5496    } while(0);                         /* end protected  */
5497
5498  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
5499  if (allocbufa!=NULL) free(allocbufa); /* ..  */
5500  if (allocbuft!=NULL) free(allocbuft); /* ..  */
5501  /* [status is handled by caller]  */
5502  return res;
5503  } /* decExpOp  */
5504
5505/* ------------------------------------------------------------------ */
5506/* Initial-estimate natural logarithm table                           */
5507/*                                                                    */
5508/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5509/*           The result is a 4-digit encode of the coefficient (c=the */
5510/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5511/*           exponent (e=the bottom 2 bits encoding 0-3)              */
5512/*                                                                    */
5513/*           The resulting value is given by:                         */
5514/*                                                                    */
5515/*             v = -c * 10**(-e-3)                                    */
5516/*                                                                    */
5517/*           where e and c are extracted from entry k = LNnn[x-10]    */
5518/*           where x is truncated (NB) into the range 10 through 99,  */
5519/*           and then c = k>>2 and e = k&3.                           */
5520/* ------------------------------------------------------------------ */
5521const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5522  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5523  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5524 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5525 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5526 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5527 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5528 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5529  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5530 10130,  6046, 20055};
5531
5532/* ------------------------------------------------------------------ */
5533/* decLnOp -- effect natural logarithm                                */
5534/*                                                                    */
5535/*   This computes C = ln(A)                                          */
5536/*                                                                    */
5537/*   res is C, the result.  C may be A                                */
5538/*   rhs is A                                                         */
5539/*   set is the context; note that rounding mode has no effect        */
5540/*                                                                    */
5541/* C must have space for set->digits digits.                          */
5542/*                                                                    */
5543/* Notable cases:                                                     */
5544/*   A<0 -> Invalid                                                   */
5545/*   A=0 -> -Infinity (Exact)                                         */
5546/*   A=+Infinity -> +Infinity (Exact)                                 */
5547/*   A=1 exactly -> 0 (Exact)                                         */
5548/*                                                                    */
5549/* Restrictions (as for Exp):                                         */
5550/*                                                                    */
5551/*   digits, emax, and -emin in the context must be less than         */
5552/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5553/*   bounds or a zero.  This is an internal routine, so these         */
5554/*   restrictions are contractual and not enforced.                   */
5555/*                                                                    */
5556/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5557/* almost always be correctly rounded, but may be up to 1 ulp in      */
5558/* error in rare cases.                                               */
5559/* ------------------------------------------------------------------ */
5560/* The result is calculated using Newton's method, with each          */
5561/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5562/* Epperson 1989.                                                     */
5563/*                                                                    */
5564/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5565/* This has to be calculated at the sum of the precision of x and the */
5566/* working precision.                                                 */
5567/*                                                                    */
5568/* Implementation notes:                                              */
5569/*                                                                    */
5570/* 1. This is separated out as decLnOp so it can be called from       */
5571/*    other Mathematical functions (e.g., Log 10) with a wider range  */
5572/*    than normal.  In particular, it can handle the slightly wider   */
5573/*    (+9+2) range needed by a power function.                        */
5574/*                                                                    */
5575/* 2. The speed of this function is about 10x slower than exp, as     */
5576/*    it typically needs 4-6 iterations for short numbers, and the    */
5577/*    extra precision needed adds a squaring effect, twice.           */
5578/*                                                                    */
5579/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5580/*    as these are common requests.  ln(10) is used by log10(x).      */
5581/*                                                                    */
5582/* 4. An iteration might be saved by widening the LNnn table, and     */
5583/*    would certainly save at least one if it were made ten times     */
5584/*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5585/*    However, for most practical evaluations, at least four or five  */
5586/*    iterations will be neede -- so this would only speed up by      */
5587/*    20-25% and that probably does not justify increasing the table  */
5588/*    size.                                                           */
5589/*                                                                    */
5590/* 5. The static buffers are larger than might be expected to allow   */
5591/*    for calls from decNumberPower.                                  */
5592/* ------------------------------------------------------------------ */
5593#pragma clang diagnostic push
5594#pragma clang diagnostic ignored "-Warray-bounds"
5595decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5596                    decContext *set, uInt *status) {
5597  uInt ignore=0;                   /* working status accumulator  */
5598  uInt needbytes;                  /* for space calculations  */
5599  Int residue;                     /* rounding residue  */
5600  Int r;                           /* rhs=f*10**r [see below]  */
5601  Int p;                           /* working precision  */
5602  Int pp;                          /* precision for iteration  */
5603  Int t;                           /* work  */
5604
5605  /* buffers for a (accumulator, typically precision+2) and b  */
5606  /* (adjustment calculator, same size)  */
5607  decNumber bufa[D2N(DECBUFFER+12)];
5608  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5609  decNumber *a=bufa;               /* accumulator/work  */
5610  decNumber bufb[D2N(DECBUFFER*2+2)];
5611  decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated  */
5612  decNumber *b=bufb;               /* adjustment/work  */
5613
5614  decNumber  numone;               /* constant 1  */
5615  decNumber  cmp;                  /* work  */
5616  decContext aset, bset;           /* working contexts  */
5617
5618  #if DECCHECK
5619  Int iterations=0;                /* for later sanity check  */
5620  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5621  #endif
5622
5623  do {                                  /* protect allocated storage  */
5624    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5625      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5626        if (decNumberIsNegative(rhs))   /* -Infinity -> error  */
5627          *status|=DEC_Invalid_operation;
5628         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5629        }
5630       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5631      break;}
5632
5633    if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity  */
5634      uprv_decNumberZero(res);               /* make clean  */
5635      res->bits=DECINF|DECNEG;          /* set - infinity  */
5636      break;}                           /* [no status to set]  */
5637
5638    /* Non-zero negatives are bad...  */
5639    if (decNumberIsNegative(rhs)) {     /* -x -> error  */
5640      *status|=DEC_Invalid_operation;
5641      break;}
5642
5643    /* Here, rhs is positive, finite, and in range  */
5644
5645    /* lookaside fastpath code for ln(2) and ln(10) at common lengths  */
5646    if (rhs->exponent==0 && set->digits<=40) {
5647      #if DECDPUN==1
5648      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10)  */
5649      #else
5650      if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10)  */
5651      #endif
5652        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5653        #define LN10 "2.302585092994045684017991454684364207601"
5654        uprv_decNumberFromString(res, LN10, &aset);
5655        *status|=(DEC_Inexact | DEC_Rounded); /* is inexact  */
5656        break;}
5657      if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2)  */
5658        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5659        #define LN2 "0.6931471805599453094172321214581765680755"
5660        uprv_decNumberFromString(res, LN2, &aset);
5661        *status|=(DEC_Inexact | DEC_Rounded);
5662        break;}
5663      } /* integer and short  */
5664
5665    /* Determine the working precision.  This is normally the  */
5666    /* requested precision + 2, with a minimum of 9.  However, if  */
5667    /* the rhs is 'over-precise' then allow for all its digits to  */
5668    /* potentially participate (consider an rhs where all the excess  */
5669    /* digits are 9s) so in this case use rhs->digits+2.  */
5670    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5671
5672    /* Allocate space for the accumulator and the high-precision  */
5673    /* adjustment calculator, if necessary.  The accumulator must  */
5674    /* be able to hold p digits, and the adjustment up to  */
5675    /* rhs->digits+p digits.  They are also made big enough for 16  */
5676    /* digits so that they can be used for calculating the initial  */
5677    /* estimate.  */
5678    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5679    if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5680      allocbufa=(decNumber *)malloc(needbytes);
5681      if (allocbufa==NULL) {          /* hopeless -- abandon  */
5682        *status|=DEC_Insufficient_storage;
5683        break;}
5684      a=allocbufa;                    /* use the allocated space  */
5685      }
5686    pp=p+rhs->digits;
5687    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5688    if (needbytes>sizeof(bufb)) {     /* need malloc space  */
5689      allocbufb=(decNumber *)malloc(needbytes);
5690      if (allocbufb==NULL) {          /* hopeless -- abandon  */
5691        *status|=DEC_Insufficient_storage;
5692        break;}
5693      b=allocbufb;                    /* use the allocated space  */
5694      }
5695
5696    /* Prepare an initial estimate in acc. Calculate this by  */
5697    /* considering the coefficient of x to be a normalized fraction,  */
5698    /* f, with the decimal point at far left and multiplied by  */
5699    /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and  */
5700    /*   ln(x) = ln(f) + ln(10)*r  */
5701    /* Get the initial estimate for ln(f) from a small lookup  */
5702    /* table (see above) indexed by the first two digits of f,  */
5703    /* truncated.  */
5704
5705    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended  */
5706    r=rhs->exponent+rhs->digits;        /* 'normalised' exponent  */
5707    uprv_decNumberFromInt32(a, r);           /* a=r  */
5708    uprv_decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585)  */
5709    b->exponent=-6;                     /*  ..  */
5710    decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b  */
5711    /* now get top two digits of rhs into b by simple truncate and  */
5712    /* force to integer  */
5713    residue=0;                          /* (no residue)  */
5714    aset.digits=2; aset.round=DEC_ROUND_DOWN;
5715    decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten  */
5716    b->exponent=0;                      /* make integer  */
5717    t=decGetInt(b);                     /* [cannot fail]  */
5718    if (t<10) t=X10(t);                 /* adjust single-digit b  */
5719    t=LNnn[t-10];                       /* look up ln(b)  */
5720    uprv_decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient  */
5721    b->exponent=-(t&3)-3;               /* set exponent  */
5722    b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve  */
5723    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore  */
5724    decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b  */
5725    /* the initial estimate is now in a, with up to 4 digits correct.  */
5726    /* When rhs is at or near Nmax the estimate will be low, so we  */
5727    /* will approach it from below, avoiding overflow when calling exp.  */
5728
5729    uprv_decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment  */
5730
5731    /* accumulator bounds are as requested (could underflow, but  */
5732    /* cannot overflow)  */
5733    aset.emax=set->emax;
5734    aset.emin=set->emin;
5735    aset.clamp=0;                       /* no concrete format  */
5736    /* set up a context to be used for the multiply and subtract  */
5737    bset=aset;
5738    bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the  */
5739    bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation  */
5740                                        /* [see decExpOp call below]  */
5741    /* for each iteration double the number of digits to calculate,  */
5742    /* up to a maximum of p  */
5743    pp=9;                               /* initial precision  */
5744    /* [initially 9 as then the sequence starts 7+2, 16+2, and  */
5745    /* 34+2, which is ideal for standard-sized numbers]  */
5746    aset.digits=pp;                     /* working context  */
5747    bset.digits=pp+rhs->digits;         /* wider context  */
5748    for (;;) {                          /* iterate  */
5749      #if DECCHECK
5750      iterations++;
5751      if (iterations>24) break;         /* consider 9 * 2**24  */
5752      #endif
5753      /* calculate the adjustment (exp(-a)*x-1) into b.  This is a  */
5754      /* catastrophic subtraction but it really is the difference  */
5755      /* from 1 that is of interest.  */
5756      /* Use the internal entry point to Exp as it allows the double  */
5757      /* range for calculating exp(-a) when a is the tiniest subnormal.  */
5758      a->bits^=DECNEG;                  /* make -a  */
5759      decExpOp(b, a, &bset, &ignore);   /* b=exp(-a)  */
5760      a->bits^=DECNEG;                  /* restore sign of a  */
5761      /* now multiply by rhs and subtract 1, at the wider precision  */
5762      decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs  */
5763      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1  */
5764
5765      /* the iteration ends when the adjustment cannot affect the  */
5766      /* result by >=0.5 ulp (at the requested digits), which  */
5767      /* is when its value is smaller than the accumulator by  */
5768      /* set->digits+1 digits (or it is zero) -- this is a looser  */
5769      /* requirement than for Exp because all that happens to the  */
5770      /* accumulator after this is the final rounding (but note that  */
5771      /* there must also be full precision in a, or a=0).  */
5772
5773      if (decNumberIsZero(b) ||
5774          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5775        if (a->digits==p) break;
5776        if (decNumberIsZero(a)) {
5777          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ?  */
5778          if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0  */
5779           else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact  */
5780          break;
5781          }
5782        /* force padding if adjustment has gone to 0 before full length  */
5783        if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5784        }
5785
5786      /* not done yet ...  */
5787      decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate  */
5788      if (pp==p) continue;                   /* precision is at maximum  */
5789      /* lengthen the next calculation  */
5790      pp=pp*2;                               /* double precision  */
5791      if (pp>p) pp=p;                        /* clamp to maximum  */
5792      aset.digits=pp;                        /* working context  */
5793      bset.digits=pp+rhs->digits;            /* wider context  */
5794      } /* Newton's iteration  */
5795
5796    #if DECCHECK
5797    /* just a sanity check; remove the test to show always  */
5798    if (iterations>24)
5799      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5800            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5801    #endif
5802
5803    /* Copy and round the result to res  */
5804    residue=1;                          /* indicate dirt to right  */
5805    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5806    aset.digits=set->digits;            /* [use default rounding]  */
5807    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5808    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5809    } while(0);                         /* end protected  */
5810
5811  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
5812  if (allocbufb!=NULL) free(allocbufb); /* ..  */
5813  /* [status is handled by caller]  */
5814  return res;
5815  } /* decLnOp  */
5816#pragma clang diagnostic pop
5817
5818/* ------------------------------------------------------------------ */
5819/* decQuantizeOp  -- force exponent to requested value                */
5820/*                                                                    */
5821/*   This computes C = op(A, B), where op adjusts the coefficient     */
5822/*   of C (by rounding or shifting) such that the exponent (-scale)   */
5823/*   of C has the value B or matches the exponent of B.               */
5824/*   The numerical value of C will equal A, except for the effects of */
5825/*   any rounding that occurred.                                      */
5826/*                                                                    */
5827/*   res is C, the result.  C may be A or B                           */
5828/*   lhs is A, the number to adjust                                   */
5829/*   rhs is B, the requested exponent                                 */
5830/*   set is the context                                               */
5831/*   quant is 1 for quantize or 0 for rescale                         */
5832/*   status is the status accumulator (this can be called without     */
5833/*          risk of control loss)                                     */
5834/*                                                                    */
5835/* C must have space for set->digits digits.                          */
5836/*                                                                    */
5837/* Unless there is an error or the result is infinite, the exponent   */
5838/* after the operation is guaranteed to be that requested.            */
5839/* ------------------------------------------------------------------ */
5840static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5841                                 const decNumber *rhs, decContext *set,
5842                                 Flag quant, uInt *status) {
5843  #if DECSUBSET
5844  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
5845  decNumber *allocrhs=NULL;        /* .., rhs  */
5846  #endif
5847  const decNumber *inrhs=rhs;      /* save original rhs  */
5848  Int   reqdigits=set->digits;     /* requested DIGITS  */
5849  Int   reqexp;                    /* requested exponent [-scale]  */
5850  Int   residue=0;                 /* rounding residue  */
5851  Int   etiny=set->emin-(reqdigits-1);
5852
5853  #if DECCHECK
5854  if (decCheckOperands(res, lhs, rhs, set)) return res;
5855  #endif
5856
5857  do {                             /* protect allocated storage  */
5858    #if DECSUBSET
5859    if (!set->extended) {
5860      /* reduce operands and set lostDigits status, as needed  */
5861      if (lhs->digits>reqdigits) {
5862        alloclhs=decRoundOperand(lhs, set, status);
5863        if (alloclhs==NULL) break;
5864        lhs=alloclhs;
5865        }
5866      if (rhs->digits>reqdigits) { /* [this only checks lostDigits]  */
5867        allocrhs=decRoundOperand(rhs, set, status);
5868        if (allocrhs==NULL) break;
5869        rhs=allocrhs;
5870        }
5871      }
5872    #endif
5873    /* [following code does not require input rounding]  */
5874
5875    /* Handle special values  */
5876    if (SPECIALARGS) {
5877      /* NaNs get usual processing  */
5878      if (SPECIALARGS & (DECSNAN | DECNAN))
5879        decNaNs(res, lhs, rhs, set, status);
5880      /* one infinity but not both is bad  */
5881      else if ((lhs->bits ^ rhs->bits) & DECINF)
5882        *status|=DEC_Invalid_operation;
5883      /* both infinity: return lhs  */
5884      else uprv_decNumberCopy(res, lhs);          /* [nop if in place]  */
5885      break;
5886      }
5887
5888    /* set requested exponent  */
5889    if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents  */
5890     else {                             /* rescale -- use value of rhs  */
5891      /* Original rhs must be an integer that fits and is in range,  */
5892      /* which could be from -1999999997 to +999999999, thanks to  */
5893      /* subnormals  */
5894      reqexp=decGetInt(inrhs);               /* [cannot fail]  */
5895      }
5896
5897    #if DECSUBSET
5898    if (!set->extended) etiny=set->emin;     /* no subnormals  */
5899    #endif
5900
5901    if (reqexp==BADINT                       /* bad (rescale only) or ..  */
5902     || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or ..  */
5903     || (reqexp<etiny)                       /* < lowest  */
5904     || (reqexp>set->emax)) {                /* > emax  */
5905      *status|=DEC_Invalid_operation;
5906      break;}
5907
5908    /* the RHS has been processed, so it can be overwritten now if necessary  */
5909    if (ISZERO(lhs)) {                       /* zero coefficient unchanged  */
5910      uprv_decNumberCopy(res, lhs);               /* [nop if in place]  */
5911      res->exponent=reqexp;                  /* .. just set exponent  */
5912      #if DECSUBSET
5913      if (!set->extended) res->bits=0;       /* subset specification; no -0  */
5914      #endif
5915      }
5916     else {                                  /* non-zero lhs  */
5917      Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed  */
5918      /* if adjusted coefficient will definitely not fit, give up now  */
5919      if ((lhs->digits-adjust)>reqdigits) {
5920        *status|=DEC_Invalid_operation;
5921        break;
5922        }
5923
5924      if (adjust>0) {                        /* increasing exponent  */
5925        /* this will decrease the length of the coefficient by adjust  */
5926        /* digits, and must round as it does so  */
5927        decContext workset;                  /* work  */
5928        workset=*set;                        /* clone rounding, etc.  */
5929        workset.digits=lhs->digits-adjust;   /* set requested length  */
5930        /* [note that the latter can be <1, here]  */
5931        decCopyFit(res, lhs, &workset, &residue, status); /* fit to result  */
5932        decApplyRound(res, &workset, residue, status);    /* .. and round  */
5933        residue=0;                                        /* [used]  */
5934        /* If just rounded a 999s case, exponent will be off by one;  */
5935        /* adjust back (after checking space), if so.  */
5936        if (res->exponent>reqexp) {
5937          /* re-check needed, e.g., for quantize(0.9999, 0.001) under  */
5938          /* set->digits==3  */
5939          if (res->digits==reqdigits) {      /* cannot shift by 1  */
5940            *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these]  */
5941            *status|=DEC_Invalid_operation;
5942            break;
5943            }
5944          res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift  */
5945          res->exponent--;                   /* (re)adjust the exponent.  */
5946          }
5947        #if DECSUBSET
5948        if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0  */
5949        #endif
5950        } /* increase  */
5951       else /* adjust<=0 */ {                /* decreasing or = exponent  */
5952        /* this will increase the length of the coefficient by -adjust  */
5953        /* digits, by adding zero or more trailing zeros; this is  */
5954        /* already checked for fit, above  */
5955        uprv_decNumberCopy(res, lhs);             /* [it will fit]  */
5956        /* if padding needed (adjust<0), add it now...  */
5957        if (adjust<0) {
5958          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5959          res->exponent+=adjust;             /* adjust the exponent  */
5960          }
5961        } /* decrease  */
5962      } /* non-zero  */
5963
5964    /* Check for overflow [do not use Finalize in this case, as an  */
5965    /* overflow here is a "don't fit" situation]  */
5966    if (res->exponent>set->emax-res->digits+1) {  /* too big  */
5967      *status|=DEC_Invalid_operation;
5968      break;
5969      }
5970     else {
5971      decFinalize(res, set, &residue, status);    /* set subnormal flags  */
5972      *status&=~DEC_Underflow;          /* suppress Underflow [as per 754]  */
5973      }
5974    } while(0);                         /* end protected  */
5975
5976  #if DECSUBSET
5977  if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used  */
5978  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5979  #endif
5980  return res;
5981  } /* decQuantizeOp  */
5982
5983/* ------------------------------------------------------------------ */
5984/* decCompareOp -- compare, min, or max two Numbers                   */
5985/*                                                                    */
5986/*   This computes C = A ? B and carries out one of four operations:  */
5987/*     COMPARE    -- returns the signum (as a number) giving the      */
5988/*                   result of a comparison unless one or both        */
5989/*                   operands is a NaN (in which case a NaN results)  */
5990/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
5991/*                   Invalid operation.                               */
5992/*     COMPMAX    -- returns the larger of the operands, using the    */
5993/*                   754 maxnum operation                             */
5994/*     COMPMAXMAG -- ditto, comparing absolute values                 */
5995/*     COMPMIN    -- the 754 minnum operation                         */
5996/*     COMPMINMAG -- ditto, comparing absolute values                 */
5997/*     COMTOTAL   -- returns the signum (as a number) giving the      */
5998/*                   result of a comparison using 754 total ordering  */
5999/*                                                                    */
6000/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
6001/*   lhs is A                                                         */
6002/*   rhs is B                                                         */
6003/*   set is the context                                               */
6004/*   op  is the operation flag                                        */
6005/*   status is the usual accumulator                                  */
6006/*                                                                    */
6007/* C must have space for one digit for COMPARE or set->digits for     */
6008/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6009/* ------------------------------------------------------------------ */
6010/* The emphasis here is on speed for common cases, and avoiding       */
6011/* coefficient comparison if possible.                                */
6012/* ------------------------------------------------------------------ */
6013static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6014                         const decNumber *rhs, decContext *set,
6015                         Flag op, uInt *status) {
6016  #if DECSUBSET
6017  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
6018  decNumber *allocrhs=NULL;        /* .., rhs  */
6019  #endif
6020  Int   result=0;                  /* default result value  */
6021  uByte merged;                    /* work  */
6022
6023  #if DECCHECK
6024  if (decCheckOperands(res, lhs, rhs, set)) return res;
6025  #endif
6026
6027  do {                             /* protect allocated storage  */
6028    #if DECSUBSET
6029    if (!set->extended) {
6030      /* reduce operands and set lostDigits status, as needed  */
6031      if (lhs->digits>set->digits) {
6032        alloclhs=decRoundOperand(lhs, set, status);
6033        if (alloclhs==NULL) {result=BADINT; break;}
6034        lhs=alloclhs;
6035        }
6036      if (rhs->digits>set->digits) {
6037        allocrhs=decRoundOperand(rhs, set, status);
6038        if (allocrhs==NULL) {result=BADINT; break;}
6039        rhs=allocrhs;
6040        }
6041      }
6042    #endif
6043    /* [following code does not require input rounding]  */
6044
6045    /* If total ordering then handle differing signs 'up front'  */
6046    if (op==COMPTOTAL) {                /* total ordering  */
6047      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6048        result=-1;
6049        break;
6050        }
6051      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6052        result=+1;
6053        break;
6054        }
6055      }
6056
6057    /* handle NaNs specially; let infinities drop through  */
6058    /* This assumes sNaN (even just one) leads to NaN.  */
6059    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6060    if (merged) {                       /* a NaN bit set  */
6061      if (op==COMPARE);                 /* result will be NaN  */
6062       else if (op==COMPSIG)            /* treat qNaN as sNaN  */
6063        *status|=DEC_Invalid_operation | DEC_sNaN;
6064       else if (op==COMPTOTAL) {        /* total ordering, always finite  */
6065        /* signs are known to be the same; compute the ordering here  */
6066        /* as if the signs are both positive, then invert for negatives  */
6067        if (!decNumberIsNaN(lhs)) result=-1;
6068         else if (!decNumberIsNaN(rhs)) result=+1;
6069         /* here if both NaNs  */
6070         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6071         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6072         else { /* both NaN or both sNaN  */
6073          /* now it just depends on the payload  */
6074          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6075                                rhs->lsu, D2U(rhs->digits), 0);
6076          /* [Error not possible, as these are 'aligned']  */
6077          } /* both same NaNs  */
6078        if (decNumberIsNegative(lhs)) result=-result;
6079        break;
6080        } /* total order  */
6081
6082       else if (merged & DECSNAN);           /* sNaN -> qNaN  */
6083       else { /* here if MIN or MAX and one or two quiet NaNs  */
6084        /* min or max -- 754 rules ignore single NaN  */
6085        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6086          /* just one NaN; force choice to be the non-NaN operand  */
6087          op=COMPMAX;
6088          if (lhs->bits & DECNAN) result=-1; /* pick rhs  */
6089                             else result=+1; /* pick lhs  */
6090          break;
6091          }
6092        } /* max or min  */
6093      op=COMPNAN;                            /* use special path  */
6094      decNaNs(res, lhs, rhs, set, status);   /* propagate NaN  */
6095      break;
6096      }
6097    /* have numbers  */
6098    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6099     else result=decCompare(lhs, rhs, 0);    /* sign matters  */
6100    } while(0);                              /* end protected  */
6101
6102  if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare  */
6103   else {
6104    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum  */
6105      if (op==COMPTOTAL && result==0) {
6106        /* operands are numerically equal or same NaN (and same sign,  */
6107        /* tested first); if identical, leave result 0  */
6108        if (lhs->exponent!=rhs->exponent) {
6109          if (lhs->exponent<rhs->exponent) result=-1;
6110           else result=+1;
6111          if (decNumberIsNegative(lhs)) result=-result;
6112          } /* lexp!=rexp  */
6113        } /* total-order by exponent  */
6114      uprv_decNumberZero(res);               /* [always a valid result]  */
6115      if (result!=0) {                  /* must be -1 or +1  */
6116        *res->lsu=1;
6117        if (result<0) res->bits=DECNEG;
6118        }
6119      }
6120     else if (op==COMPNAN);             /* special, drop through  */
6121     else {                             /* MAX or MIN, non-NaN result  */
6122      Int residue=0;                    /* rounding accumulator  */
6123      /* choose the operand for the result  */
6124      const decNumber *choice;
6125      if (result==0) { /* operands are numerically equal  */
6126        /* choose according to sign then exponent (see 754)  */
6127        uByte slhs=(lhs->bits & DECNEG);
6128        uByte srhs=(rhs->bits & DECNEG);
6129        #if DECSUBSET
6130        if (!set->extended) {           /* subset: force left-hand  */
6131          op=COMPMAX;
6132          result=+1;
6133          }
6134        else
6135        #endif
6136        if (slhs!=srhs) {          /* signs differ  */
6137          if (slhs) result=-1;     /* rhs is max  */
6138               else result=+1;     /* lhs is max  */
6139          }
6140         else if (slhs && srhs) {  /* both negative  */
6141          if (lhs->exponent<rhs->exponent) result=+1;
6142                                      else result=-1;
6143          /* [if equal, use lhs, technically identical]  */
6144          }
6145         else {                    /* both positive  */
6146          if (lhs->exponent>rhs->exponent) result=+1;
6147                                      else result=-1;
6148          /* [ditto]  */
6149          }
6150        } /* numerically equal  */
6151      /* here result will be non-0; reverse if looking for MIN  */
6152      if (op==COMPMIN || op==COMPMINMAG) result=-result;
6153      choice=(result>0 ? lhs : rhs);    /* choose  */
6154      /* copy chosen to result, rounding if need be  */
6155      decCopyFit(res, choice, set, &residue, status);
6156      decFinish(res, set, &residue, status);
6157      }
6158    }
6159  #if DECSUBSET
6160  if (allocrhs!=NULL) free(allocrhs);   /* free any storage used  */
6161  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
6162  #endif
6163  return res;
6164  } /* decCompareOp  */
6165
6166/* ------------------------------------------------------------------ */
6167/* decCompare -- compare two decNumbers by numerical value            */
6168/*                                                                    */
6169/*  This routine compares A ? B without altering them.                */
6170/*                                                                    */
6171/*  Arg1 is A, a decNumber which is not a NaN                         */
6172/*  Arg2 is B, a decNumber which is not a NaN                         */
6173/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6174/*                                                                    */
6175/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6176/*  (the only possible failure is an allocation error)                */
6177/* ------------------------------------------------------------------ */
6178static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6179                      Flag abs_c) {
6180  Int   result;                    /* result value  */
6181  Int   sigr;                      /* rhs signum  */
6182  Int   compare;                   /* work  */
6183
6184  result=1;                                  /* assume signum(lhs)  */
6185  if (ISZERO(lhs)) result=0;
6186  if (abs_c) {
6187    if (ISZERO(rhs)) return result;          /* LHS wins or both 0  */
6188    /* RHS is non-zero  */
6189    if (result==0) return -1;                /* LHS is 0; RHS wins  */
6190    /* [here, both non-zero, result=1]  */
6191    }
6192   else {                                    /* signs matter  */
6193    if (result && decNumberIsNegative(lhs)) result=-1;
6194    sigr=1;                                  /* compute signum(rhs)  */
6195    if (ISZERO(rhs)) sigr=0;
6196     else if (decNumberIsNegative(rhs)) sigr=-1;
6197    if (result > sigr) return +1;            /* L > R, return 1  */
6198    if (result < sigr) return -1;            /* L < R, return -1  */
6199    if (result==0) return 0;                   /* both 0  */
6200    }
6201
6202  /* signums are the same; both are non-zero  */
6203  if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities  */
6204    if (decNumberIsInfinite(rhs)) {
6205      if (decNumberIsInfinite(lhs)) result=0;/* both infinite  */
6206       else result=-result;                  /* only rhs infinite  */
6207      }
6208    return result;
6209    }
6210  /* must compare the coefficients, allowing for exponents  */
6211  if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger  */
6212    /* swap sides, and sign  */
6213    const decNumber *temp=lhs;
6214    lhs=rhs;
6215    rhs=temp;
6216    result=-result;
6217    }
6218  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6219                         rhs->lsu, D2U(rhs->digits),
6220                         rhs->exponent-lhs->exponent);
6221  if (compare!=BADINT) compare*=result;      /* comparison succeeded  */
6222  return compare;
6223  } /* decCompare  */
6224
6225/* ------------------------------------------------------------------ */
6226/* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6227/*                                                                    */
6228/*  This routine compares A ? B*10**E where A and B are unit arrays   */
6229/*  A is a plain integer                                              */
6230/*  B has an exponent of E (which must be non-negative)               */
6231/*                                                                    */
6232/*  Arg1 is A first Unit (lsu)                                        */
6233/*  Arg2 is A length in Units                                         */
6234/*  Arg3 is B first Unit (lsu)                                        */
6235/*  Arg4 is B length in Units                                         */
6236/*  Arg5 is E (0 if the units are aligned)                            */
6237/*                                                                    */
6238/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6239/*  (the only possible failure is an allocation error, which can      */
6240/*  only occur if E!=0)                                               */
6241/* ------------------------------------------------------------------ */
6242static Int decUnitCompare(const Unit *a, Int alength,
6243                          const Unit *b, Int blength, Int exp) {
6244  Unit  *acc;                      /* accumulator for result  */
6245  Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer  */
6246  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
6247  Int   accunits, need;            /* units in use or needed for acc  */
6248  const Unit *l, *r, *u;           /* work  */
6249  Int   expunits, exprem, result;  /* ..  */
6250
6251  if (exp==0) {                    /* aligned; fastpath  */
6252    if (alength>blength) return 1;
6253    if (alength<blength) return -1;
6254    /* same number of units in both -- need unit-by-unit compare  */
6255    l=a+alength-1;
6256    r=b+alength-1;
6257    for (;l>=a; l--, r--) {
6258      if (*l>*r) return 1;
6259      if (*l<*r) return -1;
6260      }
6261    return 0;                      /* all units match  */
6262    } /* aligned  */
6263
6264  /* Unaligned.  If one is >1 unit longer than the other, padded  */
6265  /* approximately, then can return easily  */
6266  if (alength>blength+(Int)D2U(exp)) return 1;
6267  if (alength+1<blength+(Int)D2U(exp)) return -1;
6268
6269  /* Need to do a real subtract.  For this, a result buffer is needed  */
6270  /* even though only the sign is of interest.  Its length needs  */
6271  /* to be the larger of alength and padded blength, +2  */
6272  need=blength+D2U(exp);                /* maximum real length of B  */
6273  if (need<alength) need=alength;
6274  need+=2;
6275  acc=accbuff;                          /* assume use local buffer  */
6276  if (need*sizeof(Unit)>sizeof(accbuff)) {
6277    allocacc=(Unit *)malloc(need*sizeof(Unit));
6278    if (allocacc==NULL) return BADINT;  /* hopeless -- abandon  */
6279    acc=allocacc;
6280    }
6281  /* Calculate units and remainder from exponent.  */
6282  expunits=exp/DECDPUN;
6283  exprem=exp%DECDPUN;
6284  /* subtract [A+B*(-m)]  */
6285  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6286                         -(Int)powers[exprem]);
6287  /* [UnitAddSub result may have leading zeros, even on zero]  */
6288  if (accunits<0) result=-1;            /* negative result  */
6289   else {                               /* non-negative result  */
6290    /* check units of the result before freeing any storage  */
6291    for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6292    result=(*u==0 ? 0 : +1);
6293    }
6294  /* clean up and return the result  */
6295  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
6296  return result;
6297  } /* decUnitCompare  */
6298
6299/* ------------------------------------------------------------------ */
6300/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6301/*                                                                    */
6302/*  This routine performs the calculation:                            */
6303/*                                                                    */
6304/*  C=A+(B*M)                                                         */
6305/*                                                                    */
6306/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6307/*                                                                    */
6308/*  A may be shorter or longer than B.                                */
6309/*                                                                    */
6310/*  Leading zeros are not removed after a calculation.  The result is */
6311/*  either the same length as the longer of A and B (adding any       */
6312/*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6313/*                                                                    */
6314/*  A and B content are not altered unless C is also A or B.          */
6315/*  C may be the same array as A or B, but only if no zero padding is */
6316/*  requested (that is, C may be B only if bshift==0).                */
6317/*  C is filled from the lsu; only those units necessary to complete  */
6318/*  the calculation are referenced.                                   */
6319/*                                                                    */
6320/*  Arg1 is A first Unit (lsu)                                        */
6321/*  Arg2 is A length in Units                                         */
6322/*  Arg3 is B first Unit (lsu)                                        */
6323/*  Arg4 is B length in Units                                         */
6324/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6325/*  Arg6 is C first Unit (lsu)                                        */
6326/*  Arg7 is M, the multiplier                                         */
6327/*                                                                    */
6328/*  returns the count of Units written to C, which will be non-zero   */
6329/*  and negated if the result is negative.  That is, the sign of the  */
6330/*  returned Int is the sign of the result (positive for zero) and    */
6331/*  the absolute value of the Int is the count of Units.              */
6332/*                                                                    */
6333/*  It is the caller's responsibility to make sure that C size is     */
6334/*  safe, allowing space if necessary for a one-Unit carry.           */
6335/*                                                                    */
6336/*  This routine is severely performance-critical; *any* change here  */
6337/*  must be measured (timed) to assure no performance degradation.    */
6338/*  In particular, trickery here tends to be counter-productive, as   */
6339/*  increased complexity of code hurts register optimizations on      */
6340/*  register-poor architectures.  Avoiding divisions is nearly        */
6341/*  always a Good Idea, however.                                      */
6342/*                                                                    */
6343/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6344/* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6345/* ------------------------------------------------------------------ */
6346static Int decUnitAddSub(const Unit *a, Int alength,
6347                         const Unit *b, Int blength, Int bshift,
6348                         Unit *c, Int m) {
6349  const Unit *alsu=a;              /* A lsu [need to remember it]  */
6350  Unit *clsu=c;                    /* C ditto  */
6351  Unit *minC;                      /* low water mark for C  */
6352  Unit *maxC;                      /* high water mark for C  */
6353  eInt carry=0;                    /* carry integer (could be Long)  */
6354  Int  add;                        /* work  */
6355  #if DECDPUN<=4                   /* myriadal, millenary, etc.  */
6356  Int  est;                        /* estimated quotient  */
6357  #endif
6358
6359  #if DECTRACE
6360  if (alength<1 || blength<1)
6361    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6362  #endif
6363
6364  maxC=c+alength;                  /* A is usually the longer  */
6365  minC=c+blength;                  /* .. and B the shorter  */
6366  if (bshift!=0) {                 /* B is shifted; low As copy across  */
6367    minC+=bshift;
6368    /* if in place [common], skip copy unless there's a gap [rare]  */
6369    if (a==c && bshift<=alength) {
6370      c+=bshift;
6371      a+=bshift;
6372      }
6373     else for (; c<clsu+bshift; a++, c++) {  /* copy needed  */
6374      if (a<alsu+alength) *c=*a;
6375       else *c=0;
6376      }
6377    }
6378  if (minC>maxC) { /* swap  */
6379    Unit *hold=minC;
6380    minC=maxC;
6381    maxC=hold;
6382    }
6383
6384  /* For speed, do the addition as two loops; the first where both A  */
6385  /* and B contribute, and the second (if necessary) where only one or  */
6386  /* other of the numbers contribute.  */
6387  /* Carry handling is the same (i.e., duplicated) in each case.  */
6388  for (; c<minC; c++) {
6389    carry+=*a;
6390    a++;
6391    carry+=((eInt)*b)*m;                /* [special-casing m=1/-1  */
6392    b++;                                /* here is not a win]  */
6393    /* here carry is new Unit of digits; it could be +ve or -ve  */
6394    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6395      *c=(Unit)carry;
6396      carry=0;
6397      continue;
6398      }
6399    #if DECDPUN==4                           /* use divide-by-multiply  */
6400      if (carry>=0) {
6401        est=(((ueInt)carry>>11)*53687)>>18;
6402        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6403        carry=est;                           /* likely quotient [89%]  */
6404        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6405        carry++;
6406        *c-=DECDPUNMAX+1;
6407        continue;
6408        }
6409      /* negative case  */
6410      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6411      est=(((ueInt)carry>>11)*53687)>>18;
6412      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6413      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6414      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6415      carry++;
6416      *c-=DECDPUNMAX+1;
6417    #elif DECDPUN==3
6418      if (carry>=0) {
6419        est=(((ueInt)carry>>3)*16777)>>21;
6420        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6421        carry=est;                           /* likely quotient [99%]  */
6422        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6423        carry++;
6424        *c-=DECDPUNMAX+1;
6425        continue;
6426        }
6427      /* negative case  */
6428      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6429      est=(((ueInt)carry>>3)*16777)>>21;
6430      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6431      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6432      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6433      carry++;
6434      *c-=DECDPUNMAX+1;
6435    #elif DECDPUN<=2
6436      /* Can use QUOT10 as carry <= 4 digits  */
6437      if (carry>=0) {
6438        est=QUOT10(carry, DECDPUN);
6439        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6440        carry=est;                           /* quotient  */
6441        continue;
6442        }
6443      /* negative case  */
6444      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6445      est=QUOT10(carry, DECDPUN);
6446      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6447      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6448    #else
6449      /* remainder operator is undefined if negative, so must test  */
6450      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1  */
6451        *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions]  */
6452        carry=1;
6453        continue;
6454        }
6455      if (carry>=0) {
6456        *c=(Unit)(carry%(DECDPUNMAX+1));
6457        carry=carry/(DECDPUNMAX+1);
6458        continue;
6459        }
6460      /* negative case  */
6461      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6462      *c=(Unit)(carry%(DECDPUNMAX+1));
6463      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6464    #endif
6465    } /* c  */
6466
6467  /* now may have one or other to complete  */
6468  /* [pretest to avoid loop setup/shutdown]  */
6469  if (c<maxC) for (; c<maxC; c++) {
6470    if (a<alsu+alength) {               /* still in A  */
6471      carry+=*a;
6472      a++;
6473      }
6474     else {                             /* inside B  */
6475      carry+=((eInt)*b)*m;
6476      b++;
6477      }
6478    /* here carry is new Unit of digits; it could be +ve or -ve and  */
6479    /* magnitude up to DECDPUNMAX squared  */
6480    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6481      *c=(Unit)carry;
6482      carry=0;
6483      continue;
6484      }
6485    /* result for this unit is negative or >DECDPUNMAX  */
6486    #if DECDPUN==4                           /* use divide-by-multiply  */
6487      if (carry>=0) {
6488        est=(((ueInt)carry>>11)*53687)>>18;
6489        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6490        carry=est;                           /* likely quotient [79.7%]  */
6491        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6492        carry++;
6493        *c-=DECDPUNMAX+1;
6494        continue;
6495        }
6496      /* negative case  */
6497      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6498      est=(((ueInt)carry>>11)*53687)>>18;
6499      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6500      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6501      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6502      carry++;
6503      *c-=DECDPUNMAX+1;
6504    #elif DECDPUN==3
6505      if (carry>=0) {
6506        est=(((ueInt)carry>>3)*16777)>>21;
6507        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6508        carry=est;                           /* likely quotient [99%]  */
6509        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6510        carry++;
6511        *c-=DECDPUNMAX+1;
6512        continue;
6513        }
6514      /* negative case  */
6515      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6516      est=(((ueInt)carry>>3)*16777)>>21;
6517      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6518      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6519      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6520      carry++;
6521      *c-=DECDPUNMAX+1;
6522    #elif DECDPUN<=2
6523      if (carry>=0) {
6524        est=QUOT10(carry, DECDPUN);
6525        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6526        carry=est;                           /* quotient  */
6527        continue;
6528        }
6529      /* negative case  */
6530      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6531      est=QUOT10(carry, DECDPUN);
6532      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6533      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6534    #else
6535      if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1  */
6536        *c=(Unit)(carry-(DECDPUNMAX+1));
6537        carry=1;
6538        continue;
6539        }
6540      /* remainder operator is undefined if negative, so must test  */
6541      if (carry>=0) {
6542        *c=(Unit)(carry%(DECDPUNMAX+1));
6543        carry=carry/(DECDPUNMAX+1);
6544        continue;
6545        }
6546      /* negative case  */
6547      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6548      *c=(Unit)(carry%(DECDPUNMAX+1));
6549      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6550    #endif
6551    } /* c  */
6552
6553  /* OK, all A and B processed; might still have carry or borrow  */
6554  /* return number of Units in the result, negated if a borrow  */
6555  if (carry==0) return c-clsu;     /* no carry, so no more to do  */
6556  if (carry>0) {                   /* positive carry  */
6557    *c=(Unit)carry;                /* place as new unit  */
6558    c++;                           /* ..  */
6559    return c-clsu;
6560    }
6561  /* -ve carry: it's a borrow; complement needed  */
6562  add=1;                           /* temporary carry...  */
6563  for (c=clsu; c<maxC; c++) {
6564    add=DECDPUNMAX+add-*c;
6565    if (add<=DECDPUNMAX) {
6566      *c=(Unit)add;
6567      add=0;
6568      }
6569     else {
6570      *c=0;
6571      add=1;
6572      }
6573    }
6574  /* add an extra unit iff it would be non-zero  */
6575  #if DECTRACE
6576    printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6577  #endif
6578  if ((add-carry-1)!=0) {
6579    *c=(Unit)(add-carry-1);
6580    c++;                      /* interesting, include it  */
6581    }
6582  return clsu-c;              /* -ve result indicates borrowed  */
6583  } /* decUnitAddSub  */
6584
6585/* ------------------------------------------------------------------ */
6586/* decTrim -- trim trailing zeros or normalize                        */
6587/*                                                                    */
6588/*   dn is the number to trim or normalize                            */
6589/*   set is the context to use to check for clamp                     */
6590/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6591/*   noclamp is 1 to unconditional (unclamped) trim                   */
6592/*   dropped returns the number of discarded trailing zeros           */
6593/*   returns dn                                                       */
6594/*                                                                    */
6595/* If clamp is set in the context then the number of zeros trimmed    */
6596/* may be limited if the exponent is high.                            */
6597/* All fields are updated as required.  This is a utility operation,  */
6598/* so special values are unchanged and no error is possible.          */
6599/* ------------------------------------------------------------------ */
6600static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6601                           Flag noclamp, Int *dropped) {
6602  Int   d, exp;                    /* work  */
6603  uInt  cut;                       /* ..  */
6604  Unit  *up;                       /* -> current Unit  */
6605
6606  #if DECCHECK
6607  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6608  #endif
6609
6610  *dropped=0;                           /* assume no zeros dropped  */
6611  if ((dn->bits & DECSPECIAL)           /* fast exit if special ..  */
6612    || (*dn->lsu & 0x01)) return dn;    /* .. or odd  */
6613  if (ISZERO(dn)) {                     /* .. or 0  */
6614    dn->exponent=0;                     /* (sign is preserved)  */
6615    return dn;
6616    }
6617
6618  /* have a finite number which is even  */
6619  exp=dn->exponent;
6620  cut=1;                           /* digit (1-DECDPUN) in Unit  */
6621  up=dn->lsu;                      /* -> current Unit  */
6622  for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit]  */
6623    /* slice by powers  */
6624    #if DECDPUN<=4
6625      uInt quot=QUOT10(*up, cut);
6626      if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit  */
6627    #else
6628      if (*up%powers[cut]!=0) break;         /* found non-0 digit  */
6629    #endif
6630    /* have a trailing 0  */
6631    if (!all) {                    /* trimming  */
6632      /* [if exp>0 then all trailing 0s are significant for trim]  */
6633      if (exp<=0) {                /* if digit might be significant  */
6634        if (exp==0) break;         /* then quit  */
6635        exp++;                     /* next digit might be significant  */
6636        }
6637      }
6638    cut++;                         /* next power  */
6639    if (cut>DECDPUN) {             /* need new Unit  */
6640      up++;
6641      cut=1;
6642      }
6643    } /* d  */
6644  if (d==0) return dn;             /* none to drop  */
6645
6646  /* may need to limit drop if clamping  */
6647  if (set->clamp && !noclamp) {
6648    Int maxd=set->emax-set->digits+1-dn->exponent;
6649    if (maxd<=0) return dn;        /* nothing possible  */
6650    if (d>maxd) d=maxd;
6651    }
6652
6653  /* effect the drop  */
6654  decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6655  dn->exponent+=d;                 /* maintain numerical value  */
6656  dn->digits-=d;                   /* new length  */
6657  *dropped=d;                      /* report the count  */
6658  return dn;
6659  } /* decTrim  */
6660
6661/* ------------------------------------------------------------------ */
6662/* decReverse -- reverse a Unit array in place                        */
6663/*                                                                    */
6664/*   ulo    is the start of the array                                 */
6665/*   uhi    is the end of the array (highest Unit to include)         */
6666/*                                                                    */
6667/* The units ulo through uhi are reversed in place (if the number     */
6668/* of units is odd, the middle one is untouched).  Note that the      */
6669/* digit(s) in each unit are unaffected.                              */
6670/* ------------------------------------------------------------------ */
6671static void decReverse(Unit *ulo, Unit *uhi) {
6672  Unit temp;
6673  for (; ulo<uhi; ulo++, uhi--) {
6674    temp=*ulo;
6675    *ulo=*uhi;
6676    *uhi=temp;
6677    }
6678  return;
6679  } /* decReverse  */
6680
6681/* ------------------------------------------------------------------ */
6682/* decShiftToMost -- shift digits in array towards most significant   */
6683/*                                                                    */
6684/*   uar    is the array                                              */
6685/*   digits is the count of digits in use in the array                */
6686/*   shift  is the number of zeros to pad with (least significant);   */
6687/*     it must be zero or positive                                    */
6688/*                                                                    */
6689/*   returns the new length of the integer in the array, in digits    */
6690/*                                                                    */
6691/* No overflow is permitted (that is, the uar array must be known to  */
6692/* be large enough to hold the result, after shifting).               */
6693/* ------------------------------------------------------------------ */
6694static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6695  Unit  *target, *source, *first;  /* work  */
6696  Int   cut;                       /* odd 0's to add  */
6697  uInt  next;                      /* work  */
6698
6699  if (shift==0) return digits;     /* [fastpath] nothing to do  */
6700  if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case  */
6701    *uar=(Unit)(*uar*powers[shift]);
6702    return digits+shift;
6703    }
6704
6705  next=0;                          /* all paths  */
6706  source=uar+D2U(digits)-1;        /* where msu comes from  */
6707  target=source+D2U(shift);        /* where upper part of first cut goes  */
6708  cut=DECDPUN-MSUDIGITS(shift);    /* where to slice  */
6709  if (cut==0) {                    /* unit-boundary case  */
6710    for (; source>=uar; source--, target--) *target=*source;
6711    }
6712   else {
6713    first=uar+D2U(digits+shift)-1; /* where msu of source will end up  */
6714    for (; source>=uar; source--, target--) {
6715      /* split the source Unit and accumulate remainder for next  */
6716      #if DECDPUN<=4
6717        uInt quot=QUOT10(*source, cut);
6718        uInt rem=*source-quot*powers[cut];
6719        next+=quot;
6720      #else
6721        uInt rem=*source%powers[cut];
6722        next+=*source/powers[cut];
6723      #endif
6724      if (target<=first) *target=(Unit)next;   /* write to target iff valid  */
6725      next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit  */
6726      }
6727    } /* shift-move  */
6728
6729  /* propagate any partial unit to one below and clear the rest  */
6730  for (; target>=uar; target--) {
6731    *target=(Unit)next;
6732    next=0;
6733    }
6734  return digits+shift;
6735  } /* decShiftToMost  */
6736
6737/* ------------------------------------------------------------------ */
6738/* decShiftToLeast -- shift digits in array towards least significant */
6739/*                                                                    */
6740/*   uar   is the array                                               */
6741/*   units is length of the array, in units                           */
6742/*   shift is the number of digits to remove from the lsu end; it     */
6743/*     must be zero or positive and <= than units*DECDPUN.            */
6744/*                                                                    */
6745/*   returns the new length of the integer in the array, in units     */
6746/*                                                                    */
6747/* Removed digits are discarded (lost).  Units not required to hold   */
6748/* the final result are unchanged.                                    */
6749/* ------------------------------------------------------------------ */
6750static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6751  Unit  *target, *up;              /* work  */
6752  Int   cut, count;                /* work  */
6753  Int   quot, rem;                 /* for division  */
6754
6755  if (shift==0) return units;      /* [fastpath] nothing to do  */
6756  if (shift==units*DECDPUN) {      /* [fastpath] little to do  */
6757    *uar=0;                        /* all digits cleared gives zero  */
6758    return 1;                      /* leaves just the one  */
6759    }
6760
6761  target=uar;                      /* both paths  */
6762  cut=MSUDIGITS(shift);
6763  if (cut==DECDPUN) {              /* unit-boundary case; easy  */
6764    up=uar+D2U(shift);
6765    for (; up<uar+units; target++, up++) *target=*up;
6766    return target-uar;
6767    }
6768
6769  /* messier  */
6770  up=uar+D2U(shift-cut);           /* source; correct to whole Units  */
6771  count=units*DECDPUN-shift;       /* the maximum new length  */
6772  #if DECDPUN<=4
6773    quot=QUOT10(*up, cut);
6774  #else
6775    quot=*up/powers[cut];
6776  #endif
6777  for (; ; target++) {
6778    *target=(Unit)quot;
6779    count-=(DECDPUN-cut);
6780    if (count<=0) break;
6781    up++;
6782    quot=*up;
6783    #if DECDPUN<=4
6784      quot=QUOT10(quot, cut);
6785      rem=*up-quot*powers[cut];
6786    #else
6787      rem=quot%powers[cut];
6788      quot=quot/powers[cut];
6789    #endif
6790    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6791    count-=cut;
6792    if (count<=0) break;
6793    }
6794  return target-uar+1;
6795  } /* decShiftToLeast  */
6796
6797#if DECSUBSET
6798/* ------------------------------------------------------------------ */
6799/* decRoundOperand -- round an operand  [used for subset only]        */
6800/*                                                                    */
6801/*   dn is the number to round (dn->digits is > set->digits)          */
6802/*   set is the relevant context                                      */
6803/*   status is the status accumulator                                 */
6804/*                                                                    */
6805/*   returns an allocated decNumber with the rounded result.          */
6806/*                                                                    */
6807/* lostDigits and other status may be set by this.                    */
6808/*                                                                    */
6809/* Since the input is an operand, it must not be modified.            */
6810/* Instead, return an allocated decNumber, rounded as required.       */
6811/* It is the caller's responsibility to free the allocated storage.   */
6812/*                                                                    */
6813/* If no storage is available then the result cannot be used, so NULL */
6814/* is returned.                                                       */
6815/* ------------------------------------------------------------------ */
6816static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6817                                  uInt *status) {
6818  decNumber *res;                       /* result structure  */
6819  uInt newstatus=0;                     /* status from round  */
6820  Int  residue=0;                       /* rounding accumulator  */
6821
6822  /* Allocate storage for the returned decNumber, big enough for the  */
6823  /* length specified by the context  */
6824  res=(decNumber *)malloc(sizeof(decNumber)
6825                          +(D2U(set->digits)-1)*sizeof(Unit));
6826  if (res==NULL) {
6827    *status|=DEC_Insufficient_storage;
6828    return NULL;
6829    }
6830  decCopyFit(res, dn, set, &residue, &newstatus);
6831  decApplyRound(res, set, residue, &newstatus);
6832
6833  /* If that set Inexact then "lost digits" is raised...  */
6834  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6835  *status|=newstatus;
6836  return res;
6837  } /* decRoundOperand  */
6838#endif
6839
6840/* ------------------------------------------------------------------ */
6841/* decCopyFit -- copy a number, truncating the coefficient if needed  */
6842/*                                                                    */
6843/*   dest is the target decNumber                                     */
6844/*   src  is the source decNumber                                     */
6845/*   set is the context [used for length (digits) and rounding mode]  */
6846/*   residue is the residue accumulator                               */
6847/*   status contains the current status to be updated                 */
6848/*                                                                    */
6849/* (dest==src is allowed and will be a no-op if fits)                 */
6850/* All fields are updated as required.                                */
6851/* ------------------------------------------------------------------ */
6852static void decCopyFit(decNumber *dest, const decNumber *src,
6853                       decContext *set, Int *residue, uInt *status) {
6854  dest->bits=src->bits;
6855  dest->exponent=src->exponent;
6856  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6857  } /* decCopyFit  */
6858
6859/* ------------------------------------------------------------------ */
6860/* decSetCoeff -- set the coefficient of a number                     */
6861/*                                                                    */
6862/*   dn    is the number whose coefficient array is to be set.        */
6863/*         It must have space for set->digits digits                  */
6864/*   set   is the context [for size]                                  */
6865/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6866/*   len   is digits in the source coefficient [may be dn->digits]    */
6867/*   residue is the residue accumulator.  This has values as in       */
6868/*         decApplyRound, and will be unchanged unless the            */
6869/*         target size is less than len.  In this case, the           */
6870/*         coefficient is truncated and the residue is updated to     */
6871/*         reflect the previous residue and the dropped digits.       */
6872/*   status is the status accumulator, as usual                       */
6873/*                                                                    */
6874/* The coefficient may already be in the number, or it can be an      */
6875/* external intermediate array.  If it is in the number, lsu must ==  */
6876/* dn->lsu and len must == dn->digits.                                */
6877/*                                                                    */
6878/* Note that the coefficient length (len) may be < set->digits, and   */
6879/* in this case this merely copies the coefficient (or is a no-op     */
6880/* if dn->lsu==lsu).                                                  */
6881/*                                                                    */
6882/* Note also that (only internally, from decQuantizeOp and            */
6883/* decSetSubnormal) the value of set->digits may be less than one,    */
6884/* indicating a round to left.  This routine handles that case        */
6885/* correctly; caller ensures space.                                   */
6886/*                                                                    */
6887/* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6888/* updated as necessary.   dn->bits (sign) is unchanged.              */
6889/*                                                                    */
6890/* DEC_Rounded status is set if any digits are discarded.             */
6891/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6892/*                       incoming residue was non-0 (implies rounded) */
6893/* ------------------------------------------------------------------ */
6894/* mapping array: maps 0-9 to canonical residues, so that a residue  */
6895/* can be adjusted in the range [-1, +1] and achieve correct rounding  */
6896/*                             0  1  2  3  4  5  6  7  8  9  */
6897static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6898static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6899                        Int len, Int *residue, uInt *status) {
6900  Int   discard;              /* number of digits to discard  */
6901  uInt  cut;                  /* cut point in Unit  */
6902  const Unit *up;             /* work  */
6903  Unit  *target;              /* ..  */
6904  Int   count;                /* ..  */
6905  #if DECDPUN<=4
6906  uInt  temp;                 /* ..  */
6907  #endif
6908
6909  discard=len-set->digits;    /* digits to discard  */
6910  if (discard<=0) {           /* no digits are being discarded  */
6911    if (dn->lsu!=lsu) {       /* copy needed  */
6912      /* copy the coefficient array to the result number; no shift needed  */
6913      count=len;              /* avoids D2U  */
6914      up=lsu;
6915      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6916        *target=*up;
6917      dn->digits=len;         /* set the new length  */
6918      }
6919    /* dn->exponent and residue are unchanged, record any inexactitude  */
6920    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6921    return;
6922    }
6923
6924  /* some digits must be discarded ...  */
6925  dn->exponent+=discard;      /* maintain numerical value  */
6926  *status|=DEC_Rounded;       /* accumulate Rounded status  */
6927  if (*residue>1) *residue=1; /* previous residue now to right, so reduce  */
6928
6929  if (discard>len) {          /* everything, +1, is being discarded  */
6930    /* guard digit is 0  */
6931    /* residue is all the number [NB could be all 0s]  */
6932    if (*residue<=0) {        /* not already positive  */
6933      count=len;              /* avoids D2U  */
6934      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0  */
6935        *residue=1;
6936        break;                /* no need to check any others  */
6937        }
6938      }
6939    if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
6940    *dn->lsu=0;               /* coefficient will now be 0  */
6941    dn->digits=1;             /* ..  */
6942    return;
6943    } /* total discard  */
6944
6945  /* partial discard [most common case]  */
6946  /* here, at least the first (most significant) discarded digit exists  */
6947
6948  /* spin up the number, noting residue during the spin, until get to  */
6949  /* the Unit with the first discarded digit.  When reach it, extract  */
6950  /* it and remember its position  */
6951  count=0;
6952  for (up=lsu;; up++) {
6953    count+=DECDPUN;
6954    if (count>=discard) break; /* full ones all checked  */
6955    if (*up!=0) *residue=1;
6956    } /* up  */
6957
6958  /* here up -> Unit with first discarded digit  */
6959  cut=discard-(count-DECDPUN)-1;
6960  if (cut==DECDPUN-1) {       /* unit-boundary case (fast)  */
6961    Unit half=(Unit)powers[DECDPUN]>>1;
6962    /* set residue directly  */
6963    if (*up>=half) {
6964      if (*up>half) *residue=7;
6965      else *residue+=5;       /* add sticky bit  */
6966      }
6967     else { /* <half  */
6968      if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit]  */
6969      }
6970    if (set->digits<=0) {     /* special for Quantize/Subnormal :-(  */
6971      *dn->lsu=0;             /* .. result is 0  */
6972      dn->digits=1;           /* ..  */
6973      }
6974     else {                   /* shift to least  */
6975      count=set->digits;      /* now digits to end up with  */
6976      dn->digits=count;       /* set the new length  */
6977      up++;                   /* move to next  */
6978      /* on unit boundary, so shift-down copy loop is simple  */
6979      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6980        *target=*up;
6981      }
6982    } /* unit-boundary case  */
6983
6984   else { /* discard digit is in low digit(s), and not top digit  */
6985    uInt  discard1;                /* first discarded digit  */
6986    uInt  quot, rem;               /* for divisions  */
6987    if (cut==0) quot=*up;          /* is at bottom of unit  */
6988     else /* cut>0 */ {            /* it's not at bottom of unit  */
6989      #if DECDPUN<=4
6990        quot=QUOT10(*up, cut);
6991        rem=*up-quot*powers[cut];
6992      #else
6993        rem=*up%powers[cut];
6994        quot=*up/powers[cut];
6995      #endif
6996      if (rem!=0) *residue=1;
6997      }
6998    /* discard digit is now at bottom of quot  */
6999    #if DECDPUN<=4
7000      temp=(quot*6554)>>16;        /* fast /10  */
7001      /* Vowels algorithm here not a win (9 instructions)  */
7002      discard1=quot-X10(temp);
7003      quot=temp;
7004    #else
7005      discard1=quot%10;
7006      quot=quot/10;
7007    #endif
7008    /* here, discard1 is the guard digit, and residue is everything  */
7009    /* else [use mapping array to accumulate residue safely]  */
7010    *residue+=resmap[discard1];
7011    cut++;                         /* update cut  */
7012    /* here: up -> Unit of the array with bottom digit  */
7013    /*       cut is the division point for each Unit  */
7014    /*       quot holds the uncut high-order digits for the current unit  */
7015    if (set->digits<=0) {          /* special for Quantize/Subnormal :-(  */
7016      *dn->lsu=0;                  /* .. result is 0  */
7017      dn->digits=1;                /* ..  */
7018      }
7019     else {                        /* shift to least needed  */
7020      count=set->digits;           /* now digits to end up with  */
7021      dn->digits=count;            /* set the new length  */
7022      /* shift-copy the coefficient array to the result number  */
7023      for (target=dn->lsu; ; target++) {
7024        *target=(Unit)quot;
7025        count-=(DECDPUN-cut);
7026        if (count<=0) break;
7027        up++;
7028        quot=*up;
7029        #if DECDPUN<=4
7030          quot=QUOT10(quot, cut);
7031          rem=*up-quot*powers[cut];
7032        #else
7033          rem=quot%powers[cut];
7034          quot=quot/powers[cut];
7035        #endif
7036        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7037        count-=cut;
7038        if (count<=0) break;
7039        } /* shift-copy loop  */
7040      } /* shift to least  */
7041    } /* not unit boundary  */
7042
7043  if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
7044  return;
7045  } /* decSetCoeff  */
7046
7047/* ------------------------------------------------------------------ */
7048/* decApplyRound -- apply pending rounding to a number                */
7049/*                                                                    */
7050/*   dn    is the number, with space for set->digits digits           */
7051/*   set   is the context [for size and rounding mode]                */
7052/*   residue indicates pending rounding, being any accumulated        */
7053/*         guard and sticky information.  It may be:                  */
7054/*         6-9: rounding digit is >5                                  */
7055/*         5:   rounding digit is exactly half-way                    */
7056/*         1-4: rounding digit is <5 and >0                           */
7057/*         0:   the coefficient is exact                              */
7058/*        -1:   as 1, but the hidden digits are subtractive, that     */
7059/*              is, of the opposite sign to dn.  In this case the     */
7060/*              coefficient must be non-0.  This case occurs when     */
7061/*              subtracting a small number (which can be reduced to   */
7062/*              a sticky bit); see decAddOp.                          */
7063/*   status is the status accumulator, as usual                       */
7064/*                                                                    */
7065/* This routine applies rounding while keeping the length of the      */
7066/* coefficient constant.  The exponent and status are unchanged       */
7067/* except if:                                                         */
7068/*                                                                    */
7069/*   -- the coefficient was increased and is all nines (in which      */
7070/*      case Overflow could occur, and is handled directly here so    */
7071/*      the caller does not need to re-test for overflow)             */
7072/*                                                                    */
7073/*   -- the coefficient was decreased and becomes all nines (in which */
7074/*      case Underflow could occur, and is also handled directly).    */
7075/*                                                                    */
7076/* All fields in dn are updated as required.                          */
7077/*                                                                    */
7078/* ------------------------------------------------------------------ */
7079static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7080                          uInt *status) {
7081  Int  bump;                  /* 1 if coefficient needs to be incremented  */
7082                              /* -1 if coefficient needs to be decremented  */
7083
7084  if (residue==0) return;     /* nothing to apply  */
7085
7086  bump=0;                     /* assume a smooth ride  */
7087
7088  /* now decide whether, and how, to round, depending on mode  */
7089  switch (set->round) {
7090    case DEC_ROUND_05UP: {    /* round zero or five up (for reround)  */
7091      /* This is the same as DEC_ROUND_DOWN unless there is a  */
7092      /* positive residue and the lsd of dn is 0 or 5, in which case  */
7093      /* it is bumped; when residue is <0, the number is therefore  */
7094      /* bumped down unless the final digit was 1 or 6 (in which  */
7095      /* case it is bumped down and then up -- a no-op)  */
7096      Int lsd5=*dn->lsu%5;     /* get lsd and quintate  */
7097      if (residue<0 && lsd5!=1) bump=-1;
7098       else if (residue>0 && lsd5==0) bump=1;
7099      /* [bump==1 could be applied directly; use common path for clarity]  */
7100      break;} /* r-05  */
7101
7102    case DEC_ROUND_DOWN: {
7103      /* no change, except if negative residue  */
7104      if (residue<0) bump=-1;
7105      break;} /* r-d  */
7106
7107    case DEC_ROUND_HALF_DOWN: {
7108      if (residue>5) bump=1;
7109      break;} /* r-h-d  */
7110
7111    case DEC_ROUND_HALF_EVEN: {
7112      if (residue>5) bump=1;            /* >0.5 goes up  */
7113       else if (residue==5) {           /* exactly 0.5000...  */
7114        /* 0.5 goes up iff [new] lsd is odd  */
7115        if (*dn->lsu & 0x01) bump=1;
7116        }
7117      break;} /* r-h-e  */
7118
7119    case DEC_ROUND_HALF_UP: {
7120      if (residue>=5) bump=1;
7121      break;} /* r-h-u  */
7122
7123    case DEC_ROUND_UP: {
7124      if (residue>0) bump=1;
7125      break;} /* r-u  */
7126
7127    case DEC_ROUND_CEILING: {
7128      /* same as _UP for positive numbers, and as _DOWN for negatives  */
7129      /* [negative residue cannot occur on 0]  */
7130      if (decNumberIsNegative(dn)) {
7131        if (residue<0) bump=-1;
7132        }
7133       else {
7134        if (residue>0) bump=1;
7135        }
7136      break;} /* r-c  */
7137
7138    case DEC_ROUND_FLOOR: {
7139      /* same as _UP for negative numbers, and as _DOWN for positive  */
7140      /* [negative residue cannot occur on 0]  */
7141      if (!decNumberIsNegative(dn)) {
7142        if (residue<0) bump=-1;
7143        }
7144       else {
7145        if (residue>0) bump=1;
7146        }
7147      break;} /* r-f  */
7148
7149    default: {      /* e.g., DEC_ROUND_MAX  */
7150      *status|=DEC_Invalid_context;
7151      #if DECTRACE || (DECCHECK && DECVERB)
7152      printf("Unknown rounding mode: %d\n", set->round);
7153      #endif
7154      break;}
7155    } /* switch  */
7156
7157  /* now bump the number, up or down, if need be  */
7158  if (bump==0) return;                       /* no action required  */
7159
7160  /* Simply use decUnitAddSub unless bumping up and the number is  */
7161  /* all nines.  In this special case set to 100... explicitly  */
7162  /* and adjust the exponent by one (as otherwise could overflow  */
7163  /* the array)  */
7164  /* Similarly handle all-nines result if bumping down.  */
7165  if (bump>0) {
7166    Unit *up;                                /* work  */
7167    uInt count=dn->digits;                   /* digits to be checked  */
7168    for (up=dn->lsu; ; up++) {
7169      if (count<=DECDPUN) {
7170        /* this is the last Unit (the msu)  */
7171        if (*up!=powers[count]-1) break;     /* not still 9s  */
7172        /* here if it, too, is all nines  */
7173        *up=(Unit)powers[count-1];           /* here 999 -> 100 etc.  */
7174        for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0  */
7175        dn->exponent++;                      /* and bump exponent  */
7176        /* [which, very rarely, could cause Overflow...]  */
7177        if ((dn->exponent+dn->digits)>set->emax+1) {
7178          decSetOverflow(dn, set, status);
7179          }
7180        return;                              /* done  */
7181        }
7182      /* a full unit to check, with more to come  */
7183      if (*up!=DECDPUNMAX) break;            /* not still 9s  */
7184      count-=DECDPUN;
7185      } /* up  */
7186    } /* bump>0  */
7187   else {                                    /* -1  */
7188    /* here checking for a pre-bump of 1000... (leading 1, all  */
7189    /* other digits zero)  */
7190    Unit *up, *sup;                          /* work  */
7191    uInt count=dn->digits;                   /* digits to be checked  */
7192    for (up=dn->lsu; ; up++) {
7193      if (count<=DECDPUN) {
7194        /* this is the last Unit (the msu)  */
7195        if (*up!=powers[count-1]) break;     /* not 100..  */
7196        /* here if have the 1000... case  */
7197        sup=up;                              /* save msu pointer  */
7198        *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999  */
7199        /* others all to all-nines, too  */
7200        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7201        dn->exponent--;                      /* and bump exponent  */
7202
7203        /* iff the number was at the subnormal boundary (exponent=etiny)  */
7204        /* then the exponent is now out of range, so it will in fact get  */
7205        /* clamped to etiny and the final 9 dropped.  */
7206        /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin,  */
7207        /*        dn->exponent, set->digits);  */
7208        if (dn->exponent+1==set->emin-set->digits+1) {
7209          if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9]  */
7210           else {
7211            *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99..  */
7212            dn->digits--;
7213            }
7214          dn->exponent++;
7215          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7216          }
7217        return;                              /* done  */
7218        }
7219
7220      /* a full unit to check, with more to come  */
7221      if (*up!=0) break;                     /* not still 0s  */
7222      count-=DECDPUN;
7223      } /* up  */
7224
7225    } /* bump<0  */
7226
7227  /* Actual bump needed.  Do it.  */
7228  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7229  } /* decApplyRound  */
7230
7231#if DECSUBSET
7232/* ------------------------------------------------------------------ */
7233/* decFinish -- finish processing a number                            */
7234/*                                                                    */
7235/*   dn is the number                                                 */
7236/*   set is the context                                               */
7237/*   residue is the rounding accumulator (as in decApplyRound)        */
7238/*   status is the accumulator                                        */
7239/*                                                                    */
7240/* This finishes off the current number by:                           */
7241/*    1. If not extended:                                             */
7242/*       a. Converting a zero result to clean '0'                     */
7243/*       b. Reducing positive exponents to 0, if would fit in digits  */
7244/*    2. Checking for overflow and subnormals (always)                */
7245/* Note this is just Finalize when no subset arithmetic.              */
7246/* All fields are updated as required.                                */
7247/* ------------------------------------------------------------------ */
7248static void decFinish(decNumber *dn, decContext *set, Int *residue,
7249                      uInt *status) {
7250  if (!set->extended) {
7251    if ISZERO(dn) {                /* value is zero  */
7252      dn->exponent=0;              /* clean exponent ..  */
7253      dn->bits=0;                  /* .. and sign  */
7254      return;                      /* no error possible  */
7255      }
7256    if (dn->exponent>=0) {         /* non-negative exponent  */
7257      /* >0; reduce to integer if possible  */
7258      if (set->digits >= (dn->exponent+dn->digits)) {
7259        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7260        dn->exponent=0;
7261        }
7262      }
7263    } /* !extended  */
7264
7265  decFinalize(dn, set, residue, status);
7266  } /* decFinish  */
7267#endif
7268
7269/* ------------------------------------------------------------------ */
7270/* decFinalize -- final check, clamp, and round of a number           */
7271/*                                                                    */
7272/*   dn is the number                                                 */
7273/*   set is the context                                               */
7274/*   residue is the rounding accumulator (as in decApplyRound)        */
7275/*   status is the status accumulator                                 */
7276/*                                                                    */
7277/* This finishes off the current number by checking for subnormal     */
7278/* results, applying any pending rounding, checking for overflow,     */
7279/* and applying any clamping.                                         */
7280/* Underflow and overflow conditions are raised as appropriate.       */
7281/* All fields are updated as required.                                */
7282/* ------------------------------------------------------------------ */
7283static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7284                        uInt *status) {
7285  Int shift;                            /* shift needed if clamping  */
7286  Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary  */
7287
7288  /* Must be careful, here, when checking the exponent as the  */
7289  /* adjusted exponent could overflow 31 bits [because it may already  */
7290  /* be up to twice the expected].  */
7291
7292  /* First test for subnormal.  This must be done before any final  */
7293  /* round as the result could be rounded to Nmin or 0.  */
7294  if (dn->exponent<=tinyexp) {          /* prefilter  */
7295    Int comp;
7296    decNumber nmin;
7297    /* A very nasty case here is dn == Nmin and residue<0  */
7298    if (dn->exponent<tinyexp) {
7299      /* Go handle subnormals; this will apply round if needed.  */
7300      decSetSubnormal(dn, set, residue, status);
7301      return;
7302      }
7303    /* Equals case: only subnormal if dn=Nmin and negative residue  */
7304    uprv_decNumberZero(&nmin);
7305    nmin.lsu[0]=1;
7306    nmin.exponent=set->emin;
7307    comp=decCompare(dn, &nmin, 1);                /* (signless compare)  */
7308    if (comp==BADINT) {                           /* oops  */
7309      *status|=DEC_Insufficient_storage;          /* abandon...  */
7310      return;
7311      }
7312    if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin  */
7313      decApplyRound(dn, set, *residue, status);   /* might force down  */
7314      decSetSubnormal(dn, set, residue, status);
7315      return;
7316      }
7317    }
7318
7319  /* now apply any pending round (this could raise overflow).  */
7320  if (*residue!=0) decApplyRound(dn, set, *residue, status);
7321
7322  /* Check for overflow [redundant in the 'rare' case] or clamp  */
7323  if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed  */
7324
7325
7326  /* here when might have an overflow or clamp to do  */
7327  if (dn->exponent>set->emax-dn->digits+1) {           /* too big  */
7328    decSetOverflow(dn, set, status);
7329    return;
7330    }
7331  /* here when the result is normal but in clamp range  */
7332  if (!set->clamp) return;
7333
7334  /* here when need to apply the IEEE exponent clamp (fold-down)  */
7335  shift=dn->exponent-(set->emax-set->digits+1);
7336
7337  /* shift coefficient (if non-zero)  */
7338  if (!ISZERO(dn)) {
7339    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7340    }
7341  dn->exponent-=shift;   /* adjust the exponent to match  */
7342  *status|=DEC_Clamped;  /* and record the dirty deed  */
7343  return;
7344  } /* decFinalize  */
7345
7346/* ------------------------------------------------------------------ */
7347/* decSetOverflow -- set number to proper overflow value              */
7348/*                                                                    */
7349/*   dn is the number (used for sign [only] and result)               */
7350/*   set is the context [used for the rounding mode, etc.]            */
7351/*   status contains the current status to be updated                 */
7352/*                                                                    */
7353/* This sets the sign of a number and sets its value to either        */
7354/* Infinity or the maximum finite value, depending on the sign of     */
7355/* dn and the rounding mode, following IEEE 754 rules.                */
7356/* ------------------------------------------------------------------ */
7357static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7358  Flag needmax=0;                  /* result is maximum finite value  */
7359  uByte sign=dn->bits&DECNEG;      /* clean and save sign bit  */
7360
7361  if (ISZERO(dn)) {                /* zero does not overflow magnitude  */
7362    Int emax=set->emax;                      /* limit value  */
7363    if (set->clamp) emax-=set->digits-1;     /* lower if clamping  */
7364    if (dn->exponent>emax) {                 /* clamp required  */
7365      dn->exponent=emax;
7366      *status|=DEC_Clamped;
7367      }
7368    return;
7369    }
7370
7371  uprv_decNumberZero(dn);
7372  switch (set->round) {
7373    case DEC_ROUND_DOWN: {
7374      needmax=1;                   /* never Infinity  */
7375      break;} /* r-d  */
7376    case DEC_ROUND_05UP: {
7377      needmax=1;                   /* never Infinity  */
7378      break;} /* r-05  */
7379    case DEC_ROUND_CEILING: {
7380      if (sign) needmax=1;         /* Infinity if non-negative  */
7381      break;} /* r-c  */
7382    case DEC_ROUND_FLOOR: {
7383      if (!sign) needmax=1;        /* Infinity if negative  */
7384      break;} /* r-f  */
7385    default: break;                /* Infinity in all other cases  */
7386    }
7387  if (needmax) {
7388    decSetMaxValue(dn, set);
7389    dn->bits=sign;                 /* set sign  */
7390    }
7391   else dn->bits=sign|DECINF;      /* Value is +/-Infinity  */
7392  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7393  } /* decSetOverflow  */
7394
7395/* ------------------------------------------------------------------ */
7396/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7397/*                                                                    */
7398/*   dn is the number to set                                          */
7399/*   set is the context [used for digits and emax]                    */
7400/*                                                                    */
7401/* This sets the number to the maximum positive value.                */
7402/* ------------------------------------------------------------------ */
7403static void decSetMaxValue(decNumber *dn, decContext *set) {
7404  Unit *up;                        /* work  */
7405  Int count=set->digits;           /* nines to add  */
7406  dn->digits=count;
7407  /* fill in all nines to set maximum value  */
7408  for (up=dn->lsu; ; up++) {
7409    if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines  */
7410     else {                             /* this is the msu  */
7411      *up=(Unit)(powers[count]-1);
7412      break;
7413      }
7414    count-=DECDPUN;                /* filled those digits  */
7415    } /* up  */
7416  dn->bits=0;                      /* + sign  */
7417  dn->exponent=set->emax-set->digits+1;
7418  } /* decSetMaxValue  */
7419
7420/* ------------------------------------------------------------------ */
7421/* decSetSubnormal -- process value whose exponent is <Emin           */
7422/*                                                                    */
7423/*   dn is the number (used as input as well as output; it may have   */
7424/*         an allowed subnormal value, which may need to be rounded)  */
7425/*   set is the context [used for the rounding mode]                  */
7426/*   residue is any pending residue                                   */
7427/*   status contains the current status to be updated                 */
7428/*                                                                    */
7429/* If subset mode, set result to zero and set Underflow flags.        */
7430/*                                                                    */
7431/* Value may be zero with a low exponent; this does not set Subnormal */
7432/* but the exponent will be clamped to Etiny.                         */
7433/*                                                                    */
7434/* Otherwise ensure exponent is not out of range, and round as        */
7435/* necessary.  Underflow is set if the result is Inexact.             */
7436/* ------------------------------------------------------------------ */
7437static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7438                            uInt *status) {
7439  decContext workset;         /* work  */
7440  Int        etiny, adjust;   /* ..  */
7441
7442  #if DECSUBSET
7443  /* simple set to zero and 'hard underflow' for subset  */
7444  if (!set->extended) {
7445    uprv_decNumberZero(dn);
7446    /* always full overflow  */
7447    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7448    return;
7449    }
7450  #endif
7451
7452  /* Full arithmetic -- allow subnormals, rounded to minimum exponent  */
7453  /* (Etiny) if needed  */
7454  etiny=set->emin-(set->digits-1);      /* smallest allowed exponent  */
7455
7456  if ISZERO(dn) {                       /* value is zero  */
7457    /* residue can never be non-zero here  */
7458    #if DECCHECK
7459      if (*residue!=0) {
7460        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7461        *status|=DEC_Invalid_operation;
7462        }
7463    #endif
7464    if (dn->exponent<etiny) {           /* clamp required  */
7465      dn->exponent=etiny;
7466      *status|=DEC_Clamped;
7467      }
7468    return;
7469    }
7470
7471  *status|=DEC_Subnormal;               /* have a non-zero subnormal  */
7472  adjust=etiny-dn->exponent;            /* calculate digits to remove  */
7473  if (adjust<=0) {                      /* not out of range; unrounded  */
7474    /* residue can never be non-zero here, except in the Nmin-residue  */
7475    /* case (which is a subnormal result), so can take fast-path here  */
7476    /* it may already be inexact (from setting the coefficient)  */
7477    if (*status&DEC_Inexact) *status|=DEC_Underflow;
7478    return;
7479    }
7480
7481  /* adjust>0, so need to rescale the result so exponent becomes Etiny  */
7482  /* [this code is similar to that in rescale]  */
7483  workset=*set;                         /* clone rounding, etc.  */
7484  workset.digits=dn->digits-adjust;     /* set requested length  */
7485  workset.emin-=adjust;                 /* and adjust emin to match  */
7486  /* [note that the latter can be <1, here, similar to Rescale case]  */
7487  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7488  decApplyRound(dn, &workset, *residue, status);
7489
7490  /* Use 754 default rule: Underflow is set iff Inexact  */
7491  /* [independent of whether trapped]  */
7492  if (*status&DEC_Inexact) *status|=DEC_Underflow;
7493
7494  /* if rounded up a 999s case, exponent will be off by one; adjust  */
7495  /* back if so [it will fit, because it was shortened earlier]  */
7496  if (dn->exponent>etiny) {
7497    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7498    dn->exponent--;                     /* (re)adjust the exponent.  */
7499    }
7500
7501  /* if rounded to zero, it is by definition clamped...  */
7502  if (ISZERO(dn)) *status|=DEC_Clamped;
7503  } /* decSetSubnormal  */
7504
7505/* ------------------------------------------------------------------ */
7506/* decCheckMath - check entry conditions for a math function          */
7507/*                                                                    */
7508/*   This checks the context and the operand                          */
7509/*                                                                    */
7510/*   rhs is the operand to check                                      */
7511/*   set is the context to check                                      */
7512/*   status is unchanged if both are good                             */
7513/*                                                                    */
7514/* returns non-zero if status is changed, 0 otherwise                 */
7515/*                                                                    */
7516/* Restrictions enforced:                                             */
7517/*                                                                    */
7518/*   digits, emax, and -emin in the context must be less than         */
7519/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7520/*   non-zero.  Invalid_operation is set in the status if a           */
7521/*   restriction is violated.                                         */
7522/* ------------------------------------------------------------------ */
7523static uInt decCheckMath(const decNumber *rhs, decContext *set,
7524                         uInt *status) {
7525  uInt save=*status;                         /* record  */
7526  if (set->digits>DEC_MAX_MATH
7527   || set->emax>DEC_MAX_MATH
7528   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7529   else if ((rhs->digits>DEC_MAX_MATH
7530     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7531     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7532     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7533  return (*status!=save);
7534  } /* decCheckMath  */
7535
7536/* ------------------------------------------------------------------ */
7537/* decGetInt -- get integer from a number                             */
7538/*                                                                    */
7539/*   dn is the number [which will not be altered]                     */
7540/*                                                                    */
7541/*   returns one of:                                                  */
7542/*     BADINT if there is a non-zero fraction                         */
7543/*     the converted integer                                          */
7544/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7545/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7546/*                                                                    */
7547/* This checks and gets a whole number from the input decNumber.      */
7548/* The sign can be determined from dn by the caller when BIGEVEN or   */
7549/* BIGODD is returned.                                                */
7550/* ------------------------------------------------------------------ */
7551static Int decGetInt(const decNumber *dn) {
7552  Int  theInt;                          /* result accumulator  */
7553  const Unit *up;                       /* work  */
7554  Int  got;                             /* digits (real or not) processed  */
7555  Int  ilength=dn->digits+dn->exponent; /* integral length  */
7556  Flag neg=decNumberIsNegative(dn);     /* 1 if -ve  */
7557
7558  /* The number must be an integer that fits in 10 digits  */
7559  /* Assert, here, that 10 is enough for any rescale Etiny  */
7560  #if DEC_MAX_EMAX > 999999999
7561    #error GetInt may need updating [for Emax]
7562  #endif
7563  #if DEC_MIN_EMIN < -999999999
7564    #error GetInt may need updating [for Emin]
7565  #endif
7566  if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent  */
7567
7568  up=dn->lsu;                           /* ready for lsu  */
7569  theInt=0;                             /* ready to accumulate  */
7570  if (dn->exponent>=0) {                /* relatively easy  */
7571    /* no fractional part [usual]; allow for positive exponent  */
7572    got=dn->exponent;
7573    }
7574   else { /* -ve exponent; some fractional part to check and discard  */
7575    Int count=-dn->exponent;            /* digits to discard  */
7576    /* spin up whole units until reach the Unit with the unit digit  */
7577    for (; count>=DECDPUN; up++) {
7578      if (*up!=0) return BADINT;        /* non-zero Unit to discard  */
7579      count-=DECDPUN;
7580      }
7581    if (count==0) got=0;                /* [a multiple of DECDPUN]  */
7582     else {                             /* [not multiple of DECDPUN]  */
7583      Int rem;                          /* work  */
7584      /* slice off fraction digits and check for non-zero  */
7585      #if DECDPUN<=4
7586        theInt=QUOT10(*up, count);
7587        rem=*up-theInt*powers[count];
7588      #else
7589        rem=*up%powers[count];          /* slice off discards  */
7590        theInt=*up/powers[count];
7591      #endif
7592      if (rem!=0) return BADINT;        /* non-zero fraction  */
7593      /* it looks good  */
7594      got=DECDPUN-count;                /* number of digits so far  */
7595      up++;                             /* ready for next  */
7596      }
7597    }
7598  /* now it's known there's no fractional part  */
7599
7600  /* tricky code now, to accumulate up to 9.3 digits  */
7601  if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there  */
7602
7603  if (ilength<11) {
7604    Int save=theInt;
7605    /* collect any remaining unit(s)  */
7606    for (; got<ilength; up++) {
7607      theInt+=*up*powers[got];
7608      got+=DECDPUN;
7609      }
7610    if (ilength==10) {                  /* need to check for wrap  */
7611      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7612         /* [that test also disallows the BADINT result case]  */
7613       else if (neg && theInt>1999999997) ilength=11;
7614       else if (!neg && theInt>999999999) ilength=11;
7615      if (ilength==11) theInt=save;     /* restore correct low bit  */
7616      }
7617    }
7618
7619  if (ilength>10) {                     /* too big  */
7620    if (theInt&1) return BIGODD;        /* bottom bit 1  */
7621    return BIGEVEN;                     /* bottom bit 0  */
7622    }
7623
7624  if (neg) theInt=-theInt;              /* apply sign  */
7625  return theInt;
7626  } /* decGetInt  */
7627
7628/* ------------------------------------------------------------------ */
7629/* decDecap -- decapitate the coefficient of a number                 */
7630/*                                                                    */
7631/*   dn   is the number to be decapitated                             */
7632/*   drop is the number of digits to be removed from the left of dn;  */
7633/*     this must be <= dn->digits (if equal, the coefficient is       */
7634/*     set to 0)                                                      */
7635/*                                                                    */
7636/* Returns dn; dn->digits will be <= the initial digits less drop     */
7637/* (after removing drop digits there may be leading zero digits       */
7638/* which will also be removed).  Only dn->lsu and dn->digits change.  */
7639/* ------------------------------------------------------------------ */
7640static decNumber *decDecap(decNumber *dn, Int drop) {
7641  Unit *msu;                            /* -> target cut point  */
7642  Int cut;                              /* work  */
7643  if (drop>=dn->digits) {               /* losing the whole thing  */
7644    #if DECCHECK
7645    if (drop>dn->digits)
7646      printf("decDecap called with drop>digits [%ld>%ld]\n",
7647             (LI)drop, (LI)dn->digits);
7648    #endif
7649    dn->lsu[0]=0;
7650    dn->digits=1;
7651    return dn;
7652    }
7653  msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu  */
7654  cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu  */
7655  if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits  */
7656  /* that may have left leading zero digits, so do a proper count...  */
7657  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7658  return dn;
7659  } /* decDecap  */
7660
7661/* ------------------------------------------------------------------ */
7662/* decBiStr -- compare string with pairwise options                   */
7663/*                                                                    */
7664/*   targ is the string to compare                                    */
7665/*   str1 is one of the strings to compare against (length may be 0)  */
7666/*   str2 is the other; it must be the same length as str1            */
7667/*                                                                    */
7668/*   returns 1 if strings compare equal, (that is, it is the same     */
7669/*   length as str1 and str2, and each character of targ is in either */
7670/*   str1 or str2 in the corresponding position), or 0 otherwise      */
7671/*                                                                    */
7672/* This is used for generic caseless compare, including the awkward   */
7673/* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7674/*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7675/* ------------------------------------------------------------------ */
7676static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7677  for (;;targ++, str1++, str2++) {
7678    if (*targ!=*str1 && *targ!=*str2) return 0;
7679    /* *targ has a match in one (or both, if terminator)  */
7680    if (*targ=='\0') break;
7681    } /* forever  */
7682  return 1;
7683  } /* decBiStr  */
7684
7685/* ------------------------------------------------------------------ */
7686/* decNaNs -- handle NaN operand or operands                          */
7687/*                                                                    */
7688/*   res     is the result number                                     */
7689/*   lhs     is the first operand                                     */
7690/*   rhs     is the second operand, or NULL if none                   */
7691/*   context is used to limit payload length                          */
7692/*   status  contains the current status                              */
7693/*   returns res in case convenient                                   */
7694/*                                                                    */
7695/* Called when one or both operands is a NaN, and propagates the      */
7696/* appropriate result to res.  When an sNaN is found, it is changed   */
7697/* to a qNaN and Invalid operation is set.                            */
7698/* ------------------------------------------------------------------ */
7699static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7700                           const decNumber *rhs, decContext *set,
7701                           uInt *status) {
7702  /* This decision tree ends up with LHS being the source pointer,  */
7703  /* and status updated if need be  */
7704  if (lhs->bits & DECSNAN)
7705    *status|=DEC_Invalid_operation | DEC_sNaN;
7706   else if (rhs==NULL);
7707   else if (rhs->bits & DECSNAN) {
7708    lhs=rhs;
7709    *status|=DEC_Invalid_operation | DEC_sNaN;
7710    }
7711   else if (lhs->bits & DECNAN);
7712   else lhs=rhs;
7713
7714  /* propagate the payload  */
7715  if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy  */
7716   else { /* too long  */
7717    const Unit *ul;
7718    Unit *ur, *uresp1;
7719    /* copy safe number of units, then decapitate  */
7720    res->bits=lhs->bits;                /* need sign etc.  */
7721    uresp1=res->lsu+D2U(set->digits);
7722    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7723    res->digits=D2U(set->digits)*DECDPUN;
7724    /* maybe still too long  */
7725    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7726    }
7727
7728  res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while  */
7729  res->bits|=DECNAN;          /* .. preserving sign  */
7730  res->exponent=0;            /* clean exponent  */
7731                              /* [coefficient was copied/decapitated]  */
7732  return res;
7733  } /* decNaNs  */
7734
7735/* ------------------------------------------------------------------ */
7736/* decStatus -- apply non-zero status                                 */
7737/*                                                                    */
7738/*   dn     is the number to set if error                             */
7739/*   status contains the current status (not yet in context)          */
7740/*   set    is the context                                            */
7741/*                                                                    */
7742/* If the status is an error status, the number is set to a NaN,      */
7743/* unless the error was an overflow, divide-by-zero, or underflow,    */
7744/* in which case the number will have already been set.               */
7745/*                                                                    */
7746/* The context status is then updated with the new status.  Note that */
7747/* this may raise a signal, so control may never return from this     */
7748/* routine (hence resources must be recovered before it is called).   */
7749/* ------------------------------------------------------------------ */
7750static void decStatus(decNumber *dn, uInt status, decContext *set) {
7751  if (status & DEC_NaNs) {              /* error status -> NaN  */
7752    /* if cause was an sNaN, clear and propagate [NaN is already set up]  */
7753    if (status & DEC_sNaN) status&=~DEC_sNaN;
7754     else {
7755      uprv_decNumberZero(dn);                /* other error: clean throughout  */
7756      dn->bits=DECNAN;                  /* and make a quiet NaN  */
7757      }
7758    }
7759  uprv_decContextSetStatus(set, status);     /* [may not return]  */
7760  return;
7761  } /* decStatus  */
7762
7763/* ------------------------------------------------------------------ */
7764/* decGetDigits -- count digits in a Units array                      */
7765/*                                                                    */
7766/*   uar is the Unit array holding the number (this is often an       */
7767/*          accumulator of some sort)                                 */
7768/*   len is the length of the array in units [>=1]                    */
7769/*                                                                    */
7770/*   returns the number of (significant) digits in the array          */
7771/*                                                                    */
7772/* All leading zeros are excluded, except the last if the array has   */
7773/* only zero Units.                                                   */
7774/* ------------------------------------------------------------------ */
7775/* This may be called twice during some operations.  */
7776static Int decGetDigits(Unit *uar, Int len) {
7777  Unit *up=uar+(len-1);            /* -> msu  */
7778  Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu  */
7779  #if DECDPUN>4
7780  uInt const *pow;                 /* work  */
7781  #endif
7782                                   /* (at least 1 in final msu)  */
7783  #if DECCHECK
7784  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7785  #endif
7786
7787  for (; up>=uar; up--) {
7788    if (*up==0) {                  /* unit is all 0s  */
7789      if (digits==1) break;        /* a zero has one digit  */
7790      digits-=DECDPUN;             /* adjust for 0 unit  */
7791      continue;}
7792    /* found the first (most significant) non-zero Unit  */
7793    #if DECDPUN>1                  /* not done yet  */
7794    if (*up<10) break;             /* is 1-9  */
7795    digits++;
7796    #if DECDPUN>2                  /* not done yet  */
7797    if (*up<100) break;            /* is 10-99  */
7798    digits++;
7799    #if DECDPUN>3                  /* not done yet  */
7800    if (*up<1000) break;           /* is 100-999  */
7801    digits++;
7802    #if DECDPUN>4                  /* count the rest ...  */
7803    for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7804    #endif
7805    #endif
7806    #endif
7807    #endif
7808    break;
7809    } /* up  */
7810  return digits;
7811  } /* decGetDigits  */
7812
7813#if DECTRACE | DECCHECK
7814/* ------------------------------------------------------------------ */
7815/* decNumberShow -- display a number [debug aid]                      */
7816/*   dn is the number to show                                         */
7817/*                                                                    */
7818/* Shows: sign, exponent, coefficient (msu first), digits             */
7819/*    or: sign, special-value                                         */
7820/* ------------------------------------------------------------------ */
7821/* this is public so other modules can use it  */
7822void uprv_decNumberShow(const decNumber *dn) {
7823  const Unit *up;                  /* work  */
7824  uInt u, d;                       /* ..  */
7825  Int cut;                         /* ..  */
7826  char isign='+';                  /* main sign  */
7827  if (dn==NULL) {
7828    printf("NULL\n");
7829    return;}
7830  if (decNumberIsNegative(dn)) isign='-';
7831  printf(" >> %c ", isign);
7832  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
7833    if (decNumberIsInfinite(dn)) printf("Infinity");
7834     else {                                  /* a NaN  */
7835      if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN  */
7836       else printf("NaN");
7837      }
7838    /* if coefficient and exponent are 0, no more to do  */
7839    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7840      printf("\n");
7841      return;}
7842    /* drop through to report other information  */
7843    printf(" ");
7844    }
7845
7846  /* now carefully display the coefficient  */
7847  up=dn->lsu+D2U(dn->digits)-1;         /* msu  */
7848  printf("%ld", (LI)*up);
7849  for (up=up-1; up>=dn->lsu; up--) {
7850    u=*up;
7851    printf(":");
7852    for (cut=DECDPUN-1; cut>=0; cut--) {
7853      d=u/powers[cut];
7854      u-=d*powers[cut];
7855      printf("%ld", (LI)d);
7856      } /* cut  */
7857    } /* up  */
7858  if (dn->exponent!=0) {
7859    char esign='+';
7860    if (dn->exponent<0) esign='-';
7861    printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7862    }
7863  printf(" [%ld]\n", (LI)dn->digits);
7864  } /* decNumberShow  */
7865#endif
7866
7867#if DECTRACE || DECCHECK
7868/* ------------------------------------------------------------------ */
7869/* decDumpAr -- display a unit array [debug/check aid]                */
7870/*   name is a single-character tag name                              */
7871/*   ar   is the array to display                                     */
7872/*   len  is the length of the array in Units                         */
7873/* ------------------------------------------------------------------ */
7874static void decDumpAr(char name, const Unit *ar, Int len) {
7875  Int i;
7876  const char *spec;
7877  #if DECDPUN==9
7878    spec="%09d ";
7879  #elif DECDPUN==8
7880    spec="%08d ";
7881  #elif DECDPUN==7
7882    spec="%07d ";
7883  #elif DECDPUN==6
7884    spec="%06d ";
7885  #elif DECDPUN==5
7886    spec="%05d ";
7887  #elif DECDPUN==4
7888    spec="%04d ";
7889  #elif DECDPUN==3
7890    spec="%03d ";
7891  #elif DECDPUN==2
7892    spec="%02d ";
7893  #else
7894    spec="%d ";
7895  #endif
7896  printf("  :%c: ", name);
7897  for (i=len-1; i>=0; i--) {
7898    if (i==len-1) printf("%ld ", (LI)ar[i]);
7899     else printf(spec, ar[i]);
7900    }
7901  printf("\n");
7902  return;}
7903#endif
7904
7905#if DECCHECK
7906/* ------------------------------------------------------------------ */
7907/* decCheckOperands -- check operand(s) to a routine                  */
7908/*   res is the result structure (not checked; it will be set to      */
7909/*          quiet NaN if error found (and it is not NULL))            */
7910/*   lhs is the first operand (may be DECUNRESU)                      */
7911/*   rhs is the second (may be DECUNUSED)                             */
7912/*   set is the context (may be DECUNCONT)                            */
7913/*   returns 0 if both operands, and the context are clean, or 1      */
7914/*     otherwise (in which case the context will show an error,       */
7915/*     unless NULL).  Note that res is not cleaned; caller should     */
7916/*     handle this so res=NULL case is safe.                          */
7917/* The caller is expected to abandon immediately if 1 is returned.    */
7918/* ------------------------------------------------------------------ */
7919static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7920                             const decNumber *rhs, decContext *set) {
7921  Flag bad=0;
7922  if (set==NULL) {                 /* oops; hopeless  */
7923    #if DECTRACE || DECVERB
7924    printf("Reference to context is NULL.\n");
7925    #endif
7926    bad=1;
7927    return 1;}
7928   else if (set!=DECUNCONT
7929     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7930    bad=1;
7931    #if DECTRACE || DECVERB
7932    printf("Bad context [digits=%ld round=%ld].\n",
7933           (LI)set->digits, (LI)set->round);
7934    #endif
7935    }
7936   else {
7937    if (res==NULL) {
7938      bad=1;
7939      #if DECTRACE
7940      /* this one not DECVERB as standard tests include NULL  */
7941      printf("Reference to result is NULL.\n");
7942      #endif
7943      }
7944    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7945    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7946    }
7947  if (bad) {
7948    if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7949    if (res!=DECUNRESU && res!=NULL) {
7950      uprv_decNumberZero(res);
7951      res->bits=DECNAN;       /* qNaN  */
7952      }
7953    }
7954  return bad;
7955  } /* decCheckOperands  */
7956
7957/* ------------------------------------------------------------------ */
7958/* decCheckNumber -- check a number                                   */
7959/*   dn is the number to check                                        */
7960/*   returns 0 if the number is clean, or 1 otherwise                 */
7961/*                                                                    */
7962/* The number is considered valid if it could be a result from some   */
7963/* operation in some valid context.                                   */
7964/* ------------------------------------------------------------------ */
7965static Flag decCheckNumber(const decNumber *dn) {
7966  const Unit *up;             /* work  */
7967  uInt maxuint;               /* ..  */
7968  Int ae, d, digits;          /* ..  */
7969  Int emin, emax;             /* ..  */
7970
7971  if (dn==NULL) {             /* hopeless  */
7972    #if DECTRACE
7973    /* this one not DECVERB as standard tests include NULL  */
7974    printf("Reference to decNumber is NULL.\n");
7975    #endif
7976    return 1;}
7977
7978  /* check special values  */
7979  if (dn->bits & DECSPECIAL) {
7980    if (dn->exponent!=0) {
7981      #if DECTRACE || DECVERB
7982      printf("Exponent %ld (not 0) for a special value [%02x].\n",
7983             (LI)dn->exponent, dn->bits);
7984      #endif
7985      return 1;}
7986
7987    /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only  */
7988    if (decNumberIsInfinite(dn)) {
7989      if (dn->digits!=1) {
7990        #if DECTRACE || DECVERB
7991        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
7992        #endif
7993        return 1;}
7994      if (*dn->lsu!=0) {
7995        #if DECTRACE || DECVERB
7996        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
7997        #endif
7998        decDumpAr('I', dn->lsu, D2U(dn->digits));
7999        return 1;}
8000      } /* Inf  */
8001    /* 2002.12.26: negative NaNs can now appear through proposed IEEE  */
8002    /*             concrete formats (decimal64, etc.).  */
8003    return 0;
8004    }
8005
8006  /* check the coefficient  */
8007  if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8008    #if DECTRACE || DECVERB
8009    printf("Digits %ld in number.\n", (LI)dn->digits);
8010    #endif
8011    return 1;}
8012
8013  d=dn->digits;
8014
8015  for (up=dn->lsu; d>0; up++) {
8016    if (d>DECDPUN) maxuint=DECDPUNMAX;
8017     else {                   /* reached the msu  */
8018      maxuint=powers[d]-1;
8019      if (dn->digits>1 && *up<powers[d-1]) {
8020        #if DECTRACE || DECVERB
8021        printf("Leading 0 in number.\n");
8022        uprv_decNumberShow(dn);
8023        #endif
8024        return 1;}
8025      }
8026    if (*up>maxuint) {
8027      #if DECTRACE || DECVERB
8028      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8029              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8030      #endif
8031      return 1;}
8032    d-=DECDPUN;
8033    }
8034
8035  /* check the exponent.  Note that input operands can have exponents  */
8036  /* which are out of the set->emin/set->emax and set->digits range  */
8037  /* (just as they can have more digits than set->digits).  */
8038  ae=dn->exponent+dn->digits-1;    /* adjusted exponent  */
8039  emax=DECNUMMAXE;
8040  emin=DECNUMMINE;
8041  digits=DECNUMMAXP;
8042  if (ae<emin-(digits-1)) {
8043    #if DECTRACE || DECVERB
8044    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8045    uprv_decNumberShow(dn);
8046    #endif
8047    return 1;}
8048  if (ae>+emax) {
8049    #if DECTRACE || DECVERB
8050    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8051    uprv_decNumberShow(dn);
8052    #endif
8053    return 1;}
8054
8055  return 0;              /* it's OK  */
8056  } /* decCheckNumber  */
8057
8058/* ------------------------------------------------------------------ */
8059/* decCheckInexact -- check a normal finite inexact result has digits */
8060/*   dn is the number to check                                        */
8061/*   set is the context (for status and precision)                    */
8062/*   sets Invalid operation, etc., if some digits are missing         */
8063/* [this check is not made for DECSUBSET compilation or when          */
8064/* subnormal is not set]                                              */
8065/* ------------------------------------------------------------------ */
8066static void decCheckInexact(const decNumber *dn, decContext *set) {
8067  #if !DECSUBSET && DECEXTFLAG
8068    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8069     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8070      #if DECTRACE || DECVERB
8071      printf("Insufficient digits [%ld] on normal Inexact result.\n",
8072             (LI)dn->digits);
8073      uprv_decNumberShow(dn);
8074      #endif
8075      uprv_decContextSetStatus(set, DEC_Invalid_operation);
8076      }
8077  #else
8078    /* next is a noop for quiet compiler  */
8079    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8080  #endif
8081  return;
8082  } /* decCheckInexact  */
8083#endif
8084
8085#if DECALLOC
8086#undef malloc
8087#undef free
8088/* ------------------------------------------------------------------ */
8089/* decMalloc -- accountable allocation routine                        */
8090/*   n is the number of bytes to allocate                             */
8091/*                                                                    */
8092/* Semantics is the same as the stdlib malloc routine, but bytes      */
8093/* allocated are accounted for globally, and corruption fences are    */
8094/* added before and after the 'actual' storage.                       */
8095/* ------------------------------------------------------------------ */
8096/* This routine allocates storage with an extra twelve bytes; 8 are   */
8097/* at the start and hold:                                             */
8098/*   0-3 the original length requested                                */
8099/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8100/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8101/* ------------------------------------------------------------------ */
8102static void *decMalloc(size_t n) {
8103  uInt  size=n+12;                 /* true size  */
8104  void  *alloc;                    /* -> allocated storage  */
8105  uByte *b, *b0;                   /* work  */
8106  uInt  uiwork;                    /* for macros  */
8107
8108  alloc=malloc(size);              /* -> allocated storage  */
8109  if (alloc==NULL) return NULL;    /* out of strorage  */
8110  b0=(uByte *)alloc;               /* as bytes  */
8111  decAllocBytes+=n;                /* account for storage  */
8112  UBFROMUI(alloc, n);              /* save n  */
8113  /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);  */
8114  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8115  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8116  return b0+8;                     /* -> play area  */
8117  } /* decMalloc  */
8118
8119/* ------------------------------------------------------------------ */
8120/* decFree -- accountable free routine                                */
8121/*   alloc is the storage to free                                     */
8122/*                                                                    */
8123/* Semantics is the same as the stdlib malloc routine, except that    */
8124/* the global storage accounting is updated and the fences are        */
8125/* checked to ensure that no routine has written 'out of bounds'.     */
8126/* ------------------------------------------------------------------ */
8127/* This routine first checks that the fences have not been corrupted. */
8128/* It then frees the storage using the 'truw' storage address (that   */
8129/* is, offset by 8).                                                  */
8130/* ------------------------------------------------------------------ */
8131static void decFree(void *alloc) {
8132  uInt  n;                         /* original length  */
8133  uByte *b, *b0;                   /* work  */
8134  uInt  uiwork;                    /* for macros  */
8135
8136  if (alloc==NULL) return;         /* allowed; it's a nop  */
8137  b0=(uByte *)alloc;               /* as bytes  */
8138  b0-=8;                           /* -> true start of storage  */
8139  n=UBTOUI(b0);                    /* lift length  */
8140  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8141    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8142           b-b0-8, (LI)b0);
8143  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8144    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8145           b-b0-8, (LI)b0, (LI)n);
8146  free(b0);                        /* drop the storage  */
8147  decAllocBytes-=n;                /* account for storage  */
8148  /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);  */
8149  } /* decFree  */
8150#define malloc(a) decMalloc(a)
8151#define free(a) decFree(a)
8152#endif
8153