1/* ------------------------------------------------------------------ */
2/* Decimal Number arithmetic module                                   */
3/* ------------------------------------------------------------------ */
4/* Copyright (c) IBM Corporation, 2000-2012.  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#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
1396#pragma GCC diagnostic push
1397#pragma GCC diagnostic ignored "-Warray-bounds"
1398#endif
1399U_CAPI decNumber * U_EXPORT2 uprv_decNumberLog10(decNumber *res, const decNumber *rhs,
1400                          decContext *set) {
1401  uInt status=0, ignore=0;         /* status accumulators  */
1402  uInt needbytes;                  /* for space calculations  */
1403  Int p;                           /* working precision  */
1404  Int t;                           /* digits in exponent of A  */
1405
1406  /* buffers for a and b working decimals  */
1407  /* (adjustment calculator, same size)  */
1408  decNumber bufa[D2N(DECBUFFER+2)];
1409  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
1410  decNumber *a=bufa;               /* temporary a  */
1411  decNumber bufb[D2N(DECBUFFER+2)];
1412  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
1413  decNumber *b=bufb;               /* temporary b  */
1414  decNumber bufw[D2N(10)];         /* working 2-10 digit number  */
1415  decNumber *w=bufw;               /* ..  */
1416  #if DECSUBSET
1417  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
1418  #endif
1419
1420  decContext aset;                 /* working context  */
1421
1422  #if DECCHECK
1423  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1424  #endif
1425
1426  /* Check restrictions; this is a math function; if not violated  */
1427  /* then carry out the operation.  */
1428  if (!decCheckMath(rhs, set, &status)) do { /* protect malloc  */
1429    #if DECSUBSET
1430    if (!set->extended) {
1431      /* reduce operand and set lostDigits status, as needed  */
1432      if (rhs->digits>set->digits) {
1433        allocrhs=decRoundOperand(rhs, set, &status);
1434        if (allocrhs==NULL) break;
1435        rhs=allocrhs;
1436        }
1437      /* special check in subset for rhs=0  */
1438      if (ISZERO(rhs)) {                /* +/- zeros -> error  */
1439        status|=DEC_Invalid_operation;
1440        break;}
1441      } /* extended=0  */
1442    #endif
1443
1444    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
1445
1446    /* handle exact powers of 10; only check if +ve finite  */
1447    if (!(rhs->bits&(DECNEG|DECSPECIAL)) && !ISZERO(rhs)) {
1448      Int residue=0;               /* (no residue)  */
1449      uInt copystat=0;             /* clean status  */
1450
1451      /* round to a single digit...  */
1452      aset.digits=1;
1453      decCopyFit(w, rhs, &aset, &residue, &copystat); /* copy & shorten  */
1454      /* if exact and the digit is 1, rhs is a power of 10  */
1455      if (!(copystat&DEC_Inexact) && w->lsu[0]==1) {
1456        /* the exponent, conveniently, is the power of 10; making  */
1457        /* this the result needs a little care as it might not fit,  */
1458        /* so first convert it into the working number, and then move  */
1459        /* to res  */
1460        uprv_decNumberFromInt32(w, w->exponent);
1461        residue=0;
1462        decCopyFit(res, w, set, &residue, &status); /* copy & round  */
1463        decFinish(res, set, &residue, &status);     /* cleanup/set flags  */
1464        break;
1465        } /* not a power of 10  */
1466      } /* not a candidate for exact  */
1467
1468    /* simplify the information-content calculation to use 'total  */
1469    /* number of digits in a, including exponent' as compared to the  */
1470    /* requested digits, as increasing this will only rarely cost an  */
1471    /* iteration in ln(a) anyway  */
1472    t=6;                                /* it can never be >6  */
1473
1474    /* allocate space when needed...  */
1475    p=(rhs->digits+t>set->digits?rhs->digits+t:set->digits)+3;
1476    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1477    if (needbytes>sizeof(bufa)) {       /* need malloc space  */
1478      allocbufa=(decNumber *)malloc(needbytes);
1479      if (allocbufa==NULL) {            /* hopeless -- abandon  */
1480        status|=DEC_Insufficient_storage;
1481        break;}
1482      a=allocbufa;                      /* use the allocated space  */
1483      }
1484    aset.digits=p;                      /* as calculated  */
1485    aset.emax=DEC_MAX_MATH;             /* usual bounds  */
1486    aset.emin=-DEC_MAX_MATH;            /* ..  */
1487    aset.clamp=0;                       /* and no concrete format  */
1488    decLnOp(a, rhs, &aset, &status);    /* a=ln(rhs)  */
1489
1490    /* skip the division if the result so far is infinite, NaN, or  */
1491    /* zero, or there was an error; note NaN from sNaN needs copy  */
1492    if (status&DEC_NaNs && !(status&DEC_sNaN)) break;
1493    if (a->bits&DECSPECIAL || ISZERO(a)) {
1494      uprv_decNumberCopy(res, a);            /* [will fit]  */
1495      break;}
1496
1497    /* for ln(10) an extra 3 digits of precision are needed  */
1498    p=set->digits+3;
1499    needbytes=sizeof(decNumber)+(D2U(p)-1)*sizeof(Unit);
1500    if (needbytes>sizeof(bufb)) {       /* need malloc space  */
1501      allocbufb=(decNumber *)malloc(needbytes);
1502      if (allocbufb==NULL) {            /* hopeless -- abandon  */
1503        status|=DEC_Insufficient_storage;
1504        break;}
1505      b=allocbufb;                      /* use the allocated space  */
1506      }
1507    uprv_decNumberZero(w);                   /* set up 10...  */
1508    #if DECDPUN==1
1509    w->lsu[1]=1; w->lsu[0]=0;           /* ..  */
1510    #else
1511    w->lsu[0]=10;                       /* ..  */
1512    #endif
1513    w->digits=2;                        /* ..  */
1514
1515    aset.digits=p;
1516    decLnOp(b, w, &aset, &ignore);      /* b=ln(10)  */
1517
1518    aset.digits=set->digits;            /* for final divide  */
1519    decDivideOp(res, a, b, &aset, DIVIDE, &status); /* into result  */
1520    } while(0);                         /* [for break]  */
1521
1522  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
1523  if (allocbufb!=NULL) free(allocbufb); /* ..  */
1524  #if DECSUBSET
1525  if (allocrhs !=NULL) free(allocrhs);  /* ..  */
1526  #endif
1527  /* apply significant status  */
1528  if (status!=0) decStatus(res, status, set);
1529  #if DECCHECK
1530  decCheckInexact(res, set);
1531  #endif
1532  return res;
1533  } /* decNumberLog10  */
1534#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
1535#pragma GCC diagnostic pop
1536#endif
1537
1538/* ------------------------------------------------------------------ */
1539/* decNumberMax -- compare two Numbers and return the maximum         */
1540/*                                                                    */
1541/*   This computes C = A ? B, returning the maximum by 754 rules      */
1542/*                                                                    */
1543/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1544/*   lhs is A                                                         */
1545/*   rhs is B                                                         */
1546/*   set is the context                                               */
1547/*                                                                    */
1548/* C must have space for set->digits digits.                          */
1549/* ------------------------------------------------------------------ */
1550U_CAPI decNumber * U_EXPORT2 uprv_decNumberMax(decNumber *res, const decNumber *lhs,
1551                         const decNumber *rhs, decContext *set) {
1552  uInt status=0;                        /* accumulator  */
1553  decCompareOp(res, lhs, rhs, set, COMPMAX, &status);
1554  if (status!=0) decStatus(res, status, set);
1555  #if DECCHECK
1556  decCheckInexact(res, set);
1557  #endif
1558  return res;
1559  } /* decNumberMax  */
1560
1561/* ------------------------------------------------------------------ */
1562/* decNumberMaxMag -- compare and return the maximum by magnitude     */
1563/*                                                                    */
1564/*   This computes C = A ? B, returning the maximum by 754 rules      */
1565/*                                                                    */
1566/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1567/*   lhs is A                                                         */
1568/*   rhs is B                                                         */
1569/*   set is the context                                               */
1570/*                                                                    */
1571/* C must have space for set->digits digits.                          */
1572/* ------------------------------------------------------------------ */
1573U_CAPI decNumber * U_EXPORT2 uprv_decNumberMaxMag(decNumber *res, const decNumber *lhs,
1574                         const decNumber *rhs, decContext *set) {
1575  uInt status=0;                        /* accumulator  */
1576  decCompareOp(res, lhs, rhs, set, COMPMAXMAG, &status);
1577  if (status!=0) decStatus(res, status, set);
1578  #if DECCHECK
1579  decCheckInexact(res, set);
1580  #endif
1581  return res;
1582  } /* decNumberMaxMag  */
1583
1584/* ------------------------------------------------------------------ */
1585/* decNumberMin -- compare two Numbers and return the minimum         */
1586/*                                                                    */
1587/*   This computes C = A ? B, returning the minimum by 754 rules      */
1588/*                                                                    */
1589/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1590/*   lhs is A                                                         */
1591/*   rhs is B                                                         */
1592/*   set is the context                                               */
1593/*                                                                    */
1594/* C must have space for set->digits digits.                          */
1595/* ------------------------------------------------------------------ */
1596U_CAPI decNumber * U_EXPORT2 uprv_decNumberMin(decNumber *res, const decNumber *lhs,
1597                         const decNumber *rhs, decContext *set) {
1598  uInt status=0;                        /* accumulator  */
1599  decCompareOp(res, lhs, rhs, set, COMPMIN, &status);
1600  if (status!=0) decStatus(res, status, set);
1601  #if DECCHECK
1602  decCheckInexact(res, set);
1603  #endif
1604  return res;
1605  } /* decNumberMin  */
1606
1607/* ------------------------------------------------------------------ */
1608/* decNumberMinMag -- compare and return the minimum by magnitude     */
1609/*                                                                    */
1610/*   This computes C = A ? B, returning the minimum by 754 rules      */
1611/*                                                                    */
1612/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
1613/*   lhs is A                                                         */
1614/*   rhs is B                                                         */
1615/*   set is the context                                               */
1616/*                                                                    */
1617/* C must have space for set->digits digits.                          */
1618/* ------------------------------------------------------------------ */
1619U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinMag(decNumber *res, const decNumber *lhs,
1620                         const decNumber *rhs, decContext *set) {
1621  uInt status=0;                        /* accumulator  */
1622  decCompareOp(res, lhs, rhs, set, COMPMINMAG, &status);
1623  if (status!=0) decStatus(res, status, set);
1624  #if DECCHECK
1625  decCheckInexact(res, set);
1626  #endif
1627  return res;
1628  } /* decNumberMinMag  */
1629
1630/* ------------------------------------------------------------------ */
1631/* decNumberMinus -- prefix minus operator                            */
1632/*                                                                    */
1633/*   This computes C = 0 - A                                          */
1634/*                                                                    */
1635/*   res is C, the result.  C may be A                                */
1636/*   rhs is A                                                         */
1637/*   set is the context                                               */
1638/*                                                                    */
1639/* See also decNumberCopyNegate for a quiet bitwise version of this.  */
1640/* C must have space for set->digits digits.                          */
1641/* ------------------------------------------------------------------ */
1642/* Simply use AddOp for the subtract, which will do the necessary.    */
1643/* ------------------------------------------------------------------ */
1644U_CAPI decNumber * U_EXPORT2 uprv_decNumberMinus(decNumber *res, const decNumber *rhs,
1645                           decContext *set) {
1646  decNumber dzero;
1647  uInt status=0;                        /* accumulator  */
1648
1649  #if DECCHECK
1650  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1651  #endif
1652
1653  uprv_decNumberZero(&dzero);                /* make 0  */
1654  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1655  decAddOp(res, &dzero, rhs, set, DECNEG, &status);
1656  if (status!=0) decStatus(res, status, set);
1657  #if DECCHECK
1658  decCheckInexact(res, set);
1659  #endif
1660  return res;
1661  } /* decNumberMinus  */
1662
1663/* ------------------------------------------------------------------ */
1664/* decNumberNextMinus -- next towards -Infinity                       */
1665/*                                                                    */
1666/*   This computes C = A - infinitesimal, rounded towards -Infinity   */
1667/*                                                                    */
1668/*   res is C, the result.  C may be A                                */
1669/*   rhs is A                                                         */
1670/*   set is the context                                               */
1671/*                                                                    */
1672/* This is a generalization of 754 NextDown.                          */
1673/* ------------------------------------------------------------------ */
1674U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextMinus(decNumber *res, const decNumber *rhs,
1675                               decContext *set) {
1676  decNumber dtiny;                           /* constant  */
1677  decContext workset=*set;                   /* work  */
1678  uInt status=0;                             /* accumulator  */
1679  #if DECCHECK
1680  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1681  #endif
1682
1683  /* +Infinity is the special case  */
1684  if ((rhs->bits&(DECINF|DECNEG))==DECINF) {
1685    decSetMaxValue(res, set);                /* is +ve  */
1686    /* there is no status to set  */
1687    return res;
1688    }
1689  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1690  dtiny.lsu[0]=1;                            /* make number that is ..  */
1691  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1692  workset.round=DEC_ROUND_FLOOR;
1693  decAddOp(res, rhs, &dtiny, &workset, DECNEG, &status);
1694  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1695  if (status!=0) decStatus(res, status, set);
1696  return res;
1697  } /* decNumberNextMinus  */
1698
1699/* ------------------------------------------------------------------ */
1700/* decNumberNextPlus -- next towards +Infinity                        */
1701/*                                                                    */
1702/*   This computes C = A + infinitesimal, rounded towards +Infinity   */
1703/*                                                                    */
1704/*   res is C, the result.  C may be A                                */
1705/*   rhs is A                                                         */
1706/*   set is the context                                               */
1707/*                                                                    */
1708/* This is a generalization of 754 NextUp.                            */
1709/* ------------------------------------------------------------------ */
1710U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextPlus(decNumber *res, const decNumber *rhs,
1711                              decContext *set) {
1712  decNumber dtiny;                           /* constant  */
1713  decContext workset=*set;                   /* work  */
1714  uInt status=0;                             /* accumulator  */
1715  #if DECCHECK
1716  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1717  #endif
1718
1719  /* -Infinity is the special case  */
1720  if ((rhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1721    decSetMaxValue(res, set);
1722    res->bits=DECNEG;                        /* negative  */
1723    /* there is no status to set  */
1724    return res;
1725    }
1726  uprv_decNumberZero(&dtiny);                     /* start with 0  */
1727  dtiny.lsu[0]=1;                            /* make number that is ..  */
1728  dtiny.exponent=DEC_MIN_EMIN-1;             /* .. smaller than tiniest  */
1729  workset.round=DEC_ROUND_CEILING;
1730  decAddOp(res, rhs, &dtiny, &workset, 0, &status);
1731  status&=DEC_Invalid_operation|DEC_sNaN;    /* only sNaN Invalid please  */
1732  if (status!=0) decStatus(res, status, set);
1733  return res;
1734  } /* decNumberNextPlus  */
1735
1736/* ------------------------------------------------------------------ */
1737/* decNumberNextToward -- next towards rhs                            */
1738/*                                                                    */
1739/*   This computes C = A +/- infinitesimal, rounded towards           */
1740/*   +/-Infinity in the direction of B, as per 754-1985 nextafter     */
1741/*   modified during revision but dropped from 754-2008.              */
1742/*                                                                    */
1743/*   res is C, the result.  C may be A or B.                          */
1744/*   lhs is A                                                         */
1745/*   rhs is B                                                         */
1746/*   set is the context                                               */
1747/*                                                                    */
1748/* This is a generalization of 754-1985 NextAfter.                    */
1749/* ------------------------------------------------------------------ */
1750U_CAPI decNumber * U_EXPORT2 uprv_decNumberNextToward(decNumber *res, const decNumber *lhs,
1751                                const decNumber *rhs, decContext *set) {
1752  decNumber dtiny;                           /* constant  */
1753  decContext workset=*set;                   /* work  */
1754  Int result;                                /* ..  */
1755  uInt status=0;                             /* accumulator  */
1756  #if DECCHECK
1757  if (decCheckOperands(res, lhs, rhs, set)) return res;
1758  #endif
1759
1760  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) {
1761    decNaNs(res, lhs, rhs, set, &status);
1762    }
1763   else { /* Is numeric, so no chance of sNaN Invalid, etc.  */
1764    result=decCompare(lhs, rhs, 0);     /* sign matters  */
1765    if (result==BADINT) status|=DEC_Insufficient_storage; /* rare  */
1766     else { /* valid compare  */
1767      if (result==0) uprv_decNumberCopySign(res, lhs, rhs); /* easy  */
1768       else { /* differ: need NextPlus or NextMinus  */
1769        uByte sub;                      /* add or subtract  */
1770        if (result<0) {                 /* lhs<rhs, do nextplus  */
1771          /* -Infinity is the special case  */
1772          if ((lhs->bits&(DECINF|DECNEG))==(DECINF|DECNEG)) {
1773            decSetMaxValue(res, set);
1774            res->bits=DECNEG;           /* negative  */
1775            return res;                 /* there is no status to set  */
1776            }
1777          workset.round=DEC_ROUND_CEILING;
1778          sub=0;                        /* add, please  */
1779          } /* plus  */
1780         else {                         /* lhs>rhs, do nextminus  */
1781          /* +Infinity is the special case  */
1782          if ((lhs->bits&(DECINF|DECNEG))==DECINF) {
1783            decSetMaxValue(res, set);
1784            return res;                 /* there is no status to set  */
1785            }
1786          workset.round=DEC_ROUND_FLOOR;
1787          sub=DECNEG;                   /* subtract, please  */
1788          } /* minus  */
1789        uprv_decNumberZero(&dtiny);          /* start with 0  */
1790        dtiny.lsu[0]=1;                 /* make number that is ..  */
1791        dtiny.exponent=DEC_MIN_EMIN-1;  /* .. smaller than tiniest  */
1792        decAddOp(res, lhs, &dtiny, &workset, sub, &status); /* + or -  */
1793        /* turn off exceptions if the result is a normal number  */
1794        /* (including Nmin), otherwise let all status through  */
1795        if (uprv_decNumberIsNormal(res, set)) status=0;
1796        } /* unequal  */
1797      } /* compare OK  */
1798    } /* numeric  */
1799  if (status!=0) decStatus(res, status, set);
1800  return res;
1801  } /* decNumberNextToward  */
1802
1803/* ------------------------------------------------------------------ */
1804/* decNumberOr -- OR two Numbers, digitwise                           */
1805/*                                                                    */
1806/*   This computes C = A | B                                          */
1807/*                                                                    */
1808/*   res is C, the result.  C may be A and/or B (e.g., X=X|X)         */
1809/*   lhs is A                                                         */
1810/*   rhs is B                                                         */
1811/*   set is the context (used for result length and error report)     */
1812/*                                                                    */
1813/* C must have space for set->digits digits.                          */
1814/*                                                                    */
1815/* Logical function restrictions apply (see above); a NaN is          */
1816/* returned with Invalid_operation if a restriction is violated.      */
1817/* ------------------------------------------------------------------ */
1818U_CAPI decNumber * U_EXPORT2 uprv_decNumberOr(decNumber *res, const decNumber *lhs,
1819                        const decNumber *rhs, decContext *set) {
1820  const Unit *ua, *ub;                  /* -> operands  */
1821  const Unit *msua, *msub;              /* -> operand msus  */
1822  Unit  *uc, *msuc;                     /* -> result and its msu  */
1823  Int   msudigs;                        /* digits in res msu  */
1824  #if DECCHECK
1825  if (decCheckOperands(res, lhs, rhs, set)) return res;
1826  #endif
1827
1828  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
1829   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
1830    decStatus(res, DEC_Invalid_operation, set);
1831    return res;
1832    }
1833  /* operands are valid  */
1834  ua=lhs->lsu;                          /* bottom-up  */
1835  ub=rhs->lsu;                          /* ..  */
1836  uc=res->lsu;                          /* ..  */
1837  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
1838  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
1839  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
1840  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
1841  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
1842    Unit a, b;                          /* extract units  */
1843    if (ua>msua) a=0;
1844     else a=*ua;
1845    if (ub>msub) b=0;
1846     else b=*ub;
1847    *uc=0;                              /* can now write back  */
1848    if (a|b) {                          /* maybe 1 bits to examine  */
1849      Int i, j;
1850      /* This loop could be unrolled and/or use BIN2BCD tables  */
1851      for (i=0; i<DECDPUN; i++) {
1852        if ((a|b)&1) *uc=*uc+(Unit)powers[i];     /* effect OR  */
1853        j=a%10;
1854        a=a/10;
1855        j|=b%10;
1856        b=b/10;
1857        if (j>1) {
1858          decStatus(res, DEC_Invalid_operation, set);
1859          return res;
1860          }
1861        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
1862        } /* each digit  */
1863      } /* non-zero  */
1864    } /* each unit  */
1865  /* [here uc-1 is the msu of the result]  */
1866  res->digits=decGetDigits(res->lsu, uc-res->lsu);
1867  res->exponent=0;                      /* integer  */
1868  res->bits=0;                          /* sign=0  */
1869  return res;  /* [no status to set]  */
1870  } /* decNumberOr  */
1871
1872/* ------------------------------------------------------------------ */
1873/* decNumberPlus -- prefix plus operator                              */
1874/*                                                                    */
1875/*   This computes C = 0 + A                                          */
1876/*                                                                    */
1877/*   res is C, the result.  C may be A                                */
1878/*   rhs is A                                                         */
1879/*   set is the context                                               */
1880/*                                                                    */
1881/* See also decNumberCopy for a quiet bitwise version of this.        */
1882/* C must have space for set->digits digits.                          */
1883/* ------------------------------------------------------------------ */
1884/* This simply uses AddOp; Add will take fast path after preparing A. */
1885/* Performance is a concern here, as this routine is often used to    */
1886/* check operands and apply rounding and overflow/underflow testing.  */
1887/* ------------------------------------------------------------------ */
1888U_CAPI decNumber * U_EXPORT2 uprv_decNumberPlus(decNumber *res, const decNumber *rhs,
1889                          decContext *set) {
1890  decNumber dzero;
1891  uInt status=0;                        /* accumulator  */
1892  #if DECCHECK
1893  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
1894  #endif
1895
1896  uprv_decNumberZero(&dzero);                /* make 0  */
1897  dzero.exponent=rhs->exponent;         /* [no coefficient expansion]  */
1898  decAddOp(res, &dzero, rhs, set, 0, &status);
1899  if (status!=0) decStatus(res, status, set);
1900  #if DECCHECK
1901  decCheckInexact(res, set);
1902  #endif
1903  return res;
1904  } /* decNumberPlus  */
1905
1906/* ------------------------------------------------------------------ */
1907/* decNumberMultiply -- multiply two Numbers                          */
1908/*                                                                    */
1909/*   This computes C = A x B                                          */
1910/*                                                                    */
1911/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
1912/*   lhs is A                                                         */
1913/*   rhs is B                                                         */
1914/*   set is the context                                               */
1915/*                                                                    */
1916/* C must have space for set->digits digits.                          */
1917/* ------------------------------------------------------------------ */
1918U_CAPI decNumber * U_EXPORT2 uprv_decNumberMultiply(decNumber *res, const decNumber *lhs,
1919                              const decNumber *rhs, decContext *set) {
1920  uInt status=0;                   /* accumulator  */
1921  decMultiplyOp(res, lhs, rhs, set, &status);
1922  if (status!=0) decStatus(res, status, set);
1923  #if DECCHECK
1924  decCheckInexact(res, set);
1925  #endif
1926  return res;
1927  } /* decNumberMultiply  */
1928
1929/* ------------------------------------------------------------------ */
1930/* decNumberPower -- raise a number to a power                        */
1931/*                                                                    */
1932/*   This computes C = A ** B                                         */
1933/*                                                                    */
1934/*   res is C, the result.  C may be A and/or B (e.g., X=X**X)        */
1935/*   lhs is A                                                         */
1936/*   rhs is B                                                         */
1937/*   set is the context                                               */
1938/*                                                                    */
1939/* C must have space for set->digits digits.                          */
1940/*                                                                    */
1941/* Mathematical function restrictions apply (see above); a NaN is     */
1942/* returned with Invalid_operation if a restriction is violated.      */
1943/*                                                                    */
1944/* However, if 1999999997<=B<=999999999 and B is an integer then the  */
1945/* restrictions on A and the context are relaxed to the usual bounds, */
1946/* for compatibility with the earlier (integer power only) version    */
1947/* of this function.                                                  */
1948/*                                                                    */
1949/* When B is an integer, the result may be exact, even if rounded.    */
1950/*                                                                    */
1951/* The final result is rounded according to the context; it will      */
1952/* almost always be correctly rounded, but may be up to 1 ulp in      */
1953/* error in rare cases.                                               */
1954/* ------------------------------------------------------------------ */
1955U_CAPI decNumber * U_EXPORT2 uprv_decNumberPower(decNumber *res, const decNumber *lhs,
1956                           const decNumber *rhs, decContext *set) {
1957  #if DECSUBSET
1958  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
1959  decNumber *allocrhs=NULL;        /* .., rhs  */
1960  #endif
1961  decNumber *allocdac=NULL;        /* -> allocated acc buffer, iff used  */
1962  decNumber *allocinv=NULL;        /* -> allocated 1/x buffer, iff used  */
1963  Int   reqdigits=set->digits;     /* requested DIGITS  */
1964  Int   n;                         /* rhs in binary  */
1965  Flag  rhsint=0;                  /* 1 if rhs is an integer  */
1966  Flag  useint=0;                  /* 1 if can use integer calculation  */
1967  Flag  isoddint=0;                /* 1 if rhs is an integer and odd  */
1968  Int   i;                         /* work  */
1969  #if DECSUBSET
1970  Int   dropped;                   /* ..  */
1971  #endif
1972  uInt  needbytes;                 /* buffer size needed  */
1973  Flag  seenbit;                   /* seen a bit while powering  */
1974  Int   residue=0;                 /* rounding residue  */
1975  uInt  status=0;                  /* accumulators  */
1976  uByte bits=0;                    /* result sign if errors  */
1977  decContext aset;                 /* working context  */
1978  decNumber dnOne;                 /* work value 1...  */
1979  /* local accumulator buffer [a decNumber, with digits+elength+1 digits]  */
1980  decNumber dacbuff[D2N(DECBUFFER+9)];
1981  decNumber *dac=dacbuff;          /* -> result accumulator  */
1982  /* same again for possible 1/lhs calculation  */
1983  decNumber invbuff[D2N(DECBUFFER+9)];
1984
1985  #if DECCHECK
1986  if (decCheckOperands(res, lhs, rhs, set)) return res;
1987  #endif
1988
1989  do {                             /* protect allocated storage  */
1990    #if DECSUBSET
1991    if (!set->extended) { /* reduce operands and set status, as needed  */
1992      if (lhs->digits>reqdigits) {
1993        alloclhs=decRoundOperand(lhs, set, &status);
1994        if (alloclhs==NULL) break;
1995        lhs=alloclhs;
1996        }
1997      if (rhs->digits>reqdigits) {
1998        allocrhs=decRoundOperand(rhs, set, &status);
1999        if (allocrhs==NULL) break;
2000        rhs=allocrhs;
2001        }
2002      }
2003    #endif
2004    /* [following code does not require input rounding]  */
2005
2006    /* handle NaNs and rhs Infinity (lhs infinity is harder)  */
2007    if (SPECIALARGS) {
2008      if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs)) { /* NaNs  */
2009        decNaNs(res, lhs, rhs, set, &status);
2010        break;}
2011      if (decNumberIsInfinite(rhs)) {   /* rhs Infinity  */
2012        Flag rhsneg=rhs->bits&DECNEG;   /* save rhs sign  */
2013        if (decNumberIsNegative(lhs)    /* lhs<0  */
2014         && !decNumberIsZero(lhs))      /* ..  */
2015          status|=DEC_Invalid_operation;
2016         else {                         /* lhs >=0  */
2017          uprv_decNumberZero(&dnOne);        /* set up 1  */
2018          dnOne.lsu[0]=1;
2019          uprv_decNumberCompare(dac, lhs, &dnOne, set); /* lhs ? 1  */
2020          uprv_decNumberZero(res);           /* prepare for 0/1/Infinity  */
2021          if (decNumberIsNegative(dac)) {    /* lhs<1  */
2022            if (rhsneg) res->bits|=DECINF;   /* +Infinity [else is +0]  */
2023            }
2024           else if (dac->lsu[0]==0) {        /* lhs=1  */
2025            /* 1**Infinity is inexact, so return fully-padded 1.0000  */
2026            Int shift=set->digits-1;
2027            *res->lsu=1;                     /* was 0, make int 1  */
2028            res->digits=decShiftToMost(res->lsu, 1, shift);
2029            res->exponent=-shift;            /* make 1.0000...  */
2030            status|=DEC_Inexact|DEC_Rounded; /* deemed inexact  */
2031            }
2032           else {                            /* lhs>1  */
2033            if (!rhsneg) res->bits|=DECINF;  /* +Infinity [else is +0]  */
2034            }
2035          } /* lhs>=0  */
2036        break;}
2037      /* [lhs infinity drops through]  */
2038      } /* specials  */
2039
2040    /* Original rhs may be an integer that fits and is in range  */
2041    n=decGetInt(rhs);
2042    if (n!=BADINT) {                    /* it is an integer  */
2043      rhsint=1;                         /* record the fact for 1**n  */
2044      isoddint=(Flag)n&1;               /* [works even if big]  */
2045      if (n!=BIGEVEN && n!=BIGODD)      /* can use integer path?  */
2046        useint=1;                       /* looks good  */
2047      }
2048
2049    if (decNumberIsNegative(lhs)        /* -x ..  */
2050      && isoddint) bits=DECNEG;         /* .. to an odd power  */
2051
2052    /* handle LHS infinity  */
2053    if (decNumberIsInfinite(lhs)) {     /* [NaNs already handled]  */
2054      uByte rbits=rhs->bits;            /* save  */
2055      uprv_decNumberZero(res);               /* prepare  */
2056      if (n==0) *res->lsu=1;            /* [-]Inf**0 => 1  */
2057       else {
2058        /* -Inf**nonint -> error  */
2059        if (!rhsint && decNumberIsNegative(lhs)) {
2060          status|=DEC_Invalid_operation;     /* -Inf**nonint is error  */
2061          break;}
2062        if (!(rbits & DECNEG)) bits|=DECINF; /* was not a **-n  */
2063        /* [otherwise will be 0 or -0]  */
2064        res->bits=bits;
2065        }
2066      break;}
2067
2068    /* similarly handle LHS zero  */
2069    if (decNumberIsZero(lhs)) {
2070      if (n==0) {                            /* 0**0 => Error  */
2071        #if DECSUBSET
2072        if (!set->extended) {                /* [unless subset]  */
2073          uprv_decNumberZero(res);
2074          *res->lsu=1;                       /* return 1  */
2075          break;}
2076        #endif
2077        status|=DEC_Invalid_operation;
2078        }
2079       else {                                /* 0**x  */
2080        uByte rbits=rhs->bits;               /* save  */
2081        if (rbits & DECNEG) {                /* was a 0**(-n)  */
2082          #if DECSUBSET
2083          if (!set->extended) {              /* [bad if subset]  */
2084            status|=DEC_Invalid_operation;
2085            break;}
2086          #endif
2087          bits|=DECINF;
2088          }
2089        uprv_decNumberZero(res);                  /* prepare  */
2090        /* [otherwise will be 0 or -0]  */
2091        res->bits=bits;
2092        }
2093      break;}
2094
2095    /* here both lhs and rhs are finite; rhs==0 is handled in the  */
2096    /* integer path.  Next handle the non-integer cases  */
2097    if (!useint) {                      /* non-integral rhs  */
2098      /* any -ve lhs is bad, as is either operand or context out of  */
2099      /* bounds  */
2100      if (decNumberIsNegative(lhs)) {
2101        status|=DEC_Invalid_operation;
2102        break;}
2103      if (decCheckMath(lhs, set, &status)
2104       || decCheckMath(rhs, set, &status)) break; /* variable status  */
2105
2106      uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* clean context  */
2107      aset.emax=DEC_MAX_MATH;           /* usual bounds  */
2108      aset.emin=-DEC_MAX_MATH;          /* ..  */
2109      aset.clamp=0;                     /* and no concrete format  */
2110
2111      /* calculate the result using exp(ln(lhs)*rhs), which can  */
2112      /* all be done into the accumulator, dac.  The precision needed  */
2113      /* is enough to contain the full information in the lhs (which  */
2114      /* is the total digits, including exponent), or the requested  */
2115      /* precision, if larger, + 4; 6 is used for the exponent  */
2116      /* maximum length, and this is also used when it is shorter  */
2117      /* than the requested digits as it greatly reduces the >0.5 ulp  */
2118      /* cases at little cost (because Ln doubles digits each  */
2119      /* iteration so a few extra digits rarely causes an extra  */
2120      /* iteration)  */
2121      aset.digits=MAXI(lhs->digits, set->digits)+6+4;
2122      } /* non-integer rhs  */
2123
2124     else { /* rhs is in-range integer  */
2125      if (n==0) {                       /* x**0 = 1  */
2126        /* (0**0 was handled above)  */
2127        uprv_decNumberZero(res);             /* result=1  */
2128        *res->lsu=1;                    /* ..  */
2129        break;}
2130      /* rhs is a non-zero integer  */
2131      if (n<0) n=-n;                    /* use abs(n)  */
2132
2133      aset=*set;                        /* clone the context  */
2134      aset.round=DEC_ROUND_HALF_EVEN;   /* internally use balanced  */
2135      /* calculate the working DIGITS  */
2136      aset.digits=reqdigits+(rhs->digits+rhs->exponent)+2;
2137      #if DECSUBSET
2138      if (!set->extended) aset.digits--;     /* use classic precision  */
2139      #endif
2140      /* it's an error if this is more than can be handled  */
2141      if (aset.digits>DECNUMMAXP) {status|=DEC_Invalid_operation; break;}
2142      } /* integer path  */
2143
2144    /* aset.digits is the count of digits for the accumulator needed  */
2145    /* if accumulator is too long for local storage, then allocate  */
2146    needbytes=sizeof(decNumber)+(D2U(aset.digits)-1)*sizeof(Unit);
2147    /* [needbytes also used below if 1/lhs needed]  */
2148    if (needbytes>sizeof(dacbuff)) {
2149      allocdac=(decNumber *)malloc(needbytes);
2150      if (allocdac==NULL) {   /* hopeless -- abandon  */
2151        status|=DEC_Insufficient_storage;
2152        break;}
2153      dac=allocdac;           /* use the allocated space  */
2154      }
2155    /* here, aset is set up and accumulator is ready for use  */
2156
2157    if (!useint) {                           /* non-integral rhs  */
2158      /* x ** y; special-case x=1 here as it will otherwise always  */
2159      /* reduce to integer 1; decLnOp has a fastpath which detects  */
2160      /* the case of x=1  */
2161      decLnOp(dac, lhs, &aset, &status);     /* dac=ln(lhs)  */
2162      /* [no error possible, as lhs 0 already handled]  */
2163      if (ISZERO(dac)) {                     /* x==1, 1.0, etc.  */
2164        /* need to return fully-padded 1.0000 etc., but rhsint->1  */
2165        *dac->lsu=1;                         /* was 0, make int 1  */
2166        if (!rhsint) {                       /* add padding  */
2167          Int shift=set->digits-1;
2168          dac->digits=decShiftToMost(dac->lsu, 1, shift);
2169          dac->exponent=-shift;              /* make 1.0000...  */
2170          status|=DEC_Inexact|DEC_Rounded;   /* deemed inexact  */
2171          }
2172        }
2173       else {
2174        decMultiplyOp(dac, dac, rhs, &aset, &status);  /* dac=dac*rhs  */
2175        decExpOp(dac, dac, &aset, &status);            /* dac=exp(dac)  */
2176        }
2177      /* and drop through for final rounding  */
2178      } /* non-integer rhs  */
2179
2180     else {                             /* carry on with integer  */
2181      uprv_decNumberZero(dac);               /* acc=1  */
2182      *dac->lsu=1;                      /* ..  */
2183
2184      /* if a negative power the constant 1 is needed, and if not subset  */
2185      /* invert the lhs now rather than inverting the result later  */
2186      if (decNumberIsNegative(rhs)) {   /* was a **-n [hence digits>0]  */
2187        decNumber *inv=invbuff;         /* asssume use fixed buffer  */
2188        uprv_decNumberCopy(&dnOne, dac);     /* dnOne=1;  [needed now or later]  */
2189        #if DECSUBSET
2190        if (set->extended) {            /* need to calculate 1/lhs  */
2191        #endif
2192          /* divide lhs into 1, putting result in dac [dac=1/dac]  */
2193          decDivideOp(dac, &dnOne, lhs, &aset, DIVIDE, &status);
2194          /* now locate or allocate space for the inverted lhs  */
2195          if (needbytes>sizeof(invbuff)) {
2196            allocinv=(decNumber *)malloc(needbytes);
2197            if (allocinv==NULL) {       /* hopeless -- abandon  */
2198              status|=DEC_Insufficient_storage;
2199              break;}
2200            inv=allocinv;               /* use the allocated space  */
2201            }
2202          /* [inv now points to big-enough buffer or allocated storage]  */
2203          uprv_decNumberCopy(inv, dac);      /* copy the 1/lhs  */
2204          uprv_decNumberCopy(dac, &dnOne);   /* restore acc=1  */
2205          lhs=inv;                      /* .. and go forward with new lhs  */
2206        #if DECSUBSET
2207          }
2208        #endif
2209        }
2210
2211      /* Raise-to-the-power loop...  */
2212      seenbit=0;                   /* set once a 1-bit is encountered  */
2213      for (i=1;;i++){              /* for each bit [top bit ignored]  */
2214        /* abandon if had overflow or terminal underflow  */
2215        if (status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
2216          if (status&DEC_Overflow || ISZERO(dac)) break;
2217          }
2218        /* [the following two lines revealed an optimizer bug in a C++  */
2219        /* compiler, with symptom: 5**3 -> 25, when n=n+n was used]  */
2220        n=n<<1;                    /* move next bit to testable position  */
2221        if (n<0) {                 /* top bit is set  */
2222          seenbit=1;               /* OK, significant bit seen  */
2223          decMultiplyOp(dac, dac, lhs, &aset, &status); /* dac=dac*x  */
2224          }
2225        if (i==31) break;          /* that was the last bit  */
2226        if (!seenbit) continue;    /* no need to square 1  */
2227        decMultiplyOp(dac, dac, dac, &aset, &status); /* dac=dac*dac [square]  */
2228        } /*i*/ /* 32 bits  */
2229
2230      /* complete internal overflow or underflow processing  */
2231      if (status & (DEC_Overflow|DEC_Underflow)) {
2232        #if DECSUBSET
2233        /* If subset, and power was negative, reverse the kind of -erflow  */
2234        /* [1/x not yet done]  */
2235        if (!set->extended && decNumberIsNegative(rhs)) {
2236          if (status & DEC_Overflow)
2237            status^=DEC_Overflow | DEC_Underflow | DEC_Subnormal;
2238           else { /* trickier -- Underflow may or may not be set  */
2239            status&=~(DEC_Underflow | DEC_Subnormal); /* [one or both]  */
2240            status|=DEC_Overflow;
2241            }
2242          }
2243        #endif
2244        dac->bits=(dac->bits & ~DECNEG) | bits; /* force correct sign  */
2245        /* round subnormals [to set.digits rather than aset.digits]  */
2246        /* or set overflow result similarly as required  */
2247        decFinalize(dac, set, &residue, &status);
2248        uprv_decNumberCopy(res, dac);   /* copy to result (is now OK length)  */
2249        break;
2250        }
2251
2252      #if DECSUBSET
2253      if (!set->extended &&                  /* subset math  */
2254          decNumberIsNegative(rhs)) {        /* was a **-n [hence digits>0]  */
2255        /* so divide result into 1 [dac=1/dac]  */
2256        decDivideOp(dac, &dnOne, dac, &aset, DIVIDE, &status);
2257        }
2258      #endif
2259      } /* rhs integer path  */
2260
2261    /* reduce result to the requested length and copy to result  */
2262    decCopyFit(res, dac, set, &residue, &status);
2263    decFinish(res, set, &residue, &status);  /* final cleanup  */
2264    #if DECSUBSET
2265    if (!set->extended) decTrim(res, set, 0, 1, &dropped); /* trailing zeros  */
2266    #endif
2267    } while(0);                         /* end protected  */
2268
2269  if (allocdac!=NULL) free(allocdac);   /* drop any storage used  */
2270  if (allocinv!=NULL) free(allocinv);   /* ..  */
2271  #if DECSUBSET
2272  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
2273  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
2274  #endif
2275  if (status!=0) decStatus(res, status, set);
2276  #if DECCHECK
2277  decCheckInexact(res, set);
2278  #endif
2279  return res;
2280  } /* decNumberPower  */
2281
2282/* ------------------------------------------------------------------ */
2283/* decNumberQuantize -- force exponent to requested value             */
2284/*                                                                    */
2285/*   This computes C = op(A, B), where op adjusts the coefficient     */
2286/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2287/*   of C has exponent of B.  The numerical value of C will equal A,  */
2288/*   except for the effects of any rounding that occurred.            */
2289/*                                                                    */
2290/*   res is C, the result.  C may be A or B                           */
2291/*   lhs is A, the number to adjust                                   */
2292/*   rhs is B, the number with exponent to match                      */
2293/*   set is the context                                               */
2294/*                                                                    */
2295/* C must have space for set->digits digits.                          */
2296/*                                                                    */
2297/* Unless there is an error or the result is infinite, the exponent   */
2298/* after the operation is guaranteed to be equal to that of B.        */
2299/* ------------------------------------------------------------------ */
2300U_CAPI decNumber * U_EXPORT2 uprv_decNumberQuantize(decNumber *res, const decNumber *lhs,
2301                              const decNumber *rhs, decContext *set) {
2302  uInt status=0;                        /* accumulator  */
2303  decQuantizeOp(res, lhs, rhs, set, 1, &status);
2304  if (status!=0) decStatus(res, status, set);
2305  return res;
2306  } /* decNumberQuantize  */
2307
2308/* ------------------------------------------------------------------ */
2309/* decNumberReduce -- remove trailing zeros                           */
2310/*                                                                    */
2311/*   This computes C = 0 + A, and normalizes the result               */
2312/*                                                                    */
2313/*   res is C, the result.  C may be A                                */
2314/*   rhs is A                                                         */
2315/*   set is the context                                               */
2316/*                                                                    */
2317/* C must have space for set->digits digits.                          */
2318/* ------------------------------------------------------------------ */
2319/* Previously known as Normalize  */
2320U_CAPI decNumber * U_EXPORT2 uprv_decNumberNormalize(decNumber *res, const decNumber *rhs,
2321                               decContext *set) {
2322  return uprv_decNumberReduce(res, rhs, set);
2323  } /* decNumberNormalize  */
2324
2325U_CAPI decNumber * U_EXPORT2 uprv_decNumberReduce(decNumber *res, const decNumber *rhs,
2326                            decContext *set) {
2327  #if DECSUBSET
2328  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2329  #endif
2330  uInt status=0;                   /* as usual  */
2331  Int  residue=0;                  /* as usual  */
2332  Int  dropped;                    /* work  */
2333
2334  #if DECCHECK
2335  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2336  #endif
2337
2338  do {                             /* protect allocated storage  */
2339    #if DECSUBSET
2340    if (!set->extended) {
2341      /* reduce operand and set lostDigits status, as needed  */
2342      if (rhs->digits>set->digits) {
2343        allocrhs=decRoundOperand(rhs, set, &status);
2344        if (allocrhs==NULL) break;
2345        rhs=allocrhs;
2346        }
2347      }
2348    #endif
2349    /* [following code does not require input rounding]  */
2350
2351    /* Infinities copy through; NaNs need usual treatment  */
2352    if (decNumberIsNaN(rhs)) {
2353      decNaNs(res, rhs, NULL, set, &status);
2354      break;
2355      }
2356
2357    /* reduce result to the requested length and copy to result  */
2358    decCopyFit(res, rhs, set, &residue, &status); /* copy & round  */
2359    decFinish(res, set, &residue, &status);       /* cleanup/set flags  */
2360    decTrim(res, set, 1, 0, &dropped);            /* normalize in place  */
2361                                                  /* [may clamp]  */
2362    } while(0);                              /* end protected  */
2363
2364  #if DECSUBSET
2365  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
2366  #endif
2367  if (status!=0) decStatus(res, status, set);/* then report status  */
2368  return res;
2369  } /* decNumberReduce  */
2370
2371/* ------------------------------------------------------------------ */
2372/* decNumberRescale -- force exponent to requested value              */
2373/*                                                                    */
2374/*   This computes C = op(A, B), where op adjusts the coefficient     */
2375/*   of C (by rounding or shifting) such that the exponent (-scale)   */
2376/*   of C has the value B.  The numerical value of C will equal A,    */
2377/*   except for the effects of any rounding that occurred.            */
2378/*                                                                    */
2379/*   res is C, the result.  C may be A or B                           */
2380/*   lhs is A, the number to adjust                                   */
2381/*   rhs is B, the requested exponent                                 */
2382/*   set is the context                                               */
2383/*                                                                    */
2384/* C must have space for set->digits digits.                          */
2385/*                                                                    */
2386/* Unless there is an error or the result is infinite, the exponent   */
2387/* after the operation is guaranteed to be equal to B.                */
2388/* ------------------------------------------------------------------ */
2389U_CAPI decNumber * U_EXPORT2 uprv_decNumberRescale(decNumber *res, const decNumber *lhs,
2390                             const decNumber *rhs, decContext *set) {
2391  uInt status=0;                        /* accumulator  */
2392  decQuantizeOp(res, lhs, rhs, set, 0, &status);
2393  if (status!=0) decStatus(res, status, set);
2394  return res;
2395  } /* decNumberRescale  */
2396
2397/* ------------------------------------------------------------------ */
2398/* decNumberRemainder -- divide and return remainder                  */
2399/*                                                                    */
2400/*   This computes C = A % B                                          */
2401/*                                                                    */
2402/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2403/*   lhs is A                                                         */
2404/*   rhs is B                                                         */
2405/*   set is the context                                               */
2406/*                                                                    */
2407/* C must have space for set->digits digits.                          */
2408/* ------------------------------------------------------------------ */
2409U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainder(decNumber *res, const decNumber *lhs,
2410                               const decNumber *rhs, decContext *set) {
2411  uInt status=0;                        /* accumulator  */
2412  decDivideOp(res, lhs, rhs, set, REMAINDER, &status);
2413  if (status!=0) decStatus(res, status, set);
2414  #if DECCHECK
2415  decCheckInexact(res, set);
2416  #endif
2417  return res;
2418  } /* decNumberRemainder  */
2419
2420/* ------------------------------------------------------------------ */
2421/* decNumberRemainderNear -- divide and return remainder from nearest */
2422/*                                                                    */
2423/*   This computes C = A % B, where % is the IEEE remainder operator  */
2424/*                                                                    */
2425/*   res is C, the result.  C may be A and/or B (e.g., X=X%X)         */
2426/*   lhs is A                                                         */
2427/*   rhs is B                                                         */
2428/*   set is the context                                               */
2429/*                                                                    */
2430/* C must have space for set->digits digits.                          */
2431/* ------------------------------------------------------------------ */
2432U_CAPI decNumber * U_EXPORT2 uprv_decNumberRemainderNear(decNumber *res, const decNumber *lhs,
2433                                   const decNumber *rhs, decContext *set) {
2434  uInt status=0;                        /* accumulator  */
2435  decDivideOp(res, lhs, rhs, set, REMNEAR, &status);
2436  if (status!=0) decStatus(res, status, set);
2437  #if DECCHECK
2438  decCheckInexact(res, set);
2439  #endif
2440  return res;
2441  } /* decNumberRemainderNear  */
2442
2443/* ------------------------------------------------------------------ */
2444/* decNumberRotate -- rotate the coefficient of a Number left/right   */
2445/*                                                                    */
2446/*   This computes C = A rot B  (in base ten and rotating set->digits */
2447/*   digits).                                                         */
2448/*                                                                    */
2449/*   res is C, the result.  C may be A and/or B (e.g., X=XrotX)       */
2450/*   lhs is A                                                         */
2451/*   rhs is B, the number of digits to rotate (-ve to right)          */
2452/*   set is the context                                               */
2453/*                                                                    */
2454/* The digits of the coefficient of A are rotated to the left (if B   */
2455/* is positive) or to the right (if B is negative) without adjusting  */
2456/* the exponent or the sign of A.  If lhs->digits is less than        */
2457/* set->digits the coefficient is padded with zeros on the left       */
2458/* before the rotate.  Any leading zeros in the result are removed    */
2459/* as usual.                                                          */
2460/*                                                                    */
2461/* B must be an integer (q=0) and in the range -set->digits through   */
2462/* +set->digits.                                                      */
2463/* C must have space for set->digits digits.                          */
2464/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2465/* B must be valid).  No status is set unless B is invalid or an      */
2466/* operand is an sNaN.                                                */
2467/* ------------------------------------------------------------------ */
2468U_CAPI decNumber * U_EXPORT2 uprv_decNumberRotate(decNumber *res, const decNumber *lhs,
2469                           const decNumber *rhs, decContext *set) {
2470  uInt status=0;              /* accumulator  */
2471  Int  rotate;                /* rhs as an Int  */
2472
2473  #if DECCHECK
2474  if (decCheckOperands(res, lhs, rhs, set)) return res;
2475  #endif
2476
2477  /* NaNs propagate as normal  */
2478  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2479    decNaNs(res, lhs, rhs, set, &status);
2480   /* rhs must be an integer  */
2481   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2482    status=DEC_Invalid_operation;
2483   else { /* both numeric, rhs is an integer  */
2484    rotate=decGetInt(rhs);                   /* [cannot fail]  */
2485    if (rotate==BADINT                       /* something bad ..  */
2486     || rotate==BIGODD || rotate==BIGEVEN    /* .. very big ..  */
2487     || abs(rotate)>set->digits)             /* .. or out of range  */
2488      status=DEC_Invalid_operation;
2489     else {                                  /* rhs is OK  */
2490      uprv_decNumberCopy(res, lhs);
2491      /* convert -ve rotate to equivalent positive rotation  */
2492      if (rotate<0) rotate=set->digits+rotate;
2493      if (rotate!=0 && rotate!=set->digits   /* zero or full rotation  */
2494       && !decNumberIsInfinite(res)) {       /* lhs was infinite  */
2495        /* left-rotate to do; 0 < rotate < set->digits  */
2496        uInt units, shift;                   /* work  */
2497        uInt msudigits;                      /* digits in result msu  */
2498        Unit *msu=res->lsu+D2U(res->digits)-1;    /* current msu  */
2499        Unit *msumax=res->lsu+D2U(set->digits)-1; /* rotation msu  */
2500        for (msu++; msu<=msumax; msu++) *msu=0;   /* ensure high units=0  */
2501        res->digits=set->digits;                  /* now full-length  */
2502        msudigits=MSUDIGITS(res->digits);         /* actual digits in msu  */
2503
2504        /* rotation here is done in-place, in three steps  */
2505        /* 1. shift all to least up to one unit to unit-align final  */
2506        /*    lsd [any digits shifted out are rotated to the left,  */
2507        /*    abutted to the original msd (which may require split)]  */
2508        /*  */
2509        /*    [if there are no whole units left to rotate, the  */
2510        /*    rotation is now complete]  */
2511        /*  */
2512        /* 2. shift to least, from below the split point only, so that  */
2513        /*    the final msd is in the right place in its Unit [any  */
2514        /*    digits shifted out will fit exactly in the current msu,  */
2515        /*    left aligned, no split required]  */
2516        /*  */
2517        /* 3. rotate all the units by reversing left part, right  */
2518        /*    part, and then whole  */
2519        /*  */
2520        /* example: rotate right 8 digits (2 units + 2), DECDPUN=3.  */
2521        /*  */
2522        /*   start: 00a bcd efg hij klm npq  */
2523        /*  */
2524        /*      1a  000 0ab cde fgh|ijk lmn [pq saved]  */
2525        /*      1b  00p qab cde fgh|ijk lmn  */
2526        /*  */
2527        /*      2a  00p qab cde fgh|00i jkl [mn saved]  */
2528        /*      2b  mnp qab cde fgh|00i jkl  */
2529        /*  */
2530        /*      3a  fgh cde qab mnp|00i jkl  */
2531        /*      3b  fgh cde qab mnp|jkl 00i  */
2532        /*      3c  00i jkl mnp qab cde fgh  */
2533
2534        /* Step 1: amount to shift is the partial right-rotate count  */
2535        rotate=set->digits-rotate;      /* make it right-rotate  */
2536        units=rotate/DECDPUN;           /* whole units to rotate  */
2537        shift=rotate%DECDPUN;           /* left-over digits count  */
2538        if (shift>0) {                  /* not an exact number of units  */
2539          uInt save=res->lsu[0]%powers[shift];    /* save low digit(s)  */
2540          decShiftToLeast(res->lsu, D2U(res->digits), shift);
2541          if (shift>msudigits) {        /* msumax-1 needs >0 digits  */
2542            uInt rem=save%powers[shift-msudigits];/* split save  */
2543            *msumax=(Unit)(save/powers[shift-msudigits]); /* and insert  */
2544            *(msumax-1)=*(msumax-1)
2545                       +(Unit)(rem*powers[DECDPUN-(shift-msudigits)]); /* ..  */
2546            }
2547           else { /* all fits in msumax  */
2548            *msumax=*msumax+(Unit)(save*powers[msudigits-shift]); /* [maybe *1]  */
2549            }
2550          } /* digits shift needed  */
2551
2552        /* If whole units to rotate...  */
2553        if (units>0) {                  /* some to do  */
2554          /* Step 2: the units to touch are the whole ones in rotate,  */
2555          /*   if any, and the shift is DECDPUN-msudigits (which may be  */
2556          /*   0, again)  */
2557          shift=DECDPUN-msudigits;
2558          if (shift>0) {                /* not an exact number of units  */
2559            uInt save=res->lsu[0]%powers[shift];  /* save low digit(s)  */
2560            decShiftToLeast(res->lsu, units, shift);
2561            *msumax=*msumax+(Unit)(save*powers[msudigits]);
2562            } /* partial shift needed  */
2563
2564          /* Step 3: rotate the units array using triple reverse  */
2565          /* (reversing is easy and fast)  */
2566          decReverse(res->lsu+units, msumax);     /* left part  */
2567          decReverse(res->lsu, res->lsu+units-1); /* right part  */
2568          decReverse(res->lsu, msumax);           /* whole  */
2569          } /* whole units to rotate  */
2570        /* the rotation may have left an undetermined number of zeros  */
2571        /* on the left, so true length needs to be calculated  */
2572        res->digits=decGetDigits(res->lsu, msumax-res->lsu+1);
2573        } /* rotate needed  */
2574      } /* rhs OK  */
2575    } /* numerics  */
2576  if (status!=0) decStatus(res, status, set);
2577  return res;
2578  } /* decNumberRotate  */
2579
2580/* ------------------------------------------------------------------ */
2581/* decNumberSameQuantum -- test for equal exponents                   */
2582/*                                                                    */
2583/*   res is the result number, which will contain either 0 or 1       */
2584/*   lhs is a number to test                                          */
2585/*   rhs is the second (usually a pattern)                            */
2586/*                                                                    */
2587/* No errors are possible and no context is needed.                   */
2588/* ------------------------------------------------------------------ */
2589U_CAPI decNumber * U_EXPORT2 uprv_decNumberSameQuantum(decNumber *res, const decNumber *lhs,
2590                                 const decNumber *rhs) {
2591  Unit ret=0;                      /* return value  */
2592
2593  #if DECCHECK
2594  if (decCheckOperands(res, lhs, rhs, DECUNCONT)) return res;
2595  #endif
2596
2597  if (SPECIALARGS) {
2598    if (decNumberIsNaN(lhs) && decNumberIsNaN(rhs)) ret=1;
2599     else if (decNumberIsInfinite(lhs) && decNumberIsInfinite(rhs)) ret=1;
2600     /* [anything else with a special gives 0]  */
2601    }
2602   else if (lhs->exponent==rhs->exponent) ret=1;
2603
2604  uprv_decNumberZero(res);              /* OK to overwrite an operand now  */
2605  *res->lsu=ret;
2606  return res;
2607  } /* decNumberSameQuantum  */
2608
2609/* ------------------------------------------------------------------ */
2610/* decNumberScaleB -- multiply by a power of 10                       */
2611/*                                                                    */
2612/* This computes C = A x 10**B where B is an integer (q=0) with       */
2613/* maximum magnitude 2*(emax+digits)                                  */
2614/*                                                                    */
2615/*   res is C, the result.  C may be A or B                           */
2616/*   lhs is A, the number to adjust                                   */
2617/*   rhs is B, the requested power of ten to use                      */
2618/*   set is the context                                               */
2619/*                                                                    */
2620/* C must have space for set->digits digits.                          */
2621/*                                                                    */
2622/* The result may underflow or overflow.                              */
2623/* ------------------------------------------------------------------ */
2624U_CAPI decNumber * U_EXPORT2 uprv_decNumberScaleB(decNumber *res, const decNumber *lhs,
2625                            const decNumber *rhs, decContext *set) {
2626  Int  reqexp;                /* requested exponent change [B]  */
2627  uInt status=0;              /* accumulator  */
2628  Int  residue;               /* work  */
2629
2630  #if DECCHECK
2631  if (decCheckOperands(res, lhs, rhs, set)) return res;
2632  #endif
2633
2634  /* Handle special values except lhs infinite  */
2635  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2636    decNaNs(res, lhs, rhs, set, &status);
2637    /* rhs must be an integer  */
2638   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2639    status=DEC_Invalid_operation;
2640   else {
2641    /* lhs is a number; rhs is a finite with q==0  */
2642    reqexp=decGetInt(rhs);                   /* [cannot fail]  */
2643    if (reqexp==BADINT                       /* something bad ..  */
2644     || reqexp==BIGODD || reqexp==BIGEVEN    /* .. very big ..  */
2645     || abs(reqexp)>(2*(set->digits+set->emax))) /* .. or out of range  */
2646      status=DEC_Invalid_operation;
2647     else {                                  /* rhs is OK  */
2648      uprv_decNumberCopy(res, lhs);               /* all done if infinite lhs  */
2649      if (!decNumberIsInfinite(res)) {       /* prepare to scale  */
2650        res->exponent+=reqexp;               /* adjust the exponent  */
2651        residue=0;
2652        decFinalize(res, set, &residue, &status); /* .. and check  */
2653        } /* finite LHS  */
2654      } /* rhs OK  */
2655    } /* rhs finite  */
2656  if (status!=0) decStatus(res, status, set);
2657  return res;
2658  } /* decNumberScaleB  */
2659
2660/* ------------------------------------------------------------------ */
2661/* decNumberShift -- shift the coefficient of a Number left or right  */
2662/*                                                                    */
2663/*   This computes C = A << B or C = A >> -B  (in base ten).          */
2664/*                                                                    */
2665/*   res is C, the result.  C may be A and/or B (e.g., X=X<<X)        */
2666/*   lhs is A                                                         */
2667/*   rhs is B, the number of digits to shift (-ve to right)           */
2668/*   set is the context                                               */
2669/*                                                                    */
2670/* The digits of the coefficient of A are shifted to the left (if B   */
2671/* is positive) or to the right (if B is negative) without adjusting  */
2672/* the exponent or the sign of A.                                     */
2673/*                                                                    */
2674/* B must be an integer (q=0) and in the range -set->digits through   */
2675/* +set->digits.                                                      */
2676/* C must have space for set->digits digits.                          */
2677/* NaNs are propagated as usual.  Infinities are unaffected (but      */
2678/* B must be valid).  No status is set unless B is invalid or an      */
2679/* operand is an sNaN.                                                */
2680/* ------------------------------------------------------------------ */
2681U_CAPI decNumber * U_EXPORT2 uprv_decNumberShift(decNumber *res, const decNumber *lhs,
2682                           const decNumber *rhs, decContext *set) {
2683  uInt status=0;              /* accumulator  */
2684  Int  shift;                 /* rhs as an Int  */
2685
2686  #if DECCHECK
2687  if (decCheckOperands(res, lhs, rhs, set)) return res;
2688  #endif
2689
2690  /* NaNs propagate as normal  */
2691  if (decNumberIsNaN(lhs) || decNumberIsNaN(rhs))
2692    decNaNs(res, lhs, rhs, set, &status);
2693   /* rhs must be an integer  */
2694   else if (decNumberIsInfinite(rhs) || rhs->exponent!=0)
2695    status=DEC_Invalid_operation;
2696   else { /* both numeric, rhs is an integer  */
2697    shift=decGetInt(rhs);                    /* [cannot fail]  */
2698    if (shift==BADINT                        /* something bad ..  */
2699     || shift==BIGODD || shift==BIGEVEN      /* .. very big ..  */
2700     || abs(shift)>set->digits)              /* .. or out of range  */
2701      status=DEC_Invalid_operation;
2702     else {                                  /* rhs is OK  */
2703      uprv_decNumberCopy(res, lhs);
2704      if (shift!=0 && !decNumberIsInfinite(res)) { /* something to do  */
2705        if (shift>0) {                       /* to left  */
2706          if (shift==set->digits) {          /* removing all  */
2707            *res->lsu=0;                     /* so place 0  */
2708            res->digits=1;                   /* ..  */
2709            }
2710           else {                            /*  */
2711            /* first remove leading digits if necessary  */
2712            if (res->digits+shift>set->digits) {
2713              decDecap(res, res->digits+shift-set->digits);
2714              /* that updated res->digits; may have gone to 1 (for a  */
2715              /* single digit or for zero  */
2716              }
2717            if (res->digits>1 || *res->lsu)  /* if non-zero..  */
2718              res->digits=decShiftToMost(res->lsu, res->digits, shift);
2719            } /* partial left  */
2720          } /* left  */
2721         else { /* to right  */
2722          if (-shift>=res->digits) {         /* discarding all  */
2723            *res->lsu=0;                     /* so place 0  */
2724            res->digits=1;                   /* ..  */
2725            }
2726           else {
2727            decShiftToLeast(res->lsu, D2U(res->digits), -shift);
2728            res->digits-=(-shift);
2729            }
2730          } /* to right  */
2731        } /* non-0 non-Inf shift  */
2732      } /* rhs OK  */
2733    } /* numerics  */
2734  if (status!=0) decStatus(res, status, set);
2735  return res;
2736  } /* decNumberShift  */
2737
2738/* ------------------------------------------------------------------ */
2739/* decNumberSquareRoot -- square root operator                        */
2740/*                                                                    */
2741/*   This computes C = squareroot(A)                                  */
2742/*                                                                    */
2743/*   res is C, the result.  C may be A                                */
2744/*   rhs is A                                                         */
2745/*   set is the context; note that rounding mode has no effect        */
2746/*                                                                    */
2747/* C must have space for set->digits digits.                          */
2748/* ------------------------------------------------------------------ */
2749/* This uses the following varying-precision algorithm in:            */
2750/*                                                                    */
2751/*   Properly Rounded Variable Precision Square Root, T. E. Hull and  */
2752/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 11 #3, */
2753/*   pp229-237, ACM, September 1985.                                  */
2754/*                                                                    */
2755/* The square-root is calculated using Newton's method, after which   */
2756/* a check is made to ensure the result is correctly rounded.         */
2757/*                                                                    */
2758/* % [Reformatted original Numerical Turing source code follows.]     */
2759/* function sqrt(x : real) : real                                     */
2760/* % sqrt(x) returns the properly rounded approximation to the square */
2761/* % root of x, in the precision of the calling environment, or it    */
2762/* % fails if x < 0.                                                  */
2763/* % t e hull and a abrham, august, 1984                              */
2764/* if x <= 0 then                                                     */
2765/*   if x < 0 then                                                    */
2766/*     assert false                                                   */
2767/*   else                                                             */
2768/*     result 0                                                       */
2769/*   end if                                                           */
2770/* end if                                                             */
2771/* var f := setexp(x, 0)  % fraction part of x   [0.1 <= x < 1]       */
2772/* var e := getexp(x)     % exponent part of x                        */
2773/* var approx : real                                                  */
2774/* if e mod 2 = 0  then                                               */
2775/*   approx := .259 + .819 * f   % approx to root of f                */
2776/* else                                                               */
2777/*   f := f/l0                   % adjustments                        */
2778/*   e := e + 1                  %   for odd                          */
2779/*   approx := .0819 + 2.59 * f  %   exponent                         */
2780/* end if                                                             */
2781/*                                                                    */
2782/* var p:= 3                                                          */
2783/* const maxp := currentprecision + 2                                 */
2784/* loop                                                               */
2785/*   p := min(2*p - 2, maxp)     % p = 4,6,10, . . . , maxp           */
2786/*   precision p                                                      */
2787/*   approx := .5 * (approx + f/approx)                               */
2788/*   exit when p = maxp                                               */
2789/* end loop                                                           */
2790/*                                                                    */
2791/* % approx is now within 1 ulp of the properly rounded square root   */
2792/* % of f; to ensure proper rounding, compare squares of (approx -    */
2793/* % l/2 ulp) and (approx + l/2 ulp) with f.                          */
2794/* p := currentprecision                                              */
2795/* begin                                                              */
2796/*   precision p + 2                                                  */
2797/*   const approxsubhalf := approx - setexp(.5, -p)                   */
2798/*   if mulru(approxsubhalf, approxsubhalf) > f then                  */
2799/*     approx := approx - setexp(.l, -p + 1)                          */
2800/*   else                                                             */
2801/*     const approxaddhalf := approx + setexp(.5, -p)                 */
2802/*     if mulrd(approxaddhalf, approxaddhalf) < f then                */
2803/*       approx := approx + setexp(.l, -p + 1)                        */
2804/*     end if                                                         */
2805/*   end if                                                           */
2806/* end                                                                */
2807/* result setexp(approx, e div 2)  % fix exponent                     */
2808/* end sqrt                                                           */
2809/* ------------------------------------------------------------------ */
2810#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
2811#pragma GCC diagnostic push
2812#pragma GCC diagnostic ignored "-Warray-bounds"
2813#endif
2814U_CAPI decNumber * U_EXPORT2 uprv_decNumberSquareRoot(decNumber *res, const decNumber *rhs,
2815                                decContext *set) {
2816  decContext workset, approxset;   /* work contexts  */
2817  decNumber dzero;                 /* used for constant zero  */
2818  Int  maxp;                       /* largest working precision  */
2819  Int  workp;                      /* working precision  */
2820  Int  residue=0;                  /* rounding residue  */
2821  uInt status=0, ignore=0;         /* status accumulators  */
2822  uInt rstatus;                    /* ..  */
2823  Int  exp;                        /* working exponent  */
2824  Int  ideal;                      /* ideal (preferred) exponent  */
2825  Int  needbytes;                  /* work  */
2826  Int  dropped;                    /* ..  */
2827
2828  #if DECSUBSET
2829  decNumber *allocrhs=NULL;        /* non-NULL if rounded rhs allocated  */
2830  #endif
2831  /* buffer for f [needs +1 in case DECBUFFER 0]  */
2832  decNumber buff[D2N(DECBUFFER+1)];
2833  /* buffer for a [needs +2 to match likely maxp]  */
2834  decNumber bufa[D2N(DECBUFFER+2)];
2835  /* buffer for temporary, b [must be same size as a]  */
2836  decNumber bufb[D2N(DECBUFFER+2)];
2837  decNumber *allocbuff=NULL;       /* -> allocated buff, iff allocated  */
2838  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
2839  decNumber *allocbufb=NULL;       /* -> allocated bufb, iff allocated  */
2840  decNumber *f=buff;               /* reduced fraction  */
2841  decNumber *a=bufa;               /* approximation to result  */
2842  decNumber *b=bufb;               /* intermediate result  */
2843  /* buffer for temporary variable, up to 3 digits  */
2844  decNumber buft[D2N(3)];
2845  decNumber *t=buft;               /* up-to-3-digit constant or work  */
2846
2847  #if DECCHECK
2848  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
2849  #endif
2850
2851  do {                             /* protect allocated storage  */
2852    #if DECSUBSET
2853    if (!set->extended) {
2854      /* reduce operand and set lostDigits status, as needed  */
2855      if (rhs->digits>set->digits) {
2856        allocrhs=decRoundOperand(rhs, set, &status);
2857        if (allocrhs==NULL) break;
2858        /* [Note: 'f' allocation below could reuse this buffer if  */
2859        /* used, but as this is rare they are kept separate for clarity.]  */
2860        rhs=allocrhs;
2861        }
2862      }
2863    #endif
2864    /* [following code does not require input rounding]  */
2865
2866    /* handle infinities and NaNs  */
2867    if (SPECIALARG) {
2868      if (decNumberIsInfinite(rhs)) {         /* an infinity  */
2869        if (decNumberIsNegative(rhs)) status|=DEC_Invalid_operation;
2870         else uprv_decNumberCopy(res, rhs);        /* +Infinity  */
2871        }
2872       else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
2873      break;
2874      }
2875
2876    /* calculate the ideal (preferred) exponent [floor(exp/2)]  */
2877    /* [It would be nicer to write: ideal=rhs->exponent>>1, but this  */
2878    /* generates a compiler warning.  Generated code is the same.]  */
2879    ideal=(rhs->exponent&~1)/2;         /* target  */
2880
2881    /* handle zeros  */
2882    if (ISZERO(rhs)) {
2883      uprv_decNumberCopy(res, rhs);          /* could be 0 or -0  */
2884      res->exponent=ideal;              /* use the ideal [safe]  */
2885      /* use decFinish to clamp any out-of-range exponent, etc.  */
2886      decFinish(res, set, &residue, &status);
2887      break;
2888      }
2889
2890    /* any other -x is an oops  */
2891    if (decNumberIsNegative(rhs)) {
2892      status|=DEC_Invalid_operation;
2893      break;
2894      }
2895
2896    /* space is needed for three working variables  */
2897    /*   f -- the same precision as the RHS, reduced to 0.01->0.99...  */
2898    /*   a -- Hull's approximation -- precision, when assigned, is  */
2899    /*        currentprecision+1 or the input argument precision,  */
2900    /*        whichever is larger (+2 for use as temporary)  */
2901    /*   b -- intermediate temporary result (same size as a)  */
2902    /* if any is too long for local storage, then allocate  */
2903    workp=MAXI(set->digits+1, rhs->digits);  /* actual rounding precision  */
2904    workp=MAXI(workp, 7);                    /* at least 7 for low cases  */
2905    maxp=workp+2;                            /* largest working precision  */
2906
2907    needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
2908    if (needbytes>(Int)sizeof(buff)) {
2909      allocbuff=(decNumber *)malloc(needbytes);
2910      if (allocbuff==NULL) {  /* hopeless -- abandon  */
2911        status|=DEC_Insufficient_storage;
2912        break;}
2913      f=allocbuff;            /* use the allocated space  */
2914      }
2915    /* a and b both need to be able to hold a maxp-length number  */
2916    needbytes=sizeof(decNumber)+(D2U(maxp)-1)*sizeof(Unit);
2917    if (needbytes>(Int)sizeof(bufa)) {            /* [same applies to b]  */
2918      allocbufa=(decNumber *)malloc(needbytes);
2919      allocbufb=(decNumber *)malloc(needbytes);
2920      if (allocbufa==NULL || allocbufb==NULL) {   /* hopeless  */
2921        status|=DEC_Insufficient_storage;
2922        break;}
2923      a=allocbufa;            /* use the allocated spaces  */
2924      b=allocbufb;            /* ..  */
2925      }
2926
2927    /* copy rhs -> f, save exponent, and reduce so 0.1 <= f < 1  */
2928    uprv_decNumberCopy(f, rhs);
2929    exp=f->exponent+f->digits;               /* adjusted to Hull rules  */
2930    f->exponent=-(f->digits);                /* to range  */
2931
2932    /* set up working context  */
2933    uprv_decContextDefault(&workset, DEC_INIT_DECIMAL64);
2934    workset.emax=DEC_MAX_EMAX;
2935    workset.emin=DEC_MIN_EMIN;
2936
2937    /* [Until further notice, no error is possible and status bits  */
2938    /* (Rounded, etc.) should be ignored, not accumulated.]  */
2939
2940    /* Calculate initial approximation, and allow for odd exponent  */
2941    workset.digits=workp;                    /* p for initial calculation  */
2942    t->bits=0; t->digits=3;
2943    a->bits=0; a->digits=3;
2944    if ((exp & 1)==0) {                      /* even exponent  */
2945      /* Set t=0.259, a=0.819  */
2946      t->exponent=-3;
2947      a->exponent=-3;
2948      #if DECDPUN>=3
2949        t->lsu[0]=259;
2950        a->lsu[0]=819;
2951      #elif DECDPUN==2
2952        t->lsu[0]=59; t->lsu[1]=2;
2953        a->lsu[0]=19; a->lsu[1]=8;
2954      #else
2955        t->lsu[0]=9; t->lsu[1]=5; t->lsu[2]=2;
2956        a->lsu[0]=9; a->lsu[1]=1; a->lsu[2]=8;
2957      #endif
2958      }
2959     else {                                  /* odd exponent  */
2960      /* Set t=0.0819, a=2.59  */
2961      f->exponent--;                         /* f=f/10  */
2962      exp++;                                 /* e=e+1  */
2963      t->exponent=-4;
2964      a->exponent=-2;
2965      #if DECDPUN>=3
2966        t->lsu[0]=819;
2967        a->lsu[0]=259;
2968      #elif DECDPUN==2
2969        t->lsu[0]=19; t->lsu[1]=8;
2970        a->lsu[0]=59; a->lsu[1]=2;
2971      #else
2972        t->lsu[0]=9; t->lsu[1]=1; t->lsu[2]=8;
2973        a->lsu[0]=9; a->lsu[1]=5; a->lsu[2]=2;
2974      #endif
2975      }
2976
2977    decMultiplyOp(a, a, f, &workset, &ignore);    /* a=a*f  */
2978    decAddOp(a, a, t, &workset, 0, &ignore);      /* ..+t  */
2979    /* [a is now the initial approximation for sqrt(f), calculated with  */
2980    /* currentprecision, which is also a's precision.]  */
2981
2982    /* the main calculation loop  */
2983    uprv_decNumberZero(&dzero);                   /* make 0  */
2984    uprv_decNumberZero(t);                        /* set t = 0.5  */
2985    t->lsu[0]=5;                             /* ..  */
2986    t->exponent=-1;                          /* ..  */
2987    workset.digits=3;                        /* initial p  */
2988    for (; workset.digits<maxp;) {
2989      /* set p to min(2*p - 2, maxp)  [hence 3; or: 4, 6, 10, ... , maxp]  */
2990      workset.digits=MINI(workset.digits*2-2, maxp);
2991      /* a = 0.5 * (a + f/a)  */
2992      /* [calculated at p then rounded to currentprecision]  */
2993      decDivideOp(b, f, a, &workset, DIVIDE, &ignore); /* b=f/a  */
2994      decAddOp(b, b, a, &workset, 0, &ignore);         /* b=b+a  */
2995      decMultiplyOp(a, b, t, &workset, &ignore);       /* a=b*0.5  */
2996      } /* loop  */
2997
2998    /* Here, 0.1 <= a < 1 [Hull], and a has maxp digits  */
2999    /* now reduce to length, etc.; this needs to be done with a  */
3000    /* having the correct exponent so as to handle subnormals  */
3001    /* correctly  */
3002    approxset=*set;                          /* get emin, emax, etc.  */
3003    approxset.round=DEC_ROUND_HALF_EVEN;
3004    a->exponent+=exp/2;                      /* set correct exponent  */
3005    rstatus=0;                               /* clear status  */
3006    residue=0;                               /* .. and accumulator  */
3007    decCopyFit(a, a, &approxset, &residue, &rstatus);  /* reduce (if needed)  */
3008    decFinish(a, &approxset, &residue, &rstatus);      /* clean and finalize  */
3009
3010    /* Overflow was possible if the input exponent was out-of-range,  */
3011    /* in which case quit  */
3012    if (rstatus&DEC_Overflow) {
3013      status=rstatus;                        /* use the status as-is  */
3014      uprv_decNumberCopy(res, a);                 /* copy to result  */
3015      break;
3016      }
3017
3018    /* Preserve status except Inexact/Rounded  */
3019    status|=(rstatus & ~(DEC_Rounded|DEC_Inexact));
3020
3021    /* Carry out the Hull correction  */
3022    a->exponent-=exp/2;                      /* back to 0.1->1  */
3023
3024    /* a is now at final precision and within 1 ulp of the properly  */
3025    /* rounded square root of f; to ensure proper rounding, compare  */
3026    /* squares of (a - l/2 ulp) and (a + l/2 ulp) with f.  */
3027    /* Here workset.digits=maxp and t=0.5, and a->digits determines  */
3028    /* the ulp  */
3029    workset.digits--;                             /* maxp-1 is OK now  */
3030    t->exponent=-a->digits-1;                     /* make 0.5 ulp  */
3031    decAddOp(b, a, t, &workset, DECNEG, &ignore); /* b = a - 0.5 ulp  */
3032    workset.round=DEC_ROUND_UP;
3033    decMultiplyOp(b, b, b, &workset, &ignore);    /* b = mulru(b, b)  */
3034    decCompareOp(b, f, b, &workset, COMPARE, &ignore); /* b ? f, reversed  */
3035    if (decNumberIsNegative(b)) {                 /* f < b [i.e., b > f]  */
3036      /* this is the more common adjustment, though both are rare  */
3037      t->exponent++;                              /* make 1.0 ulp  */
3038      t->lsu[0]=1;                                /* ..  */
3039      decAddOp(a, a, t, &workset, DECNEG, &ignore); /* a = a - 1 ulp  */
3040      /* assign to approx [round to length]  */
3041      approxset.emin-=exp/2;                      /* adjust to match a  */
3042      approxset.emax-=exp/2;
3043      decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3044      }
3045     else {
3046      decAddOp(b, a, t, &workset, 0, &ignore);    /* b = a + 0.5 ulp  */
3047      workset.round=DEC_ROUND_DOWN;
3048      decMultiplyOp(b, b, b, &workset, &ignore);  /* b = mulrd(b, b)  */
3049      decCompareOp(b, b, f, &workset, COMPARE, &ignore);   /* b ? f  */
3050      if (decNumberIsNegative(b)) {               /* b < f  */
3051        t->exponent++;                            /* make 1.0 ulp  */
3052        t->lsu[0]=1;                              /* ..  */
3053        decAddOp(a, a, t, &workset, 0, &ignore);  /* a = a + 1 ulp  */
3054        /* assign to approx [round to length]  */
3055        approxset.emin-=exp/2;                    /* adjust to match a  */
3056        approxset.emax-=exp/2;
3057        decAddOp(a, &dzero, a, &approxset, 0, &ignore);
3058        }
3059      }
3060    /* [no errors are possible in the above, and rounding/inexact during  */
3061    /* estimation are irrelevant, so status was not accumulated]  */
3062
3063    /* Here, 0.1 <= a < 1  (still), so adjust back  */
3064    a->exponent+=exp/2;                      /* set correct exponent  */
3065
3066    /* count droppable zeros [after any subnormal rounding] by  */
3067    /* trimming a copy  */
3068    uprv_decNumberCopy(b, a);
3069    decTrim(b, set, 1, 1, &dropped);         /* [drops trailing zeros]  */
3070
3071    /* Set Inexact and Rounded.  The answer can only be exact if  */
3072    /* it is short enough so that squaring it could fit in workp  */
3073    /* digits, so this is the only (relatively rare) condition that  */
3074    /* a careful check is needed  */
3075    if (b->digits*2-1 > workp) {             /* cannot fit  */
3076      status|=DEC_Inexact|DEC_Rounded;
3077      }
3078     else {                                  /* could be exact/unrounded  */
3079      uInt mstatus=0;                        /* local status  */
3080      decMultiplyOp(b, b, b, &workset, &mstatus); /* try the multiply  */
3081      if (mstatus&DEC_Overflow) {            /* result just won't fit  */
3082        status|=DEC_Inexact|DEC_Rounded;
3083        }
3084       else {                                /* plausible  */
3085        decCompareOp(t, b, rhs, &workset, COMPARE, &mstatus); /* b ? rhs  */
3086        if (!ISZERO(t)) status|=DEC_Inexact|DEC_Rounded; /* not equal  */
3087         else {                              /* is Exact  */
3088          /* here, dropped is the count of trailing zeros in 'a'  */
3089          /* use closest exponent to ideal...  */
3090          Int todrop=ideal-a->exponent;      /* most that can be dropped  */
3091          if (todrop<0) status|=DEC_Rounded; /* ideally would add 0s  */
3092           else {                            /* unrounded  */
3093            /* there are some to drop, but emax may not allow all  */
3094            Int maxexp=set->emax-set->digits+1;
3095            Int maxdrop=maxexp-a->exponent;
3096            if (todrop>maxdrop && set->clamp) { /* apply clamping  */
3097              todrop=maxdrop;
3098              status|=DEC_Clamped;
3099              }
3100            if (dropped<todrop) {            /* clamp to those available  */
3101              todrop=dropped;
3102              status|=DEC_Clamped;
3103              }
3104            if (todrop>0) {                  /* have some to drop  */
3105              decShiftToLeast(a->lsu, D2U(a->digits), todrop);
3106              a->exponent+=todrop;           /* maintain numerical value  */
3107              a->digits-=todrop;             /* new length  */
3108              }
3109            }
3110          }
3111        }
3112      }
3113
3114    /* double-check Underflow, as perhaps the result could not have  */
3115    /* been subnormal (initial argument too big), or it is now Exact  */
3116    if (status&DEC_Underflow) {
3117      Int ae=rhs->exponent+rhs->digits-1;    /* adjusted exponent  */
3118      /* check if truly subnormal  */
3119      #if DECEXTFLAG                         /* DEC_Subnormal too  */
3120        if (ae>=set->emin*2) status&=~(DEC_Subnormal|DEC_Underflow);
3121      #else
3122        if (ae>=set->emin*2) status&=~DEC_Underflow;
3123      #endif
3124      /* check if truly inexact  */
3125      if (!(status&DEC_Inexact)) status&=~DEC_Underflow;
3126      }
3127
3128    uprv_decNumberCopy(res, a);                   /* a is now the result  */
3129    } while(0);                              /* end protected  */
3130
3131  if (allocbuff!=NULL) free(allocbuff);      /* drop any storage used  */
3132  if (allocbufa!=NULL) free(allocbufa);      /* ..  */
3133  if (allocbufb!=NULL) free(allocbufb);      /* ..  */
3134  #if DECSUBSET
3135  if (allocrhs !=NULL) free(allocrhs);       /* ..  */
3136  #endif
3137  if (status!=0) decStatus(res, status, set);/* then report status  */
3138  #if DECCHECK
3139  decCheckInexact(res, set);
3140  #endif
3141  return res;
3142  } /* decNumberSquareRoot  */
3143#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
3144#pragma GCC diagnostic pop
3145#endif
3146
3147/* ------------------------------------------------------------------ */
3148/* decNumberSubtract -- subtract two Numbers                          */
3149/*                                                                    */
3150/*   This computes C = A - B                                          */
3151/*                                                                    */
3152/*   res is C, the result.  C may be A and/or B (e.g., X=X-X)         */
3153/*   lhs is A                                                         */
3154/*   rhs is B                                                         */
3155/*   set is the context                                               */
3156/*                                                                    */
3157/* C must have space for set->digits digits.                          */
3158/* ------------------------------------------------------------------ */
3159U_CAPI decNumber * U_EXPORT2 uprv_decNumberSubtract(decNumber *res, const decNumber *lhs,
3160                              const decNumber *rhs, decContext *set) {
3161  uInt status=0;                        /* accumulator  */
3162
3163  decAddOp(res, lhs, rhs, set, DECNEG, &status);
3164  if (status!=0) decStatus(res, status, set);
3165  #if DECCHECK
3166  decCheckInexact(res, set);
3167  #endif
3168  return res;
3169  } /* decNumberSubtract  */
3170
3171/* ------------------------------------------------------------------ */
3172/* decNumberToIntegralExact -- round-to-integral-value with InExact   */
3173/* decNumberToIntegralValue -- round-to-integral-value                */
3174/*                                                                    */
3175/*   res is the result                                                */
3176/*   rhs is input number                                              */
3177/*   set is the context                                               */
3178/*                                                                    */
3179/* res must have space for any value of rhs.                          */
3180/*                                                                    */
3181/* This implements the IEEE special operators and therefore treats    */
3182/* special values as valid.  For finite numbers it returns            */
3183/* rescale(rhs, 0) if rhs->exponent is <0.                            */
3184/* Otherwise the result is rhs (so no error is possible, except for   */
3185/* sNaN).                                                             */
3186/*                                                                    */
3187/* The context is used for rounding mode and status after sNaN, but   */
3188/* the digits setting is ignored.  The Exact version will signal      */
3189/* Inexact if the result differs numerically from rhs; the other      */
3190/* never signals Inexact.                                             */
3191/* ------------------------------------------------------------------ */
3192U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralExact(decNumber *res, const decNumber *rhs,
3193                                     decContext *set) {
3194  decNumber dn;
3195  decContext workset;              /* working context  */
3196  uInt status=0;                   /* accumulator  */
3197
3198  #if DECCHECK
3199  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
3200  #endif
3201
3202  /* handle infinities and NaNs  */
3203  if (SPECIALARG) {
3204    if (decNumberIsInfinite(rhs)) uprv_decNumberCopy(res, rhs); /* an Infinity  */
3205     else decNaNs(res, rhs, NULL, set, &status); /* a NaN  */
3206    }
3207   else { /* finite  */
3208    /* have a finite number; no error possible (res must be big enough)  */
3209    if (rhs->exponent>=0) return uprv_decNumberCopy(res, rhs);
3210    /* that was easy, but if negative exponent there is work to do...  */
3211    workset=*set;                  /* clone rounding, etc.  */
3212    workset.digits=rhs->digits;    /* no length rounding  */
3213    workset.traps=0;               /* no traps  */
3214    uprv_decNumberZero(&dn);            /* make a number with exponent 0  */
3215    uprv_decNumberQuantize(res, rhs, &dn, &workset);
3216    status|=workset.status;
3217    }
3218  if (status!=0) decStatus(res, status, set);
3219  return res;
3220  } /* decNumberToIntegralExact  */
3221
3222U_CAPI decNumber * U_EXPORT2 uprv_decNumberToIntegralValue(decNumber *res, const decNumber *rhs,
3223                                     decContext *set) {
3224  decContext workset=*set;         /* working context  */
3225  workset.traps=0;                 /* no traps  */
3226  uprv_decNumberToIntegralExact(res, rhs, &workset);
3227  /* this never affects set, except for sNaNs; NaN will have been set  */
3228  /* or propagated already, so no need to call decStatus  */
3229  set->status|=workset.status&DEC_Invalid_operation;
3230  return res;
3231  } /* decNumberToIntegralValue  */
3232
3233/* ------------------------------------------------------------------ */
3234/* decNumberXor -- XOR two Numbers, digitwise                         */
3235/*                                                                    */
3236/*   This computes C = A ^ B                                          */
3237/*                                                                    */
3238/*   res is C, the result.  C may be A and/or B (e.g., X=X^X)         */
3239/*   lhs is A                                                         */
3240/*   rhs is B                                                         */
3241/*   set is the context (used for result length and error report)     */
3242/*                                                                    */
3243/* C must have space for set->digits digits.                          */
3244/*                                                                    */
3245/* Logical function restrictions apply (see above); a NaN is          */
3246/* returned with Invalid_operation if a restriction is violated.      */
3247/* ------------------------------------------------------------------ */
3248U_CAPI decNumber * U_EXPORT2 uprv_decNumberXor(decNumber *res, const decNumber *lhs,
3249                         const decNumber *rhs, decContext *set) {
3250  const Unit *ua, *ub;                  /* -> operands  */
3251  const Unit *msua, *msub;              /* -> operand msus  */
3252  Unit  *uc, *msuc;                     /* -> result and its msu  */
3253  Int   msudigs;                        /* digits in res msu  */
3254  #if DECCHECK
3255  if (decCheckOperands(res, lhs, rhs, set)) return res;
3256  #endif
3257
3258  if (lhs->exponent!=0 || decNumberIsSpecial(lhs) || decNumberIsNegative(lhs)
3259   || rhs->exponent!=0 || decNumberIsSpecial(rhs) || decNumberIsNegative(rhs)) {
3260    decStatus(res, DEC_Invalid_operation, set);
3261    return res;
3262    }
3263  /* operands are valid  */
3264  ua=lhs->lsu;                          /* bottom-up  */
3265  ub=rhs->lsu;                          /* ..  */
3266  uc=res->lsu;                          /* ..  */
3267  msua=ua+D2U(lhs->digits)-1;           /* -> msu of lhs  */
3268  msub=ub+D2U(rhs->digits)-1;           /* -> msu of rhs  */
3269  msuc=uc+D2U(set->digits)-1;           /* -> msu of result  */
3270  msudigs=MSUDIGITS(set->digits);       /* [faster than remainder]  */
3271  for (; uc<=msuc; ua++, ub++, uc++) {  /* Unit loop  */
3272    Unit a, b;                          /* extract units  */
3273    if (ua>msua) a=0;
3274     else a=*ua;
3275    if (ub>msub) b=0;
3276     else b=*ub;
3277    *uc=0;                              /* can now write back  */
3278    if (a|b) {                          /* maybe 1 bits to examine  */
3279      Int i, j;
3280      /* This loop could be unrolled and/or use BIN2BCD tables  */
3281      for (i=0; i<DECDPUN; i++) {
3282        if ((a^b)&1) *uc=*uc+(Unit)powers[i];     /* effect XOR  */
3283        j=a%10;
3284        a=a/10;
3285        j|=b%10;
3286        b=b/10;
3287        if (j>1) {
3288          decStatus(res, DEC_Invalid_operation, set);
3289          return res;
3290          }
3291        if (uc==msuc && i==msudigs-1) break;      /* just did final digit  */
3292        } /* each digit  */
3293      } /* non-zero  */
3294    } /* each unit  */
3295  /* [here uc-1 is the msu of the result]  */
3296  res->digits=decGetDigits(res->lsu, uc-res->lsu);
3297  res->exponent=0;                      /* integer  */
3298  res->bits=0;                          /* sign=0  */
3299  return res;  /* [no status to set]  */
3300  } /* decNumberXor  */
3301
3302
3303/* ================================================================== */
3304/* Utility routines                                                   */
3305/* ================================================================== */
3306
3307/* ------------------------------------------------------------------ */
3308/* decNumberClass -- return the decClass of a decNumber               */
3309/*   dn -- the decNumber to test                                      */
3310/*   set -- the context to use for Emin                               */
3311/*   returns the decClass enum                                        */
3312/* ------------------------------------------------------------------ */
3313enum decClass uprv_decNumberClass(const decNumber *dn, decContext *set) {
3314  if (decNumberIsSpecial(dn)) {
3315    if (decNumberIsQNaN(dn)) return DEC_CLASS_QNAN;
3316    if (decNumberIsSNaN(dn)) return DEC_CLASS_SNAN;
3317    /* must be an infinity  */
3318    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_INF;
3319    return DEC_CLASS_POS_INF;
3320    }
3321  /* is finite  */
3322  if (uprv_decNumberIsNormal(dn, set)) { /* most common  */
3323    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_NORMAL;
3324    return DEC_CLASS_POS_NORMAL;
3325    }
3326  /* is subnormal or zero  */
3327  if (decNumberIsZero(dn)) {    /* most common  */
3328    if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_ZERO;
3329    return DEC_CLASS_POS_ZERO;
3330    }
3331  if (decNumberIsNegative(dn)) return DEC_CLASS_NEG_SUBNORMAL;
3332  return DEC_CLASS_POS_SUBNORMAL;
3333  } /* decNumberClass  */
3334
3335/* ------------------------------------------------------------------ */
3336/* decNumberClassToString -- convert decClass to a string             */
3337/*                                                                    */
3338/*  eclass is a valid decClass                                        */
3339/*  returns a constant string describing the class (max 13+1 chars)   */
3340/* ------------------------------------------------------------------ */
3341const char *uprv_decNumberClassToString(enum decClass eclass) {
3342  if (eclass==DEC_CLASS_POS_NORMAL)    return DEC_ClassString_PN;
3343  if (eclass==DEC_CLASS_NEG_NORMAL)    return DEC_ClassString_NN;
3344  if (eclass==DEC_CLASS_POS_ZERO)      return DEC_ClassString_PZ;
3345  if (eclass==DEC_CLASS_NEG_ZERO)      return DEC_ClassString_NZ;
3346  if (eclass==DEC_CLASS_POS_SUBNORMAL) return DEC_ClassString_PS;
3347  if (eclass==DEC_CLASS_NEG_SUBNORMAL) return DEC_ClassString_NS;
3348  if (eclass==DEC_CLASS_POS_INF)       return DEC_ClassString_PI;
3349  if (eclass==DEC_CLASS_NEG_INF)       return DEC_ClassString_NI;
3350  if (eclass==DEC_CLASS_QNAN)          return DEC_ClassString_QN;
3351  if (eclass==DEC_CLASS_SNAN)          return DEC_ClassString_SN;
3352  return DEC_ClassString_UN;           /* Unknown  */
3353  } /* decNumberClassToString  */
3354
3355/* ------------------------------------------------------------------ */
3356/* decNumberCopy -- copy a number                                     */
3357/*                                                                    */
3358/*   dest is the target decNumber                                     */
3359/*   src  is the source decNumber                                     */
3360/*   returns dest                                                     */
3361/*                                                                    */
3362/* (dest==src is allowed and is a no-op)                              */
3363/* All fields are updated as required.  This is a utility operation,  */
3364/* so special values are unchanged and no error is possible.          */
3365/* ------------------------------------------------------------------ */
3366U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopy(decNumber *dest, const decNumber *src) {
3367
3368  #if DECCHECK
3369  if (src==NULL) return uprv_decNumberZero(dest);
3370  #endif
3371
3372  if (dest==src) return dest;                /* no copy required  */
3373
3374  /* Use explicit assignments here as structure assignment could copy  */
3375  /* more than just the lsu (for small DECDPUN).  This would not affect  */
3376  /* the value of the results, but could disturb test harness spill  */
3377  /* checking.  */
3378  dest->bits=src->bits;
3379  dest->exponent=src->exponent;
3380  dest->digits=src->digits;
3381  dest->lsu[0]=src->lsu[0];
3382  if (src->digits>DECDPUN) {                 /* more Units to come  */
3383    const Unit *smsup, *s;                   /* work  */
3384    Unit  *d;                                /* ..  */
3385    /* memcpy for the remaining Units would be safe as they cannot  */
3386    /* overlap.  However, this explicit loop is faster in short cases.  */
3387    d=dest->lsu+1;                           /* -> first destination  */
3388    smsup=src->lsu+D2U(src->digits);         /* -> source msu+1  */
3389    for (s=src->lsu+1; s<smsup; s++, d++) *d=*s;
3390    }
3391  return dest;
3392  } /* decNumberCopy  */
3393
3394/* ------------------------------------------------------------------ */
3395/* decNumberCopyAbs -- quiet absolute value operator                  */
3396/*                                                                    */
3397/*   This sets C = abs(A)                                             */
3398/*                                                                    */
3399/*   res is C, the result.  C may be A                                */
3400/*   rhs is A                                                         */
3401/*                                                                    */
3402/* C must have space for set->digits digits.                          */
3403/* No exception or error can occur; this is a quiet bitwise operation.*/
3404/* See also decNumberAbs for a checking version of this.              */
3405/* ------------------------------------------------------------------ */
3406U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyAbs(decNumber *res, const decNumber *rhs) {
3407  #if DECCHECK
3408  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3409  #endif
3410  uprv_decNumberCopy(res, rhs);
3411  res->bits&=~DECNEG;                   /* turn off sign  */
3412  return res;
3413  } /* decNumberCopyAbs  */
3414
3415/* ------------------------------------------------------------------ */
3416/* decNumberCopyNegate -- quiet negate value operator                 */
3417/*                                                                    */
3418/*   This sets C = negate(A)                                          */
3419/*                                                                    */
3420/*   res is C, the result.  C may be A                                */
3421/*   rhs is A                                                         */
3422/*                                                                    */
3423/* C must have space for set->digits digits.                          */
3424/* No exception or error can occur; this is a quiet bitwise operation.*/
3425/* See also decNumberMinus for a checking version of this.            */
3426/* ------------------------------------------------------------------ */
3427U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopyNegate(decNumber *res, const decNumber *rhs) {
3428  #if DECCHECK
3429  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3430  #endif
3431  uprv_decNumberCopy(res, rhs);
3432  res->bits^=DECNEG;                    /* invert the sign  */
3433  return res;
3434  } /* decNumberCopyNegate  */
3435
3436/* ------------------------------------------------------------------ */
3437/* decNumberCopySign -- quiet copy and set sign operator              */
3438/*                                                                    */
3439/*   This sets C = A with the sign of B                               */
3440/*                                                                    */
3441/*   res is C, the result.  C may be A                                */
3442/*   lhs is A                                                         */
3443/*   rhs is B                                                         */
3444/*                                                                    */
3445/* C must have space for set->digits digits.                          */
3446/* No exception or error can occur; this is a quiet bitwise operation.*/
3447/* ------------------------------------------------------------------ */
3448U_CAPI decNumber * U_EXPORT2 uprv_decNumberCopySign(decNumber *res, const decNumber *lhs,
3449                              const decNumber *rhs) {
3450  uByte sign;                           /* rhs sign  */
3451  #if DECCHECK
3452  if (decCheckOperands(res, DECUNUSED, rhs, DECUNCONT)) return res;
3453  #endif
3454  sign=rhs->bits & DECNEG;              /* save sign bit  */
3455  uprv_decNumberCopy(res, lhs);
3456  res->bits&=~DECNEG;                   /* clear the sign  */
3457  res->bits|=sign;                      /* set from rhs  */
3458  return res;
3459  } /* decNumberCopySign  */
3460
3461/* ------------------------------------------------------------------ */
3462/* decNumberGetBCD -- get the coefficient in BCD8                     */
3463/*   dn is the source decNumber                                       */
3464/*   bcd is the uInt array that will receive dn->digits BCD bytes,    */
3465/*     most-significant at offset 0                                   */
3466/*   returns bcd                                                      */
3467/*                                                                    */
3468/* bcd must have at least dn->digits bytes.  No error is possible; if */
3469/* dn is a NaN or Infinite, digits must be 1 and the coefficient 0.   */
3470/* ------------------------------------------------------------------ */
3471U_CAPI uByte * U_EXPORT2 uprv_decNumberGetBCD(const decNumber *dn, uByte *bcd) {
3472  uByte *ub=bcd+dn->digits-1;      /* -> lsd  */
3473  const Unit *up=dn->lsu;          /* Unit pointer, -> lsu  */
3474
3475  #if DECDPUN==1                   /* trivial simple copy  */
3476    for (; ub>=bcd; ub--, up++) *ub=*up;
3477  #else                            /* chopping needed  */
3478    uInt u=*up;                    /* work  */
3479    uInt cut=DECDPUN;              /* downcounter through unit  */
3480    for (; ub>=bcd; ub--) {
3481      *ub=(uByte)(u%10);           /* [*6554 trick inhibits, here]  */
3482      u=u/10;
3483      cut--;
3484      if (cut>0) continue;         /* more in this unit  */
3485      up++;
3486      u=*up;
3487      cut=DECDPUN;
3488      }
3489  #endif
3490  return bcd;
3491  } /* decNumberGetBCD  */
3492
3493/* ------------------------------------------------------------------ */
3494/* decNumberSetBCD -- set (replace) the coefficient from BCD8         */
3495/*   dn is the target decNumber                                       */
3496/*   bcd is the uInt array that will source n BCD bytes, most-        */
3497/*     significant at offset 0                                        */
3498/*   n is the number of digits in the source BCD array (bcd)          */
3499/*   returns dn                                                       */
3500/*                                                                    */
3501/* dn must have space for at least n digits.  No error is possible;   */
3502/* if dn is a NaN, or Infinite, or is to become a zero, n must be 1   */
3503/* and bcd[0] zero.                                                   */
3504/* ------------------------------------------------------------------ */
3505U_CAPI decNumber * U_EXPORT2 uprv_decNumberSetBCD(decNumber *dn, const uByte *bcd, uInt n) {
3506  Unit *up=dn->lsu+D2U(dn->digits)-1;   /* -> msu [target pointer]  */
3507  const uByte *ub=bcd;                  /* -> source msd  */
3508
3509  #if DECDPUN==1                        /* trivial simple copy  */
3510    for (; ub<bcd+n; ub++, up--) *up=*ub;
3511  #else                                 /* some assembly needed  */
3512    /* calculate how many digits in msu, and hence first cut  */
3513    Int cut=MSUDIGITS(n);               /* [faster than remainder]  */
3514    for (;up>=dn->lsu; up--) {          /* each Unit from msu  */
3515      *up=0;                            /* will take <=DECDPUN digits  */
3516      for (; cut>0; ub++, cut--) *up=X10(*up)+*ub;
3517      cut=DECDPUN;                      /* next Unit has all digits  */
3518      }
3519  #endif
3520  dn->digits=n;                         /* set digit count  */
3521  return dn;
3522  } /* decNumberSetBCD  */
3523
3524/* ------------------------------------------------------------------ */
3525/* decNumberIsNormal -- test normality of a decNumber                 */
3526/*   dn is the decNumber to test                                      */
3527/*   set is the context to use for Emin                               */
3528/*   returns 1 if |dn| is finite and >=Nmin, 0 otherwise              */
3529/* ------------------------------------------------------------------ */
3530Int uprv_decNumberIsNormal(const decNumber *dn, decContext *set) {
3531  Int ae;                               /* adjusted exponent  */
3532  #if DECCHECK
3533  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3534  #endif
3535
3536  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3537  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3538
3539  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3540  if (ae<set->emin) return 0;           /* is subnormal  */
3541  return 1;
3542  } /* decNumberIsNormal  */
3543
3544/* ------------------------------------------------------------------ */
3545/* decNumberIsSubnormal -- test subnormality of a decNumber           */
3546/*   dn is the decNumber to test                                      */
3547/*   set is the context to use for Emin                               */
3548/*   returns 1 if |dn| is finite, non-zero, and <Nmin, 0 otherwise    */
3549/* ------------------------------------------------------------------ */
3550Int uprv_decNumberIsSubnormal(const decNumber *dn, decContext *set) {
3551  Int ae;                               /* adjusted exponent  */
3552  #if DECCHECK
3553  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, set)) return 0;
3554  #endif
3555
3556  if (decNumberIsSpecial(dn)) return 0; /* not finite  */
3557  if (decNumberIsZero(dn)) return 0;    /* not non-zero  */
3558
3559  ae=dn->exponent+dn->digits-1;         /* adjusted exponent  */
3560  if (ae<set->emin) return 1;           /* is subnormal  */
3561  return 0;
3562  } /* decNumberIsSubnormal  */
3563
3564/* ------------------------------------------------------------------ */
3565/* decNumberTrim -- remove insignificant zeros                        */
3566/*                                                                    */
3567/*   dn is the number to trim                                         */
3568/*   returns dn                                                       */
3569/*                                                                    */
3570/* All fields are updated as required.  This is a utility operation,  */
3571/* so special values are unchanged and no error is possible.  The     */
3572/* zeros are removed unconditionally.                                 */
3573/* ------------------------------------------------------------------ */
3574U_CAPI decNumber * U_EXPORT2 uprv_decNumberTrim(decNumber *dn) {
3575  Int  dropped;                    /* work  */
3576  decContext set;                  /* ..  */
3577  #if DECCHECK
3578  if (decCheckOperands(DECUNRESU, DECUNUSED, dn, DECUNCONT)) return dn;
3579  #endif
3580  uprv_decContextDefault(&set, DEC_INIT_BASE);    /* clamp=0  */
3581  return decTrim(dn, &set, 0, 1, &dropped);
3582  } /* decNumberTrim  */
3583
3584/* ------------------------------------------------------------------ */
3585/* decNumberVersion -- return the name and version of this module     */
3586/*                                                                    */
3587/* No error is possible.                                              */
3588/* ------------------------------------------------------------------ */
3589const char * uprv_decNumberVersion(void) {
3590  return DECVERSION;
3591  } /* decNumberVersion  */
3592
3593/* ------------------------------------------------------------------ */
3594/* decNumberZero -- set a number to 0                                 */
3595/*                                                                    */
3596/*   dn is the number to set, with space for one digit                */
3597/*   returns dn                                                       */
3598/*                                                                    */
3599/* No error is possible.                                              */
3600/* ------------------------------------------------------------------ */
3601/* Memset is not used as it is much slower in some environments.  */
3602U_CAPI decNumber * U_EXPORT2 uprv_decNumberZero(decNumber *dn) {
3603
3604  #if DECCHECK
3605  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
3606  #endif
3607
3608  dn->bits=0;
3609  dn->exponent=0;
3610  dn->digits=1;
3611  dn->lsu[0]=0;
3612  return dn;
3613  } /* decNumberZero  */
3614
3615/* ================================================================== */
3616/* Local routines                                                     */
3617/* ================================================================== */
3618
3619/* ------------------------------------------------------------------ */
3620/* decToString -- lay out a number into a string                      */
3621/*                                                                    */
3622/*   dn     is the number to lay out                                  */
3623/*   string is where to lay out the number                            */
3624/*   eng    is 1 if Engineering, 0 if Scientific                      */
3625/*                                                                    */
3626/* string must be at least dn->digits+14 characters long              */
3627/* No error is possible.                                              */
3628/*                                                                    */
3629/* Note that this routine can generate a -0 or 0.000.  These are      */
3630/* never generated in subset to-number or arithmetic, but can occur   */
3631/* in non-subset arithmetic (e.g., -1*0 or 1.234-1.234).              */
3632/* ------------------------------------------------------------------ */
3633/* If DECCHECK is enabled the string "?" is returned if a number is  */
3634/* invalid.  */
3635static void decToString(const decNumber *dn, char *string, Flag eng) {
3636  Int exp=dn->exponent;       /* local copy  */
3637  Int e;                      /* E-part value  */
3638  Int pre;                    /* digits before the '.'  */
3639  Int cut;                    /* for counting digits in a Unit  */
3640  char *c=string;             /* work [output pointer]  */
3641  const Unit *up=dn->lsu+D2U(dn->digits)-1; /* -> msu [input pointer]  */
3642  uInt u, pow;                /* work  */
3643
3644  #if DECCHECK
3645  if (decCheckOperands(DECUNRESU, dn, DECUNUSED, DECUNCONT)) {
3646    strcpy(string, "?");
3647    return;}
3648  #endif
3649
3650  if (decNumberIsNegative(dn)) {   /* Negatives get a minus  */
3651    *c='-';
3652    c++;
3653    }
3654  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
3655    if (decNumberIsInfinite(dn)) {
3656      strcpy(c,   "Inf");
3657      strcpy(c+3, "inity");
3658      return;}
3659    /* a NaN  */
3660    if (dn->bits&DECSNAN) {        /* signalling NaN  */
3661      *c='s';
3662      c++;
3663      }
3664    strcpy(c, "NaN");
3665    c+=3;                          /* step past  */
3666    /* if not a clean non-zero coefficient, that's all there is in a  */
3667    /* NaN string  */
3668    if (exp!=0 || (*dn->lsu==0 && dn->digits==1)) return;
3669    /* [drop through to add integer]  */
3670    }
3671
3672  /* calculate how many digits in msu, and hence first cut  */
3673  cut=MSUDIGITS(dn->digits);       /* [faster than remainder]  */
3674  cut--;                           /* power of ten for digit  */
3675
3676  if (exp==0) {                    /* simple integer [common fastpath]  */
3677    for (;up>=dn->lsu; up--) {     /* each Unit from msu  */
3678      u=*up;                       /* contains DECDPUN digits to lay out  */
3679      for (; cut>=0; c++, cut--) TODIGIT(u, cut, c, pow);
3680      cut=DECDPUN-1;               /* next Unit has all digits  */
3681      }
3682    *c='\0';                       /* terminate the string  */
3683    return;}
3684
3685  /* non-0 exponent -- assume plain form */
3686  pre=dn->digits+exp;              /* digits before '.'  */
3687  e=0;                             /* no E  */
3688  if ((exp>0) || (pre<-5)) {       /* need exponential form  */
3689    e=exp+dn->digits-1;            /* calculate E value  */
3690    pre=1;                         /* assume one digit before '.'  */
3691    if (eng && (e!=0)) {           /* engineering: may need to adjust  */
3692      Int adj;                     /* adjustment  */
3693      /* The C remainder operator is undefined for negative numbers, so  */
3694      /* a positive remainder calculation must be used here  */
3695      if (e<0) {
3696        adj=(-e)%3;
3697        if (adj!=0) adj=3-adj;
3698        }
3699       else { /* e>0  */
3700        adj=e%3;
3701        }
3702      e=e-adj;
3703      /* if dealing with zero still produce an exponent which is a  */
3704      /* multiple of three, as expected, but there will only be the  */
3705      /* one zero before the E, still.  Otherwise note the padding.  */
3706      if (!ISZERO(dn)) pre+=adj;
3707       else {  /* is zero  */
3708        if (adj!=0) {              /* 0.00Esnn needed  */
3709          e=e+3;
3710          pre=-(2-adj);
3711          }
3712        } /* zero  */
3713      } /* eng  */
3714    } /* need exponent  */
3715
3716  /* lay out the digits of the coefficient, adding 0s and . as needed */
3717  u=*up;
3718  if (pre>0) {                     /* xxx.xxx or xx00 (engineering) form  */
3719    Int n=pre;
3720    for (; pre>0; pre--, c++, cut--) {
3721      if (cut<0) {                 /* need new Unit  */
3722        if (up==dn->lsu) break;    /* out of input digits (pre>digits)  */
3723        up--;
3724        cut=DECDPUN-1;
3725        u=*up;
3726        }
3727      TODIGIT(u, cut, c, pow);
3728      }
3729    if (n<dn->digits) {            /* more to come, after '.'  */
3730      *c='.'; c++;
3731      for (;; c++, cut--) {
3732        if (cut<0) {               /* need new Unit  */
3733          if (up==dn->lsu) break;  /* out of input digits  */
3734          up--;
3735          cut=DECDPUN-1;
3736          u=*up;
3737          }
3738        TODIGIT(u, cut, c, pow);
3739        }
3740      }
3741     else for (; pre>0; pre--, c++) *c='0'; /* 0 padding (for engineering) needed  */
3742    }
3743   else {                          /* 0.xxx or 0.000xxx form  */
3744    *c='0'; c++;
3745    *c='.'; c++;
3746    for (; pre<0; pre++, c++) *c='0';   /* add any 0's after '.'  */
3747    for (; ; c++, cut--) {
3748      if (cut<0) {                 /* need new Unit  */
3749        if (up==dn->lsu) break;    /* out of input digits  */
3750        up--;
3751        cut=DECDPUN-1;
3752        u=*up;
3753        }
3754      TODIGIT(u, cut, c, pow);
3755      }
3756    }
3757
3758  /* Finally add the E-part, if needed.  It will never be 0, has a
3759     base maximum and minimum of +999999999 through -999999999, but
3760     could range down to -1999999998 for anormal numbers */
3761  if (e!=0) {
3762    Flag had=0;               /* 1=had non-zero  */
3763    *c='E'; c++;
3764    *c='+'; c++;              /* assume positive  */
3765    u=e;                      /* ..  */
3766    if (e<0) {
3767      *(c-1)='-';             /* oops, need -  */
3768      u=-e;                   /* uInt, please  */
3769      }
3770    /* lay out the exponent [_itoa or equivalent is not ANSI C]  */
3771    for (cut=9; cut>=0; cut--) {
3772      TODIGIT(u, cut, c, pow);
3773      if (*c=='0' && !had) continue;    /* skip leading zeros  */
3774      had=1;                            /* had non-0  */
3775      c++;                              /* step for next  */
3776      } /* cut  */
3777    }
3778  *c='\0';          /* terminate the string (all paths)  */
3779  return;
3780  } /* decToString  */
3781
3782/* ------------------------------------------------------------------ */
3783/* decAddOp -- add/subtract operation                                 */
3784/*                                                                    */
3785/*   This computes C = A + B                                          */
3786/*                                                                    */
3787/*   res is C, the result.  C may be A and/or B (e.g., X=X+X)         */
3788/*   lhs is A                                                         */
3789/*   rhs is B                                                         */
3790/*   set is the context                                               */
3791/*   negate is DECNEG if rhs should be negated, or 0 otherwise        */
3792/*   status accumulates status for the caller                         */
3793/*                                                                    */
3794/* C must have space for set->digits digits.                          */
3795/* Inexact in status must be 0 for correct Exact zero sign in result  */
3796/* ------------------------------------------------------------------ */
3797/* If possible, the coefficient is calculated directly into C.        */
3798/* However, if:                                                       */
3799/*   -- a digits+1 calculation is needed because the numbers are      */
3800/*      unaligned and span more than set->digits digits               */
3801/*   -- a carry to digits+1 digits looks possible                     */
3802/*   -- C is the same as A or B, and the result would destructively   */
3803/*      overlap the A or B coefficient                                */
3804/* then the result must be calculated into a temporary buffer.  In    */
3805/* this case a local (stack) buffer is used if possible, and only if  */
3806/* too long for that does malloc become the final resort.             */
3807/*                                                                    */
3808/* Misalignment is handled as follows:                                */
3809/*   Apad: (AExp>BExp) Swap operands and proceed as for BExp>AExp.    */
3810/*   BPad: Apply the padding by a combination of shifting (whole      */
3811/*         units) and multiplication (part units).                    */
3812/*                                                                    */
3813/* Addition, especially x=x+1, is speed-critical.                     */
3814/* The static buffer is larger than might be expected to allow for    */
3815/* calls from higher-level funtions (notable exp).                    */
3816/* ------------------------------------------------------------------ */
3817static decNumber * decAddOp(decNumber *res, const decNumber *lhs,
3818                            const decNumber *rhs, decContext *set,
3819                            uByte negate, uInt *status) {
3820  #if DECSUBSET
3821  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
3822  decNumber *allocrhs=NULL;        /* .., rhs  */
3823  #endif
3824  Int   rhsshift;                  /* working shift (in Units)  */
3825  Int   maxdigits;                 /* longest logical length  */
3826  Int   mult;                      /* multiplier  */
3827  Int   residue;                   /* rounding accumulator  */
3828  uByte bits;                      /* result bits  */
3829  Flag  diffsign;                  /* non-0 if arguments have different sign  */
3830  Unit  *acc;                      /* accumulator for result  */
3831  Unit  accbuff[SD2U(DECBUFFER*2+20)]; /* local buffer [*2+20 reduces many  */
3832                                   /* allocations when called from  */
3833                                   /* other operations, notable exp]  */
3834  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
3835  Int   reqdigits=set->digits;     /* local copy; requested DIGITS  */
3836  Int   padding;                   /* work  */
3837
3838  #if DECCHECK
3839  if (decCheckOperands(res, lhs, rhs, set)) return res;
3840  #endif
3841
3842  do {                             /* protect allocated storage  */
3843    #if DECSUBSET
3844    if (!set->extended) {
3845      /* reduce operands and set lostDigits status, as needed  */
3846      if (lhs->digits>reqdigits) {
3847        alloclhs=decRoundOperand(lhs, set, status);
3848        if (alloclhs==NULL) break;
3849        lhs=alloclhs;
3850        }
3851      if (rhs->digits>reqdigits) {
3852        allocrhs=decRoundOperand(rhs, set, status);
3853        if (allocrhs==NULL) break;
3854        rhs=allocrhs;
3855        }
3856      }
3857    #endif
3858    /* [following code does not require input rounding]  */
3859
3860    /* note whether signs differ [used all paths]  */
3861    diffsign=(Flag)((lhs->bits^rhs->bits^negate)&DECNEG);
3862
3863    /* handle infinities and NaNs  */
3864    if (SPECIALARGS) {                  /* a special bit set  */
3865      if (SPECIALARGS & (DECSNAN | DECNAN))  /* a NaN  */
3866        decNaNs(res, lhs, rhs, set, status);
3867       else { /* one or two infinities  */
3868        if (decNumberIsInfinite(lhs)) { /* LHS is infinity  */
3869          /* two infinities with different signs is invalid  */
3870          if (decNumberIsInfinite(rhs) && diffsign) {
3871            *status|=DEC_Invalid_operation;
3872            break;
3873            }
3874          bits=lhs->bits & DECNEG;      /* get sign from LHS  */
3875          }
3876         else bits=(rhs->bits^negate) & DECNEG;/* RHS must be Infinity  */
3877        bits|=DECINF;
3878        uprv_decNumberZero(res);
3879        res->bits=bits;                 /* set +/- infinity  */
3880        } /* an infinity  */
3881      break;
3882      }
3883
3884    /* Quick exit for add 0s; return the non-0, modified as need be  */
3885    if (ISZERO(lhs)) {
3886      Int adjust;                       /* work  */
3887      Int lexp=lhs->exponent;           /* save in case LHS==RES  */
3888      bits=lhs->bits;                   /* ..  */
3889      residue=0;                        /* clear accumulator  */
3890      decCopyFit(res, rhs, set, &residue, status); /* copy (as needed)  */
3891      res->bits^=negate;                /* flip if rhs was negated  */
3892      #if DECSUBSET
3893      if (set->extended) {              /* exponents on zeros count  */
3894      #endif
3895        /* exponent will be the lower of the two  */
3896        adjust=lexp-res->exponent;      /* adjustment needed [if -ve]  */
3897        if (ISZERO(res)) {              /* both 0: special IEEE 754 rules  */
3898          if (adjust<0) res->exponent=lexp;  /* set exponent  */
3899          /* 0-0 gives +0 unless rounding to -infinity, and -0-0 gives -0  */
3900          if (diffsign) {
3901            if (set->round!=DEC_ROUND_FLOOR) res->bits=0;
3902             else res->bits=DECNEG;     /* preserve 0 sign  */
3903            }
3904          }
3905         else { /* non-0 res  */
3906          if (adjust<0) {     /* 0-padding needed  */
3907            if ((res->digits-adjust)>set->digits) {
3908              adjust=res->digits-set->digits;     /* to fit exactly  */
3909              *status|=DEC_Rounded;               /* [but exact]  */
3910              }
3911            res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3912            res->exponent+=adjust;                /* set the exponent.  */
3913            }
3914          } /* non-0 res  */
3915      #if DECSUBSET
3916        } /* extended  */
3917      #endif
3918      decFinish(res, set, &residue, status);      /* clean and finalize  */
3919      break;}
3920
3921    if (ISZERO(rhs)) {                  /* [lhs is non-zero]  */
3922      Int adjust;                       /* work  */
3923      Int rexp=rhs->exponent;           /* save in case RHS==RES  */
3924      bits=rhs->bits;                   /* be clean  */
3925      residue=0;                        /* clear accumulator  */
3926      decCopyFit(res, lhs, set, &residue, status); /* copy (as needed)  */
3927      #if DECSUBSET
3928      if (set->extended) {              /* exponents on zeros count  */
3929      #endif
3930        /* exponent will be the lower of the two  */
3931        /* [0-0 case handled above]  */
3932        adjust=rexp-res->exponent;      /* adjustment needed [if -ve]  */
3933        if (adjust<0) {     /* 0-padding needed  */
3934          if ((res->digits-adjust)>set->digits) {
3935            adjust=res->digits-set->digits;     /* to fit exactly  */
3936            *status|=DEC_Rounded;               /* [but exact]  */
3937            }
3938          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
3939          res->exponent+=adjust;                /* set the exponent.  */
3940          }
3941      #if DECSUBSET
3942        } /* extended  */
3943      #endif
3944      decFinish(res, set, &residue, status);      /* clean and finalize  */
3945      break;}
3946
3947    /* [NB: both fastpath and mainpath code below assume these cases  */
3948    /* (notably 0-0) have already been handled]  */
3949
3950    /* calculate the padding needed to align the operands  */
3951    padding=rhs->exponent-lhs->exponent;
3952
3953    /* Fastpath cases where the numbers are aligned and normal, the RHS  */
3954    /* is all in one unit, no operand rounding is needed, and no carry,  */
3955    /* lengthening, or borrow is needed  */
3956    if (padding==0
3957        && rhs->digits<=DECDPUN
3958        && rhs->exponent>=set->emin     /* [some normals drop through]  */
3959        && rhs->exponent<=set->emax-set->digits+1 /* [could clamp]  */
3960        && rhs->digits<=reqdigits
3961        && lhs->digits<=reqdigits) {
3962      Int partial=*lhs->lsu;
3963      if (!diffsign) {                  /* adding  */
3964        partial+=*rhs->lsu;
3965        if ((partial<=DECDPUNMAX)       /* result fits in unit  */
3966         && (lhs->digits>=DECDPUN ||    /* .. and no digits-count change  */
3967             partial<(Int)powers[lhs->digits])) { /* ..  */
3968          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3969          *res->lsu=(Unit)partial;      /* [copy could have overwritten RHS]  */
3970          break;
3971          }
3972        /* else drop out for careful add  */
3973        }
3974       else {                           /* signs differ  */
3975        partial-=*rhs->lsu;
3976        if (partial>0) { /* no borrow needed, and non-0 result  */
3977          if (res!=lhs) uprv_decNumberCopy(res, lhs);  /* not in place  */
3978          *res->lsu=(Unit)partial;
3979          /* this could have reduced digits [but result>0]  */
3980          res->digits=decGetDigits(res->lsu, D2U(res->digits));
3981          break;
3982          }
3983        /* else drop out for careful subtract  */
3984        }
3985      }
3986
3987    /* Now align (pad) the lhs or rhs so they can be added or  */
3988    /* subtracted, as necessary.  If one number is much larger than  */
3989    /* the other (that is, if in plain form there is a least one  */
3990    /* digit between the lowest digit of one and the highest of the  */
3991    /* other) padding with up to DIGITS-1 trailing zeros may be  */
3992    /* needed; then apply rounding (as exotic rounding modes may be  */
3993    /* affected by the residue).  */
3994    rhsshift=0;               /* rhs shift to left (padding) in Units  */
3995    bits=lhs->bits;           /* assume sign is that of LHS  */
3996    mult=1;                   /* likely multiplier  */
3997
3998    /* [if padding==0 the operands are aligned; no padding is needed]  */
3999    if (padding!=0) {
4000      /* some padding needed; always pad the RHS, as any required  */
4001      /* padding can then be effected by a simple combination of  */
4002      /* shifts and a multiply  */
4003      Flag swapped=0;
4004      if (padding<0) {                  /* LHS needs the padding  */
4005        const decNumber *t;
4006        padding=-padding;               /* will be +ve  */
4007        bits=(uByte)(rhs->bits^negate); /* assumed sign is now that of RHS  */
4008        t=lhs; lhs=rhs; rhs=t;
4009        swapped=1;
4010        }
4011
4012      /* If, after pad, rhs would be longer than lhs by digits+1 or  */
4013      /* more then lhs cannot affect the answer, except as a residue,  */
4014      /* so only need to pad up to a length of DIGITS+1.  */
4015      if (rhs->digits+padding > lhs->digits+reqdigits+1) {
4016        /* The RHS is sufficient  */
4017        /* for residue use the relative sign indication...  */
4018        Int shift=reqdigits-rhs->digits;     /* left shift needed  */
4019        residue=1;                           /* residue for rounding  */
4020        if (diffsign) residue=-residue;      /* signs differ  */
4021        /* copy, shortening if necessary  */
4022        decCopyFit(res, rhs, set, &residue, status);
4023        /* if it was already shorter, then need to pad with zeros  */
4024        if (shift>0) {
4025          res->digits=decShiftToMost(res->lsu, res->digits, shift);
4026          res->exponent-=shift;              /* adjust the exponent.  */
4027          }
4028        /* flip the result sign if unswapped and rhs was negated  */
4029        if (!swapped) res->bits^=negate;
4030        decFinish(res, set, &residue, status);    /* done  */
4031        break;}
4032
4033      /* LHS digits may affect result  */
4034      rhsshift=D2U(padding+1)-1;        /* this much by Unit shift ..  */
4035      mult=powers[padding-(rhsshift*DECDPUN)]; /* .. this by multiplication  */
4036      } /* padding needed  */
4037
4038    if (diffsign) mult=-mult;           /* signs differ  */
4039
4040    /* determine the longer operand  */
4041    maxdigits=rhs->digits+padding;      /* virtual length of RHS  */
4042    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4043
4044    /* Decide on the result buffer to use; if possible place directly  */
4045    /* into result.  */
4046    acc=res->lsu;                       /* assume add direct to result  */
4047    /* If destructive overlap, or the number is too long, or a carry or  */
4048    /* borrow to DIGITS+1 might be possible, a buffer must be used.  */
4049    /* [Might be worth more sophisticated tests when maxdigits==reqdigits]  */
4050    if ((maxdigits>=reqdigits)          /* is, or could be, too large  */
4051     || (res==rhs && rhsshift>0)) {     /* destructive overlap  */
4052      /* buffer needed, choose it; units for maxdigits digits will be  */
4053      /* needed, +1 Unit for carry or borrow  */
4054      Int need=D2U(maxdigits)+1;
4055      acc=accbuff;                      /* assume use local buffer  */
4056      if (need*sizeof(Unit)>sizeof(accbuff)) {
4057        /* printf("malloc add %ld %ld\n", need, sizeof(accbuff));  */
4058        allocacc=(Unit *)malloc(need*sizeof(Unit));
4059        if (allocacc==NULL) {           /* hopeless -- abandon  */
4060          *status|=DEC_Insufficient_storage;
4061          break;}
4062        acc=allocacc;
4063        }
4064      }
4065
4066    res->bits=(uByte)(bits&DECNEG);     /* it's now safe to overwrite..  */
4067    res->exponent=lhs->exponent;        /* .. operands (even if aliased)  */
4068
4069    #if DECTRACE
4070      decDumpAr('A', lhs->lsu, D2U(lhs->digits));
4071      decDumpAr('B', rhs->lsu, D2U(rhs->digits));
4072      printf("  :h: %ld %ld\n", rhsshift, mult);
4073    #endif
4074
4075    /* add [A+B*m] or subtract [A+B*(-m)]  */
4076    res->digits=decUnitAddSub(lhs->lsu, D2U(lhs->digits),
4077                              rhs->lsu, D2U(rhs->digits),
4078                              rhsshift, acc, mult)
4079               *DECDPUN;           /* [units -> digits]  */
4080    if (res->digits<0) {           /* borrowed...  */
4081      res->digits=-res->digits;
4082      res->bits^=DECNEG;           /* flip the sign  */
4083      }
4084    #if DECTRACE
4085      decDumpAr('+', acc, D2U(res->digits));
4086    #endif
4087
4088    /* If a buffer was used the result must be copied back, possibly  */
4089    /* shortening.  (If no buffer was used then the result must have  */
4090    /* fit, so can't need rounding and residue must be 0.)  */
4091    residue=0;                     /* clear accumulator  */
4092    if (acc!=res->lsu) {
4093      #if DECSUBSET
4094      if (set->extended) {         /* round from first significant digit  */
4095      #endif
4096        /* remove leading zeros that were added due to rounding up to  */
4097        /* integral Units -- before the test for rounding.  */
4098        if (res->digits>reqdigits)
4099          res->digits=decGetDigits(acc, D2U(res->digits));
4100        decSetCoeff(res, set, acc, res->digits, &residue, status);
4101      #if DECSUBSET
4102        }
4103       else { /* subset arithmetic rounds from original significant digit  */
4104        /* May have an underestimate.  This only occurs when both  */
4105        /* numbers fit in DECDPUN digits and are padding with a  */
4106        /* negative multiple (-10, -100...) and the top digit(s) become  */
4107        /* 0.  (This only matters when using X3.274 rules where the  */
4108        /* leading zero could be included in the rounding.)  */
4109        if (res->digits<maxdigits) {
4110          *(acc+D2U(res->digits))=0; /* ensure leading 0 is there  */
4111          res->digits=maxdigits;
4112          }
4113         else {
4114          /* remove leading zeros that added due to rounding up to  */
4115          /* integral Units (but only those in excess of the original  */
4116          /* maxdigits length, unless extended) before test for rounding.  */
4117          if (res->digits>reqdigits) {
4118            res->digits=decGetDigits(acc, D2U(res->digits));
4119            if (res->digits<maxdigits) res->digits=maxdigits;
4120            }
4121          }
4122        decSetCoeff(res, set, acc, res->digits, &residue, status);
4123        /* Now apply rounding if needed before removing leading zeros.  */
4124        /* This is safe because subnormals are not a possibility  */
4125        if (residue!=0) {
4126          decApplyRound(res, set, residue, status);
4127          residue=0;                 /* did what needed to be done  */
4128          }
4129        } /* subset  */
4130      #endif
4131      } /* used buffer  */
4132
4133    /* strip leading zeros [these were left on in case of subset subtract]  */
4134    res->digits=decGetDigits(res->lsu, D2U(res->digits));
4135
4136    /* apply checks and rounding  */
4137    decFinish(res, set, &residue, status);
4138
4139    /* "When the sum of two operands with opposite signs is exactly  */
4140    /* zero, the sign of that sum shall be '+' in all rounding modes  */
4141    /* except round toward -Infinity, in which mode that sign shall be  */
4142    /* '-'."  [Subset zeros also never have '-', set by decFinish.]  */
4143    if (ISZERO(res) && diffsign
4144     #if DECSUBSET
4145     && set->extended
4146     #endif
4147     && (*status&DEC_Inexact)==0) {
4148      if (set->round==DEC_ROUND_FLOOR) res->bits|=DECNEG;   /* sign -  */
4149                                  else res->bits&=~DECNEG;  /* sign +  */
4150      }
4151    } while(0);                              /* end protected  */
4152
4153  if (allocacc!=NULL) free(allocacc);        /* drop any storage used  */
4154  #if DECSUBSET
4155  if (allocrhs!=NULL) free(allocrhs);        /* ..  */
4156  if (alloclhs!=NULL) free(alloclhs);        /* ..  */
4157  #endif
4158  return res;
4159  } /* decAddOp  */
4160
4161/* ------------------------------------------------------------------ */
4162/* decDivideOp -- division operation                                  */
4163/*                                                                    */
4164/*  This routine performs the calculations for all four division      */
4165/*  operators (divide, divideInteger, remainder, remainderNear).      */
4166/*                                                                    */
4167/*  C=A op B                                                          */
4168/*                                                                    */
4169/*   res is C, the result.  C may be A and/or B (e.g., X=X/X)         */
4170/*   lhs is A                                                         */
4171/*   rhs is B                                                         */
4172/*   set is the context                                               */
4173/*   op  is DIVIDE, DIVIDEINT, REMAINDER, or REMNEAR respectively.    */
4174/*   status is the usual accumulator                                  */
4175/*                                                                    */
4176/* C must have space for set->digits digits.                          */
4177/*                                                                    */
4178/* ------------------------------------------------------------------ */
4179/*   The underlying algorithm of this routine is the same as in the   */
4180/*   1981 S/370 implementation, that is, non-restoring long division  */
4181/*   with bi-unit (rather than bi-digit) estimation for each unit     */
4182/*   multiplier.  In this pseudocode overview, complications for the  */
4183/*   Remainder operators and division residues for exact rounding are */
4184/*   omitted for clarity.                                             */
4185/*                                                                    */
4186/*     Prepare operands and handle special values                     */
4187/*     Test for x/0 and then 0/x                                      */
4188/*     Exp =Exp1 - Exp2                                               */
4189/*     Exp =Exp +len(var1) -len(var2)                                 */
4190/*     Sign=Sign1 * Sign2                                             */
4191/*     Pad accumulator (Var1) to double-length with 0's (pad1)        */
4192/*     Pad Var2 to same length as Var1                                */
4193/*     msu2pair/plus=1st 2 or 1 units of var2, +1 to allow for round  */
4194/*     have=0                                                         */
4195/*     Do until (have=digits+1 OR residue=0)                          */
4196/*       if exp<0 then if integer divide/residue then leave           */
4197/*       this_unit=0                                                  */
4198/*       Do forever                                                   */
4199/*          compare numbers                                           */
4200/*          if <0 then leave inner_loop                               */
4201/*          if =0 then (* quick exit without subtract *) do           */
4202/*             this_unit=this_unit+1; output this_unit                */
4203/*             leave outer_loop; end                                  */
4204/*          Compare lengths of numbers (mantissae):                   */
4205/*          If same then tops2=msu2pair -- {units 1&2 of var2}        */
4206/*                  else tops2=msu2plus -- {0, unit 1 of var2}        */
4207/*          tops1=first_unit_of_Var1*10**DECDPUN +second_unit_of_var1 */
4208/*          mult=tops1/tops2  -- Good and safe guess at divisor       */
4209/*          if mult=0 then mult=1                                     */
4210/*          this_unit=this_unit+mult                                  */
4211/*          subtract                                                  */
4212/*          end inner_loop                                            */
4213/*        if have\=0 | this_unit\=0 then do                           */
4214/*          output this_unit                                          */
4215/*          have=have+1; end                                          */
4216/*        var2=var2/10                                                */
4217/*        exp=exp-1                                                   */
4218/*        end outer_loop                                              */
4219/*     exp=exp+1   -- set the proper exponent                         */
4220/*     if have=0 then generate answer=0                               */
4221/*     Return (Result is defined by Var1)                             */
4222/*                                                                    */
4223/* ------------------------------------------------------------------ */
4224/* Two working buffers are needed during the division; one (digits+   */
4225/* 1) to accumulate the result, and the other (up to 2*digits+1) for  */
4226/* long subtractions.  These are acc and var1 respectively.           */
4227/* var1 is a copy of the lhs coefficient, var2 is the rhs coefficient.*/
4228/* The static buffers may be larger than might be expected to allow   */
4229/* for calls from higher-level funtions (notable exp).                */
4230/* ------------------------------------------------------------------ */
4231static decNumber * decDivideOp(decNumber *res,
4232                               const decNumber *lhs, const decNumber *rhs,
4233                               decContext *set, Flag op, uInt *status) {
4234  #if DECSUBSET
4235  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
4236  decNumber *allocrhs=NULL;        /* .., rhs  */
4237  #endif
4238  Unit  accbuff[SD2U(DECBUFFER+DECDPUN+10)]; /* local buffer  */
4239  Unit  *acc=accbuff;              /* -> accumulator array for result  */
4240  Unit  *allocacc=NULL;            /* -> allocated buffer, iff allocated  */
4241  Unit  *accnext;                  /* -> where next digit will go  */
4242  Int   acclength;                 /* length of acc needed [Units]  */
4243  Int   accunits;                  /* count of units accumulated  */
4244  Int   accdigits;                 /* count of digits accumulated  */
4245
4246  Unit  varbuff[SD2U(DECBUFFER*2+DECDPUN)];  /* buffer for var1  */
4247  Unit  *var1=varbuff;             /* -> var1 array for long subtraction  */
4248  Unit  *varalloc=NULL;            /* -> allocated buffer, iff used  */
4249  Unit  *msu1;                     /* -> msu of var1  */
4250
4251  const Unit *var2;                /* -> var2 array  */
4252  const Unit *msu2;                /* -> msu of var2  */
4253  Int   msu2plus;                  /* msu2 plus one [does not vary]  */
4254  eInt  msu2pair;                  /* msu2 pair plus one [does not vary]  */
4255
4256  Int   var1units, var2units;      /* actual lengths  */
4257  Int   var2ulen;                  /* logical length (units)  */
4258  Int   var1initpad=0;             /* var1 initial padding (digits)  */
4259  Int   maxdigits;                 /* longest LHS or required acc length  */
4260  Int   mult;                      /* multiplier for subtraction  */
4261  Unit  thisunit;                  /* current unit being accumulated  */
4262  Int   residue;                   /* for rounding  */
4263  Int   reqdigits=set->digits;     /* requested DIGITS  */
4264  Int   exponent;                  /* working exponent  */
4265  Int   maxexponent=0;             /* DIVIDE maximum exponent if unrounded  */
4266  uByte bits;                      /* working sign  */
4267  Unit  *target;                   /* work  */
4268  const Unit *source;              /* ..  */
4269  uInt  const *pow;                /* ..  */
4270  Int   shift, cut;                /* ..  */
4271  #if DECSUBSET
4272  Int   dropped;                   /* work  */
4273  #endif
4274
4275  #if DECCHECK
4276  if (decCheckOperands(res, lhs, rhs, set)) return res;
4277  #endif
4278
4279  do {                             /* protect allocated storage  */
4280    #if DECSUBSET
4281    if (!set->extended) {
4282      /* reduce operands and set lostDigits status, as needed  */
4283      if (lhs->digits>reqdigits) {
4284        alloclhs=decRoundOperand(lhs, set, status);
4285        if (alloclhs==NULL) break;
4286        lhs=alloclhs;
4287        }
4288      if (rhs->digits>reqdigits) {
4289        allocrhs=decRoundOperand(rhs, set, status);
4290        if (allocrhs==NULL) break;
4291        rhs=allocrhs;
4292        }
4293      }
4294    #endif
4295    /* [following code does not require input rounding]  */
4296
4297    bits=(lhs->bits^rhs->bits)&DECNEG;  /* assumed sign for divisions  */
4298
4299    /* handle infinities and NaNs  */
4300    if (SPECIALARGS) {                  /* a special bit set  */
4301      if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4302        decNaNs(res, lhs, rhs, set, status);
4303        break;
4304        }
4305      /* one or two infinities  */
4306      if (decNumberIsInfinite(lhs)) {   /* LHS (dividend) is infinite  */
4307        if (decNumberIsInfinite(rhs) || /* two infinities are invalid ..  */
4308            op & (REMAINDER | REMNEAR)) { /* as is remainder of infinity  */
4309          *status|=DEC_Invalid_operation;
4310          break;
4311          }
4312        /* [Note that infinity/0 raises no exceptions]  */
4313        uprv_decNumberZero(res);
4314        res->bits=bits|DECINF;          /* set +/- infinity  */
4315        break;
4316        }
4317       else {                           /* RHS (divisor) is infinite  */
4318        residue=0;
4319        if (op&(REMAINDER|REMNEAR)) {
4320          /* result is [finished clone of] lhs  */
4321          decCopyFit(res, lhs, set, &residue, status);
4322          }
4323         else {  /* a division  */
4324          uprv_decNumberZero(res);
4325          res->bits=bits;               /* set +/- zero  */
4326          /* for DIVIDEINT the exponent is always 0.  For DIVIDE, result  */
4327          /* is a 0 with infinitely negative exponent, clamped to minimum  */
4328          if (op&DIVIDE) {
4329            res->exponent=set->emin-set->digits+1;
4330            *status|=DEC_Clamped;
4331            }
4332          }
4333        decFinish(res, set, &residue, status);
4334        break;
4335        }
4336      }
4337
4338    /* handle 0 rhs (x/0)  */
4339    if (ISZERO(rhs)) {                  /* x/0 is always exceptional  */
4340      if (ISZERO(lhs)) {
4341        uprv_decNumberZero(res);             /* [after lhs test]  */
4342        *status|=DEC_Division_undefined;/* 0/0 will become NaN  */
4343        }
4344       else {
4345        uprv_decNumberZero(res);
4346        if (op&(REMAINDER|REMNEAR)) *status|=DEC_Invalid_operation;
4347         else {
4348          *status|=DEC_Division_by_zero; /* x/0  */
4349          res->bits=bits|DECINF;         /* .. is +/- Infinity  */
4350          }
4351        }
4352      break;}
4353
4354    /* handle 0 lhs (0/x)  */
4355    if (ISZERO(lhs)) {                  /* 0/x [x!=0]  */
4356      #if DECSUBSET
4357      if (!set->extended) uprv_decNumberZero(res);
4358       else {
4359      #endif
4360        if (op&DIVIDE) {
4361          residue=0;
4362          exponent=lhs->exponent-rhs->exponent; /* ideal exponent  */
4363          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4364          res->bits=bits;               /* sign as computed  */
4365          res->exponent=exponent;       /* exponent, too  */
4366          decFinalize(res, set, &residue, status);   /* check exponent  */
4367          }
4368         else if (op&DIVIDEINT) {
4369          uprv_decNumberZero(res);           /* integer 0  */
4370          res->bits=bits;               /* sign as computed  */
4371          }
4372         else {                         /* a remainder  */
4373          exponent=rhs->exponent;       /* [save in case overwrite]  */
4374          uprv_decNumberCopy(res, lhs);      /* [zeros always fit]  */
4375          if (exponent<res->exponent) res->exponent=exponent; /* use lower  */
4376          }
4377      #if DECSUBSET
4378        }
4379      #endif
4380      break;}
4381
4382    /* Precalculate exponent.  This starts off adjusted (and hence fits  */
4383    /* in 31 bits) and becomes the usual unadjusted exponent as the  */
4384    /* division proceeds.  The order of evaluation is important, here,  */
4385    /* to avoid wrap.  */
4386    exponent=(lhs->exponent+lhs->digits)-(rhs->exponent+rhs->digits);
4387
4388    /* If the working exponent is -ve, then some quick exits are  */
4389    /* possible because the quotient is known to be <1  */
4390    /* [for REMNEAR, it needs to be < -1, as -0.5 could need work]  */
4391    if (exponent<0 && !(op==DIVIDE)) {
4392      if (op&DIVIDEINT) {
4393        uprv_decNumberZero(res);                  /* integer part is 0  */
4394        #if DECSUBSET
4395        if (set->extended)
4396        #endif
4397          res->bits=bits;                    /* set +/- zero  */
4398        break;}
4399      /* fastpath remainders so long as the lhs has the smaller  */
4400      /* (or equal) exponent  */
4401      if (lhs->exponent<=rhs->exponent) {
4402        if (op&REMAINDER || exponent<-1) {
4403          /* It is REMAINDER or safe REMNEAR; result is [finished  */
4404          /* clone of] lhs  (r = x - 0*y)  */
4405          residue=0;
4406          decCopyFit(res, lhs, set, &residue, status);
4407          decFinish(res, set, &residue, status);
4408          break;
4409          }
4410        /* [unsafe REMNEAR drops through]  */
4411        }
4412      } /* fastpaths  */
4413
4414    /* Long (slow) division is needed; roll up the sleeves... */
4415
4416    /* The accumulator will hold the quotient of the division.  */
4417    /* If it needs to be too long for stack storage, then allocate.  */
4418    acclength=D2U(reqdigits+DECDPUN);   /* in Units  */
4419    if (acclength*sizeof(Unit)>sizeof(accbuff)) {
4420      /* printf("malloc dvacc %ld units\n", acclength);  */
4421      allocacc=(Unit *)malloc(acclength*sizeof(Unit));
4422      if (allocacc==NULL) {             /* hopeless -- abandon  */
4423        *status|=DEC_Insufficient_storage;
4424        break;}
4425      acc=allocacc;                     /* use the allocated space  */
4426      }
4427
4428    /* var1 is the padded LHS ready for subtractions.  */
4429    /* If it needs to be too long for stack storage, then allocate.  */
4430    /* The maximum units needed for var1 (long subtraction) is:  */
4431    /* Enough for  */
4432    /*     (rhs->digits+reqdigits-1) -- to allow full slide to right  */
4433    /* or  (lhs->digits)             -- to allow for long lhs  */
4434    /* whichever is larger  */
4435    /*   +1                -- for rounding of slide to right  */
4436    /*   +1                -- for leading 0s  */
4437    /*   +1                -- for pre-adjust if a remainder or DIVIDEINT  */
4438    /* [Note: unused units do not participate in decUnitAddSub data]  */
4439    maxdigits=rhs->digits+reqdigits-1;
4440    if (lhs->digits>maxdigits) maxdigits=lhs->digits;
4441    var1units=D2U(maxdigits)+2;
4442    /* allocate a guard unit above msu1 for REMAINDERNEAR  */
4443    if (!(op&DIVIDE)) var1units++;
4444    if ((var1units+1)*sizeof(Unit)>sizeof(varbuff)) {
4445      /* printf("malloc dvvar %ld units\n", var1units+1);  */
4446      varalloc=(Unit *)malloc((var1units+1)*sizeof(Unit));
4447      if (varalloc==NULL) {             /* hopeless -- abandon  */
4448        *status|=DEC_Insufficient_storage;
4449        break;}
4450      var1=varalloc;                    /* use the allocated space  */
4451      }
4452
4453    /* Extend the lhs and rhs to full long subtraction length.  The lhs  */
4454    /* is truly extended into the var1 buffer, with 0 padding, so a  */
4455    /* subtract in place is always possible.  The rhs (var2) has  */
4456    /* virtual padding (implemented by decUnitAddSub).  */
4457    /* One guard unit was allocated above msu1 for rem=rem+rem in  */
4458    /* REMAINDERNEAR.  */
4459    msu1=var1+var1units-1;              /* msu of var1  */
4460    source=lhs->lsu+D2U(lhs->digits)-1; /* msu of input array  */
4461    for (target=msu1; source>=lhs->lsu; source--, target--) *target=*source;
4462    for (; target>=var1; target--) *target=0;
4463
4464    /* rhs (var2) is left-aligned with var1 at the start  */
4465    var2ulen=var1units;                 /* rhs logical length (units)  */
4466    var2units=D2U(rhs->digits);         /* rhs actual length (units)  */
4467    var2=rhs->lsu;                      /* -> rhs array  */
4468    msu2=var2+var2units-1;              /* -> msu of var2 [never changes]  */
4469    /* now set up the variables which will be used for estimating the  */
4470    /* multiplication factor.  If these variables are not exact, add  */
4471    /* 1 to make sure that the multiplier is never overestimated.  */
4472    msu2plus=*msu2;                     /* it's value ..  */
4473    if (var2units>1) msu2plus++;        /* .. +1 if any more  */
4474    msu2pair=(eInt)*msu2*(DECDPUNMAX+1);/* top two pair ..  */
4475    if (var2units>1) {                  /* .. [else treat 2nd as 0]  */
4476      msu2pair+=*(msu2-1);              /* ..  */
4477      if (var2units>2) msu2pair++;      /* .. +1 if any more  */
4478      }
4479
4480    /* The calculation is working in units, which may have leading zeros,  */
4481    /* but the exponent was calculated on the assumption that they are  */
4482    /* both left-aligned.  Adjust the exponent to compensate: add the  */
4483    /* number of leading zeros in var1 msu and subtract those in var2 msu.  */
4484    /* [This is actually done by counting the digits and negating, as  */
4485    /* lead1=DECDPUN-digits1, and similarly for lead2.]  */
4486    for (pow=&powers[1]; *msu1>=*pow; pow++) exponent--;
4487    for (pow=&powers[1]; *msu2>=*pow; pow++) exponent++;
4488
4489    /* Now, if doing an integer divide or remainder, ensure that  */
4490    /* the result will be Unit-aligned.  To do this, shift the var1  */
4491    /* accumulator towards least if need be.  (It's much easier to  */
4492    /* do this now than to reassemble the residue afterwards, if  */
4493    /* doing a remainder.)  Also ensure the exponent is not negative.  */
4494    if (!(op&DIVIDE)) {
4495      Unit *u;                          /* work  */
4496      /* save the initial 'false' padding of var1, in digits  */
4497      var1initpad=(var1units-D2U(lhs->digits))*DECDPUN;
4498      /* Determine the shift to do.  */
4499      if (exponent<0) cut=-exponent;
4500       else cut=DECDPUN-exponent%DECDPUN;
4501      decShiftToLeast(var1, var1units, cut);
4502      exponent+=cut;                    /* maintain numerical value  */
4503      var1initpad-=cut;                 /* .. and reduce padding  */
4504      /* clean any most-significant units which were just emptied  */
4505      for (u=msu1; cut>=DECDPUN; cut-=DECDPUN, u--) *u=0;
4506      } /* align  */
4507     else { /* is DIVIDE  */
4508      maxexponent=lhs->exponent-rhs->exponent;    /* save  */
4509      /* optimization: if the first iteration will just produce 0,  */
4510      /* preadjust to skip it [valid for DIVIDE only]  */
4511      if (*msu1<*msu2) {
4512        var2ulen--;                     /* shift down  */
4513        exponent-=DECDPUN;              /* update the exponent  */
4514        }
4515      }
4516
4517    /* ---- start the long-division loops ------------------------------  */
4518    accunits=0;                         /* no units accumulated yet  */
4519    accdigits=0;                        /* .. or digits  */
4520    accnext=acc+acclength-1;            /* -> msu of acc [NB: allows digits+1]  */
4521    for (;;) {                          /* outer forever loop  */
4522      thisunit=0;                       /* current unit assumed 0  */
4523      /* find the next unit  */
4524      for (;;) {                        /* inner forever loop  */
4525        /* strip leading zero units [from either pre-adjust or from  */
4526        /* subtract last time around].  Leave at least one unit.  */
4527        for (; *msu1==0 && msu1>var1; msu1--) var1units--;
4528
4529        if (var1units<var2ulen) break;       /* var1 too low for subtract  */
4530        if (var1units==var2ulen) {           /* unit-by-unit compare needed  */
4531          /* compare the two numbers, from msu  */
4532          const Unit *pv1, *pv2;
4533          Unit v2;                           /* units to compare  */
4534          pv2=msu2;                          /* -> msu  */
4535          for (pv1=msu1; ; pv1--, pv2--) {
4536            /* v1=*pv1 -- always OK  */
4537            v2=0;                            /* assume in padding  */
4538            if (pv2>=var2) v2=*pv2;          /* in range  */
4539            if (*pv1!=v2) break;             /* no longer the same  */
4540            if (pv1==var1) break;            /* done; leave pv1 as is  */
4541            }
4542          /* here when all inspected or a difference seen  */
4543          if (*pv1<v2) break;                /* var1 too low to subtract  */
4544          if (*pv1==v2) {                    /* var1 == var2  */
4545            /* reach here if var1 and var2 are identical; subtraction  */
4546            /* would increase digit by one, and the residue will be 0 so  */
4547            /* the calculation is done; leave the loop with residue=0.  */
4548            thisunit++;                      /* as though subtracted  */
4549            *var1=0;                         /* set var1 to 0  */
4550            var1units=1;                     /* ..  */
4551            break;  /* from inner  */
4552            } /* var1 == var2  */
4553          /* *pv1>v2.  Prepare for real subtraction; the lengths are equal  */
4554          /* Estimate the multiplier (there's always a msu1-1)...  */
4555          /* Bring in two units of var2 to provide a good estimate.  */
4556          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2pair);
4557          } /* lengths the same  */
4558         else { /* var1units > var2ulen, so subtraction is safe  */
4559          /* The var2 msu is one unit towards the lsu of the var1 msu,  */
4560          /* so only one unit for var2 can be used.  */
4561          mult=(Int)(((eInt)*msu1*(DECDPUNMAX+1)+*(msu1-1))/msu2plus);
4562          }
4563        if (mult==0) mult=1;                 /* must always be at least 1  */
4564        /* subtraction needed; var1 is > var2  */
4565        thisunit=(Unit)(thisunit+mult);      /* accumulate  */
4566        /* subtract var1-var2, into var1; only the overlap needs  */
4567        /* processing, as this is an in-place calculation  */
4568        shift=var2ulen-var2units;
4569        #if DECTRACE
4570          decDumpAr('1', &var1[shift], var1units-shift);
4571          decDumpAr('2', var2, var2units);
4572          printf("m=%ld\n", -mult);
4573        #endif
4574        decUnitAddSub(&var1[shift], var1units-shift,
4575                      var2, var2units, 0,
4576                      &var1[shift], -mult);
4577        #if DECTRACE
4578          decDumpAr('#', &var1[shift], var1units-shift);
4579        #endif
4580        /* var1 now probably has leading zeros; these are removed at the  */
4581        /* top of the inner loop.  */
4582        } /* inner loop  */
4583
4584      /* The next unit has been calculated in full; unless it's a  */
4585      /* leading zero, add to acc  */
4586      if (accunits!=0 || thisunit!=0) {      /* is first or non-zero  */
4587        *accnext=thisunit;                   /* store in accumulator  */
4588        /* account exactly for the new digits  */
4589        if (accunits==0) {
4590          accdigits++;                       /* at least one  */
4591          for (pow=&powers[1]; thisunit>=*pow; pow++) accdigits++;
4592          }
4593         else accdigits+=DECDPUN;
4594        accunits++;                          /* update count  */
4595        accnext--;                           /* ready for next  */
4596        if (accdigits>reqdigits) break;      /* have enough digits  */
4597        }
4598
4599      /* if the residue is zero, the operation is done (unless divide  */
4600      /* or divideInteger and still not enough digits yet)  */
4601      if (*var1==0 && var1units==1) {        /* residue is 0  */
4602        if (op&(REMAINDER|REMNEAR)) break;
4603        if ((op&DIVIDE) && (exponent<=maxexponent)) break;
4604        /* [drop through if divideInteger]  */
4605        }
4606      /* also done enough if calculating remainder or integer  */
4607      /* divide and just did the last ('units') unit  */
4608      if (exponent==0 && !(op&DIVIDE)) break;
4609
4610      /* to get here, var1 is less than var2, so divide var2 by the per-  */
4611      /* Unit power of ten and go for the next digit  */
4612      var2ulen--;                            /* shift down  */
4613      exponent-=DECDPUN;                     /* update the exponent  */
4614      } /* outer loop  */
4615
4616    /* ---- division is complete ---------------------------------------  */
4617    /* here: acc      has at least reqdigits+1 of good results (or fewer  */
4618    /*                if early stop), starting at accnext+1 (its lsu)  */
4619    /*       var1     has any residue at the stopping point  */
4620    /*       accunits is the number of digits collected in acc  */
4621    if (accunits==0) {             /* acc is 0  */
4622      accunits=1;                  /* show have a unit ..  */
4623      accdigits=1;                 /* ..  */
4624      *accnext=0;                  /* .. whose value is 0  */
4625      }
4626     else accnext++;               /* back to last placed  */
4627    /* accnext now -> lowest unit of result  */
4628
4629    residue=0;                     /* assume no residue  */
4630    if (op&DIVIDE) {
4631      /* record the presence of any residue, for rounding  */
4632      if (*var1!=0 || var1units>1) residue=1;
4633       else { /* no residue  */
4634        /* Had an exact division; clean up spurious trailing 0s.  */
4635        /* There will be at most DECDPUN-1, from the final multiply,  */
4636        /* and then only if the result is non-0 (and even) and the  */
4637        /* exponent is 'loose'.  */
4638        #if DECDPUN>1
4639        Unit lsu=*accnext;
4640        if (!(lsu&0x01) && (lsu!=0)) {
4641          /* count the trailing zeros  */
4642          Int drop=0;
4643          for (;; drop++) {    /* [will terminate because lsu!=0]  */
4644            if (exponent>=maxexponent) break;     /* don't chop real 0s  */
4645            #if DECDPUN<=4
4646              if ((lsu-QUOT10(lsu, drop+1)
4647                  *powers[drop+1])!=0) break;     /* found non-0 digit  */
4648            #else
4649              if (lsu%powers[drop+1]!=0) break;   /* found non-0 digit  */
4650            #endif
4651            exponent++;
4652            }
4653          if (drop>0) {
4654            accunits=decShiftToLeast(accnext, accunits, drop);
4655            accdigits=decGetDigits(accnext, accunits);
4656            accunits=D2U(accdigits);
4657            /* [exponent was adjusted in the loop]  */
4658            }
4659          } /* neither odd nor 0  */
4660        #endif
4661        } /* exact divide  */
4662      } /* divide  */
4663     else /* op!=DIVIDE */ {
4664      /* check for coefficient overflow  */
4665      if (accdigits+exponent>reqdigits) {
4666        *status|=DEC_Division_impossible;
4667        break;
4668        }
4669      if (op & (REMAINDER|REMNEAR)) {
4670        /* [Here, the exponent will be 0, because var1 was adjusted  */
4671        /* appropriately.]  */
4672        Int postshift;                       /* work  */
4673        Flag wasodd=0;                       /* integer was odd  */
4674        Unit *quotlsu;                       /* for save  */
4675        Int  quotdigits;                     /* ..  */
4676
4677        bits=lhs->bits;                      /* remainder sign is always as lhs  */
4678
4679        /* Fastpath when residue is truly 0 is worthwhile [and  */
4680        /* simplifies the code below]  */
4681        if (*var1==0 && var1units==1) {      /* residue is 0  */
4682          Int exp=lhs->exponent;             /* save min(exponents)  */
4683          if (rhs->exponent<exp) exp=rhs->exponent;
4684          uprv_decNumberZero(res);                /* 0 coefficient  */
4685          #if DECSUBSET
4686          if (set->extended)
4687          #endif
4688          res->exponent=exp;                 /* .. with proper exponent  */
4689          res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4690          decFinish(res, set, &residue, status);   /* might clamp  */
4691          break;
4692          }
4693        /* note if the quotient was odd  */
4694        if (*accnext & 0x01) wasodd=1;       /* acc is odd  */
4695        quotlsu=accnext;                     /* save in case need to reinspect  */
4696        quotdigits=accdigits;                /* ..  */
4697
4698        /* treat the residue, in var1, as the value to return, via acc  */
4699        /* calculate the unused zero digits.  This is the smaller of:  */
4700        /*   var1 initial padding (saved above)  */
4701        /*   var2 residual padding, which happens to be given by:  */
4702        postshift=var1initpad+exponent-lhs->exponent+rhs->exponent;
4703        /* [the 'exponent' term accounts for the shifts during divide]  */
4704        if (var1initpad<postshift) postshift=var1initpad;
4705
4706        /* shift var1 the requested amount, and adjust its digits  */
4707        var1units=decShiftToLeast(var1, var1units, postshift);
4708        accnext=var1;
4709        accdigits=decGetDigits(var1, var1units);
4710        accunits=D2U(accdigits);
4711
4712        exponent=lhs->exponent;         /* exponent is smaller of lhs & rhs  */
4713        if (rhs->exponent<exponent) exponent=rhs->exponent;
4714
4715        /* Now correct the result if doing remainderNear; if it  */
4716        /* (looking just at coefficients) is > rhs/2, or == rhs/2 and  */
4717        /* the integer was odd then the result should be rem-rhs.  */
4718        if (op&REMNEAR) {
4719          Int compare, tarunits;        /* work  */
4720          Unit *up;                     /* ..  */
4721          /* calculate remainder*2 into the var1 buffer (which has  */
4722          /* 'headroom' of an extra unit and hence enough space)  */
4723          /* [a dedicated 'double' loop would be faster, here]  */
4724          tarunits=decUnitAddSub(accnext, accunits, accnext, accunits,
4725                                 0, accnext, 1);
4726          /* decDumpAr('r', accnext, tarunits);  */
4727
4728          /* Here, accnext (var1) holds tarunits Units with twice the  */
4729          /* remainder's coefficient, which must now be compared to the  */
4730          /* RHS.  The remainder's exponent may be smaller than the RHS's.  */
4731          compare=decUnitCompare(accnext, tarunits, rhs->lsu, D2U(rhs->digits),
4732                                 rhs->exponent-exponent);
4733          if (compare==BADINT) {             /* deep trouble  */
4734            *status|=DEC_Insufficient_storage;
4735            break;}
4736
4737          /* now restore the remainder by dividing by two; the lsu  */
4738          /* is known to be even.  */
4739          for (up=accnext; up<accnext+tarunits; up++) {
4740            Int half;              /* half to add to lower unit  */
4741            half=*up & 0x01;
4742            *up/=2;                /* [shift]  */
4743            if (!half) continue;
4744            *(up-1)+=(DECDPUNMAX+1)/2;
4745            }
4746          /* [accunits still describes the original remainder length]  */
4747
4748          if (compare>0 || (compare==0 && wasodd)) { /* adjustment needed  */
4749            Int exp, expunits, exprem;       /* work  */
4750            /* This is effectively causing round-up of the quotient,  */
4751            /* so if it was the rare case where it was full and all  */
4752            /* nines, it would overflow and hence division-impossible  */
4753            /* should be raised  */
4754            Flag allnines=0;                 /* 1 if quotient all nines  */
4755            if (quotdigits==reqdigits) {     /* could be borderline  */
4756              for (up=quotlsu; ; up++) {
4757                if (quotdigits>DECDPUN) {
4758                  if (*up!=DECDPUNMAX) break;/* non-nines  */
4759                  }
4760                 else {                      /* this is the last Unit  */
4761                  if (*up==powers[quotdigits]-1) allnines=1;
4762                  break;
4763                  }
4764                quotdigits-=DECDPUN;         /* checked those digits  */
4765                } /* up  */
4766              } /* borderline check  */
4767            if (allnines) {
4768              *status|=DEC_Division_impossible;
4769              break;}
4770
4771            /* rem-rhs is needed; the sign will invert.  Again, var1  */
4772            /* can safely be used for the working Units array.  */
4773            exp=rhs->exponent-exponent;      /* RHS padding needed  */
4774            /* Calculate units and remainder from exponent.  */
4775            expunits=exp/DECDPUN;
4776            exprem=exp%DECDPUN;
4777            /* subtract [A+B*(-m)]; the result will always be negative  */
4778            accunits=-decUnitAddSub(accnext, accunits,
4779                                    rhs->lsu, D2U(rhs->digits),
4780                                    expunits, accnext, -(Int)powers[exprem]);
4781            accdigits=decGetDigits(accnext, accunits); /* count digits exactly  */
4782            accunits=D2U(accdigits);    /* and recalculate the units for copy  */
4783            /* [exponent is as for original remainder]  */
4784            bits^=DECNEG;               /* flip the sign  */
4785            }
4786          } /* REMNEAR  */
4787        } /* REMAINDER or REMNEAR  */
4788      } /* not DIVIDE  */
4789
4790    /* Set exponent and bits  */
4791    res->exponent=exponent;
4792    res->bits=(uByte)(bits&DECNEG);          /* [cleaned]  */
4793
4794    /* Now the coefficient.  */
4795    decSetCoeff(res, set, accnext, accdigits, &residue, status);
4796
4797    decFinish(res, set, &residue, status);   /* final cleanup  */
4798
4799    #if DECSUBSET
4800    /* If a divide then strip trailing zeros if subset [after round]  */
4801    if (!set->extended && (op==DIVIDE)) decTrim(res, set, 0, 1, &dropped);
4802    #endif
4803    } while(0);                              /* end protected  */
4804
4805  if (varalloc!=NULL) free(varalloc);   /* drop any storage used  */
4806  if (allocacc!=NULL) free(allocacc);   /* ..  */
4807  #if DECSUBSET
4808  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
4809  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
4810  #endif
4811  return res;
4812  } /* decDivideOp  */
4813
4814/* ------------------------------------------------------------------ */
4815/* decMultiplyOp -- multiplication operation                          */
4816/*                                                                    */
4817/*  This routine performs the multiplication C=A x B.                 */
4818/*                                                                    */
4819/*   res is C, the result.  C may be A and/or B (e.g., X=X*X)         */
4820/*   lhs is A                                                         */
4821/*   rhs is B                                                         */
4822/*   set is the context                                               */
4823/*   status is the usual accumulator                                  */
4824/*                                                                    */
4825/* C must have space for set->digits digits.                          */
4826/*                                                                    */
4827/* ------------------------------------------------------------------ */
4828/* 'Classic' multiplication is used rather than Karatsuba, as the     */
4829/* latter would give only a minor improvement for the short numbers   */
4830/* expected to be handled most (and uses much more memory).           */
4831/*                                                                    */
4832/* There are two major paths here: the general-purpose ('old code')   */
4833/* path which handles all DECDPUN values, and a fastpath version      */
4834/* which is used if 64-bit ints are available, DECDPUN<=4, and more   */
4835/* than two calls to decUnitAddSub would be made.                     */
4836/*                                                                    */
4837/* The fastpath version lumps units together into 8-digit or 9-digit  */
4838/* chunks, and also uses a lazy carry strategy to minimise expensive  */
4839/* 64-bit divisions.  The chunks are then broken apart again into     */
4840/* units for continuing processing.  Despite this overhead, the       */
4841/* fastpath can speed up some 16-digit operations by 10x (and much    */
4842/* more for higher-precision calculations).                           */
4843/*                                                                    */
4844/* A buffer always has to be used for the accumulator; in the         */
4845/* fastpath, buffers are also always needed for the chunked copies of */
4846/* of the operand coefficients.                                       */
4847/* Static buffers are larger than needed just for multiply, to allow  */
4848/* for calls from other operations (notably exp).                     */
4849/* ------------------------------------------------------------------ */
4850#define FASTMUL (DECUSE64 && DECDPUN<5)
4851static decNumber * decMultiplyOp(decNumber *res, const decNumber *lhs,
4852                                 const decNumber *rhs, decContext *set,
4853                                 uInt *status) {
4854  Int    accunits;                 /* Units of accumulator in use  */
4855  Int    exponent;                 /* work  */
4856  Int    residue=0;                /* rounding residue  */
4857  uByte  bits;                     /* result sign  */
4858  Unit  *acc;                      /* -> accumulator Unit array  */
4859  Int    needbytes;                /* size calculator  */
4860  void  *allocacc=NULL;            /* -> allocated accumulator, iff allocated  */
4861  Unit  accbuff[SD2U(DECBUFFER*4+1)]; /* buffer (+1 for DECBUFFER==0,  */
4862                                   /* *4 for calls from other operations)  */
4863  const Unit *mer, *mermsup;       /* work  */
4864  Int   madlength;                 /* Units in multiplicand  */
4865  Int   shift;                     /* Units to shift multiplicand by  */
4866
4867  #if FASTMUL
4868    /* if DECDPUN is 1 or 3 work in base 10**9, otherwise  */
4869    /* (DECDPUN is 2 or 4) then work in base 10**8  */
4870    #if DECDPUN & 1                /* odd  */
4871      #define FASTBASE 1000000000  /* base  */
4872      #define FASTDIGS          9  /* digits in base  */
4873      #define FASTLAZY         18  /* carry resolution point [1->18]  */
4874    #else
4875      #define FASTBASE  100000000
4876      #define FASTDIGS          8
4877      #define FASTLAZY       1844  /* carry resolution point [1->1844]  */
4878    #endif
4879    /* three buffers are used, two for chunked copies of the operands  */
4880    /* (base 10**8 or base 10**9) and one base 2**64 accumulator with  */
4881    /* lazy carry evaluation  */
4882    uInt   zlhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4883    uInt  *zlhi=zlhibuff;                 /* -> lhs array  */
4884    uInt  *alloclhi=NULL;                 /* -> allocated buffer, iff allocated  */
4885    uInt   zrhibuff[(DECBUFFER*2+1)/8+1]; /* buffer (+1 for DECBUFFER==0)  */
4886    uInt  *zrhi=zrhibuff;                 /* -> rhs array  */
4887    uInt  *allocrhi=NULL;                 /* -> allocated buffer, iff allocated  */
4888    uLong  zaccbuff[(DECBUFFER*2+1)/4+2]; /* buffer (+1 for DECBUFFER==0)  */
4889    /* [allocacc is shared for both paths, as only one will run]  */
4890    uLong *zacc=zaccbuff;          /* -> accumulator array for exact result  */
4891    #if DECDPUN==1
4892    Int    zoff;                   /* accumulator offset  */
4893    #endif
4894    uInt  *lip, *rip;              /* item pointers  */
4895    uInt  *lmsi, *rmsi;            /* most significant items  */
4896    Int    ilhs, irhs, iacc;       /* item counts in the arrays  */
4897    Int    lazy;                   /* lazy carry counter  */
4898    uLong  lcarry;                 /* uLong carry  */
4899    uInt   carry;                  /* carry (NB not uLong)  */
4900    Int    count;                  /* work  */
4901    const  Unit *cup;              /* ..  */
4902    Unit  *up;                     /* ..  */
4903    uLong *lp;                     /* ..  */
4904    Int    p;                      /* ..  */
4905  #endif
4906
4907  #if DECSUBSET
4908    decNumber *alloclhs=NULL;      /* -> allocated buffer, iff allocated  */
4909    decNumber *allocrhs=NULL;      /* -> allocated buffer, iff allocated  */
4910  #endif
4911
4912  #if DECCHECK
4913  if (decCheckOperands(res, lhs, rhs, set)) return res;
4914  #endif
4915
4916  /* precalculate result sign  */
4917  bits=(uByte)((lhs->bits^rhs->bits)&DECNEG);
4918
4919  /* handle infinities and NaNs  */
4920  if (SPECIALARGS) {               /* a special bit set  */
4921    if (SPECIALARGS & (DECSNAN | DECNAN)) { /* one or two NaNs  */
4922      decNaNs(res, lhs, rhs, set, status);
4923      return res;}
4924    /* one or two infinities; Infinity * 0 is invalid  */
4925    if (((lhs->bits & DECINF)==0 && ISZERO(lhs))
4926      ||((rhs->bits & DECINF)==0 && ISZERO(rhs))) {
4927      *status|=DEC_Invalid_operation;
4928      return res;}
4929    uprv_decNumberZero(res);
4930    res->bits=bits|DECINF;         /* infinity  */
4931    return res;}
4932
4933  /* For best speed, as in DMSRCN [the original Rexx numerics  */
4934  /* module], use the shorter number as the multiplier (rhs) and  */
4935  /* the longer as the multiplicand (lhs) to minimise the number of  */
4936  /* adds (partial products)  */
4937  if (lhs->digits<rhs->digits) {   /* swap...  */
4938    const decNumber *hold=lhs;
4939    lhs=rhs;
4940    rhs=hold;
4941    }
4942
4943  do {                             /* protect allocated storage  */
4944    #if DECSUBSET
4945    if (!set->extended) {
4946      /* reduce operands and set lostDigits status, as needed  */
4947      if (lhs->digits>set->digits) {
4948        alloclhs=decRoundOperand(lhs, set, status);
4949        if (alloclhs==NULL) break;
4950        lhs=alloclhs;
4951        }
4952      if (rhs->digits>set->digits) {
4953        allocrhs=decRoundOperand(rhs, set, status);
4954        if (allocrhs==NULL) break;
4955        rhs=allocrhs;
4956        }
4957      }
4958    #endif
4959    /* [following code does not require input rounding]  */
4960
4961    #if FASTMUL                    /* fastpath can be used  */
4962    /* use the fast path if there are enough digits in the shorter  */
4963    /* operand to make the setup and takedown worthwhile  */
4964    #define NEEDTWO (DECDPUN*2)    /* within two decUnitAddSub calls  */
4965    if (rhs->digits>NEEDTWO) {     /* use fastpath...  */
4966      /* calculate the number of elements in each array  */
4967      ilhs=(lhs->digits+FASTDIGS-1)/FASTDIGS; /* [ceiling]  */
4968      irhs=(rhs->digits+FASTDIGS-1)/FASTDIGS; /* ..  */
4969      iacc=ilhs+irhs;
4970
4971      /* allocate buffers if required, as usual  */
4972      needbytes=ilhs*sizeof(uInt);
4973      if (needbytes>(Int)sizeof(zlhibuff)) {
4974        alloclhi=(uInt *)malloc(needbytes);
4975        zlhi=alloclhi;}
4976      needbytes=irhs*sizeof(uInt);
4977      if (needbytes>(Int)sizeof(zrhibuff)) {
4978        allocrhi=(uInt *)malloc(needbytes);
4979        zrhi=allocrhi;}
4980
4981      /* Allocating the accumulator space needs a special case when  */
4982      /* DECDPUN=1 because when converting the accumulator to Units  */
4983      /* after the multiplication each 8-byte item becomes 9 1-byte  */
4984      /* units.  Therefore iacc extra bytes are needed at the front  */
4985      /* (rounded up to a multiple of 8 bytes), and the uLong  */
4986      /* accumulator starts offset the appropriate number of units  */
4987      /* to the right to avoid overwrite during the unchunking.  */
4988      needbytes=iacc*sizeof(uLong);
4989      #if DECDPUN==1
4990      zoff=(iacc+7)/8;        /* items to offset by  */
4991      needbytes+=zoff*8;
4992      #endif
4993      if (needbytes>(Int)sizeof(zaccbuff)) {
4994        allocacc=(uLong *)malloc(needbytes);
4995        zacc=(uLong *)allocacc;}
4996      if (zlhi==NULL||zrhi==NULL||zacc==NULL) {
4997        *status|=DEC_Insufficient_storage;
4998        break;}
4999
5000      acc=(Unit *)zacc;       /* -> target Unit array  */
5001      #if DECDPUN==1
5002      zacc+=zoff;             /* start uLong accumulator to right  */
5003      #endif
5004
5005      /* assemble the chunked copies of the left and right sides  */
5006      for (count=lhs->digits, cup=lhs->lsu, lip=zlhi; count>0; lip++)
5007        for (p=0, *lip=0; p<FASTDIGS && count>0;
5008             p+=DECDPUN, cup++, count-=DECDPUN)
5009          *lip+=*cup*powers[p];
5010      lmsi=lip-1;     /* save -> msi  */
5011      for (count=rhs->digits, cup=rhs->lsu, rip=zrhi; count>0; rip++)
5012        for (p=0, *rip=0; p<FASTDIGS && count>0;
5013             p+=DECDPUN, cup++, count-=DECDPUN)
5014          *rip+=*cup*powers[p];
5015      rmsi=rip-1;     /* save -> msi  */
5016
5017      /* zero the accumulator  */
5018      for (lp=zacc; lp<zacc+iacc; lp++) *lp=0;
5019
5020      /* Start the multiplication */
5021      /* Resolving carries can dominate the cost of accumulating the  */
5022      /* partial products, so this is only done when necessary.  */
5023      /* Each uLong item in the accumulator can hold values up to  */
5024      /* 2**64-1, and each partial product can be as large as  */
5025      /* (10**FASTDIGS-1)**2.  When FASTDIGS=9, this can be added to  */
5026      /* itself 18.4 times in a uLong without overflowing, so during  */
5027      /* the main calculation resolution is carried out every 18th  */
5028      /* add -- every 162 digits.  Similarly, when FASTDIGS=8, the  */
5029      /* partial products can be added to themselves 1844.6 times in  */
5030      /* a uLong without overflowing, so intermediate carry  */
5031      /* resolution occurs only every 14752 digits.  Hence for common  */
5032      /* short numbers usually only the one final carry resolution  */
5033      /* occurs.  */
5034      /* (The count is set via FASTLAZY to simplify experiments to  */
5035      /* measure the value of this approach: a 35% improvement on a  */
5036      /* [34x34] multiply.)  */
5037      lazy=FASTLAZY;                         /* carry delay count  */
5038      for (rip=zrhi; rip<=rmsi; rip++) {     /* over each item in rhs  */
5039        lp=zacc+(rip-zrhi);                  /* where to add the lhs  */
5040        for (lip=zlhi; lip<=lmsi; lip++, lp++) { /* over each item in lhs  */
5041          *lp+=(uLong)(*lip)*(*rip);         /* [this should in-line]  */
5042          } /* lip loop  */
5043        lazy--;
5044        if (lazy>0 && rip!=rmsi) continue;
5045        lazy=FASTLAZY;                       /* reset delay count  */
5046        /* spin up the accumulator resolving overflows  */
5047        for (lp=zacc; lp<zacc+iacc; lp++) {
5048          if (*lp<FASTBASE) continue;        /* it fits  */
5049          lcarry=*lp/FASTBASE;               /* top part [slow divide]  */
5050          /* lcarry can exceed 2**32-1, so check again; this check  */
5051          /* and occasional extra divide (slow) is well worth it, as  */
5052          /* it allows FASTLAZY to be increased to 18 rather than 4  */
5053          /* in the FASTDIGS=9 case  */
5054          if (lcarry<FASTBASE) carry=(uInt)lcarry;  /* [usual]  */
5055           else { /* two-place carry [fairly rare]  */
5056            uInt carry2=(uInt)(lcarry/FASTBASE);    /* top top part  */
5057            *(lp+2)+=carry2;                        /* add to item+2  */
5058            *lp-=((uLong)FASTBASE*FASTBASE*carry2); /* [slow]  */
5059            carry=(uInt)(lcarry-((uLong)FASTBASE*carry2)); /* [inline]  */
5060            }
5061          *(lp+1)+=carry;                    /* add to item above [inline]  */
5062          *lp-=((uLong)FASTBASE*carry);      /* [inline]  */
5063          } /* carry resolution  */
5064        } /* rip loop  */
5065
5066      /* The multiplication is complete; time to convert back into  */
5067      /* units.  This can be done in-place in the accumulator and in  */
5068      /* 32-bit operations, because carries were resolved after the  */
5069      /* final add.  This needs N-1 divides and multiplies for  */
5070      /* each item in the accumulator (which will become up to N  */
5071      /* units, where 2<=N<=9).  */
5072      for (lp=zacc, up=acc; lp<zacc+iacc; lp++) {
5073        uInt item=(uInt)*lp;                 /* decapitate to uInt  */
5074        for (p=0; p<FASTDIGS-DECDPUN; p+=DECDPUN, up++) {
5075          uInt part=item/(DECDPUNMAX+1);
5076          *up=(Unit)(item-(part*(DECDPUNMAX+1)));
5077          item=part;
5078          } /* p  */
5079        *up=(Unit)item; up++;                /* [final needs no division]  */
5080        } /* lp  */
5081      accunits=up-acc;                       /* count of units  */
5082      }
5083     else { /* here to use units directly, without chunking ['old code']  */
5084    #endif
5085
5086      /* if accumulator will be too long for local storage, then allocate  */
5087      acc=accbuff;                 /* -> assume buffer for accumulator  */
5088      needbytes=(D2U(lhs->digits)+D2U(rhs->digits))*sizeof(Unit);
5089      if (needbytes>(Int)sizeof(accbuff)) {
5090        allocacc=(Unit *)malloc(needbytes);
5091        if (allocacc==NULL) {*status|=DEC_Insufficient_storage; break;}
5092        acc=(Unit *)allocacc;                /* use the allocated space  */
5093        }
5094
5095      /* Now the main long multiplication loop */
5096      /* Unlike the equivalent in the IBM Java implementation, there  */
5097      /* is no advantage in calculating from msu to lsu.  So, do it  */
5098      /* by the book, as it were.  */
5099      /* Each iteration calculates ACC=ACC+MULTAND*MULT  */
5100      accunits=1;                  /* accumulator starts at '0'  */
5101      *acc=0;                      /* .. (lsu=0)  */
5102      shift=0;                     /* no multiplicand shift at first  */
5103      madlength=D2U(lhs->digits);  /* this won't change  */
5104      mermsup=rhs->lsu+D2U(rhs->digits); /* -> msu+1 of multiplier  */
5105
5106      for (mer=rhs->lsu; mer<mermsup; mer++) {
5107        /* Here, *mer is the next Unit in the multiplier to use  */
5108        /* If non-zero [optimization] add it...  */
5109        if (*mer!=0) accunits=decUnitAddSub(&acc[shift], accunits-shift,
5110                                            lhs->lsu, madlength, 0,
5111                                            &acc[shift], *mer)
5112                                            + shift;
5113         else { /* extend acc with a 0; it will be used shortly  */
5114          *(acc+accunits)=0;       /* [this avoids length of <=0 later]  */
5115          accunits++;
5116          }
5117        /* multiply multiplicand by 10**DECDPUN for next Unit to left  */
5118        shift++;                   /* add this for 'logical length'  */
5119        } /* n  */
5120    #if FASTMUL
5121      } /* unchunked units  */
5122    #endif
5123    /* common end-path  */
5124    #if DECTRACE
5125      decDumpAr('*', acc, accunits);         /* Show exact result  */
5126    #endif
5127
5128    /* acc now contains the exact result of the multiplication,  */
5129    /* possibly with a leading zero unit; build the decNumber from  */
5130    /* it, noting if any residue  */
5131    res->bits=bits;                          /* set sign  */
5132    res->digits=decGetDigits(acc, accunits); /* count digits exactly  */
5133
5134    /* There can be a 31-bit wrap in calculating the exponent.  */
5135    /* This can only happen if both input exponents are negative and  */
5136    /* both their magnitudes are large.  If there was a wrap, set a  */
5137    /* safe very negative exponent, from which decFinalize() will  */
5138    /* raise a hard underflow shortly.  */
5139    exponent=lhs->exponent+rhs->exponent;    /* calculate exponent  */
5140    if (lhs->exponent<0 && rhs->exponent<0 && exponent>0)
5141      exponent=-2*DECNUMMAXE;                /* force underflow  */
5142    res->exponent=exponent;                  /* OK to overwrite now  */
5143
5144
5145    /* Set the coefficient.  If any rounding, residue records  */
5146    decSetCoeff(res, set, acc, res->digits, &residue, status);
5147    decFinish(res, set, &residue, status);   /* final cleanup  */
5148    } while(0);                         /* end protected  */
5149
5150  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
5151  #if DECSUBSET
5152  if (allocrhs!=NULL) free(allocrhs);   /* ..  */
5153  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5154  #endif
5155  #if FASTMUL
5156  if (allocrhi!=NULL) free(allocrhi);   /* ..  */
5157  if (alloclhi!=NULL) free(alloclhi);   /* ..  */
5158  #endif
5159  return res;
5160  } /* decMultiplyOp  */
5161
5162/* ------------------------------------------------------------------ */
5163/* decExpOp -- effect exponentiation                                  */
5164/*                                                                    */
5165/*   This computes C = exp(A)                                         */
5166/*                                                                    */
5167/*   res is C, the result.  C may be A                                */
5168/*   rhs is A                                                         */
5169/*   set is the context; note that rounding mode has no effect        */
5170/*                                                                    */
5171/* C must have space for set->digits digits. status is updated but    */
5172/* not set.                                                           */
5173/*                                                                    */
5174/* Restrictions:                                                      */
5175/*                                                                    */
5176/*   digits, emax, and -emin in the context must be less than         */
5177/*   2*DEC_MAX_MATH (1999998), and the rhs must be within these       */
5178/*   bounds or a zero.  This is an internal routine, so these         */
5179/*   restrictions are contractual and not enforced.                   */
5180/*                                                                    */
5181/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5182/* almost always be correctly rounded, but may be up to 1 ulp in      */
5183/* error in rare cases.                                               */
5184/*                                                                    */
5185/* Finite results will always be full precision and Inexact, except   */
5186/* when A is a zero or -Infinity (giving 1 or 0 respectively).        */
5187/* ------------------------------------------------------------------ */
5188/* This approach used here is similar to the algorithm described in   */
5189/*                                                                    */
5190/*   Variable Precision Exponential Function, T. E. Hull and          */
5191/*   A. Abrham, ACM Transactions on Mathematical Software, Vol 12 #2, */
5192/*   pp79-91, ACM, June 1986.                                         */
5193/*                                                                    */
5194/* with the main difference being that the iterations in the series   */
5195/* evaluation are terminated dynamically (which does not require the  */
5196/* extra variable-precision variables which are expensive in this     */
5197/* context).                                                          */
5198/*                                                                    */
5199/* The error analysis in Hull & Abrham's paper applies except for the */
5200/* round-off error accumulation during the series evaluation.  This   */
5201/* code does not precalculate the number of iterations and so cannot  */
5202/* use Horner's scheme.  Instead, the accumulation is done at double- */
5203/* precision, which ensures that the additions of the terms are exact */
5204/* and do not accumulate round-off (and any round-off errors in the   */
5205/* terms themselves move 'to the right' faster than they can          */
5206/* accumulate).  This code also extends the calculation by allowing,  */
5207/* in the spirit of other decNumber operators, the input to be more   */
5208/* precise than the result (the precision used is based on the more   */
5209/* precise of the input or requested result).                         */
5210/*                                                                    */
5211/* Implementation notes:                                              */
5212/*                                                                    */
5213/* 1. This is separated out as decExpOp so it can be called from      */
5214/*    other Mathematical functions (notably Ln) with a wider range    */
5215/*    than normal.  In particular, it can handle the slightly wider   */
5216/*    (double) range needed by Ln (which has to be able to calculate  */
5217/*    exp(-x) where x can be the tiniest number (Ntiny).              */
5218/*                                                                    */
5219/* 2. Normalizing x to be <=0.1 (instead of <=1) reduces loop         */
5220/*    iterations by appoximately a third with additional (although    */
5221/*    diminishing) returns as the range is reduced to even smaller    */
5222/*    fractions.  However, h (the power of 10 used to correct the     */
5223/*    result at the end, see below) must be kept <=8 as otherwise     */
5224/*    the final result cannot be computed.  Hence the leverage is a   */
5225/*    sliding value (8-h), where potentially the range is reduced     */
5226/*    more for smaller values.                                        */
5227/*                                                                    */
5228/*    The leverage that can be applied in this way is severely        */
5229/*    limited by the cost of the raise-to-the power at the end,       */
5230/*    which dominates when the number of iterations is small (less    */
5231/*    than ten) or when rhs is short.  As an example, the adjustment  */
5232/*    x**10,000,000 needs 31 multiplications, all but one full-width. */
5233/*                                                                    */
5234/* 3. The restrictions (especially precision) could be raised with    */
5235/*    care, but the full decNumber range seems very hard within the   */
5236/*    32-bit limits.                                                  */
5237/*                                                                    */
5238/* 4. The working precisions for the static buffers are twice the     */
5239/*    obvious size to allow for calls from decNumberPower.            */
5240/* ------------------------------------------------------------------ */
5241decNumber * decExpOp(decNumber *res, const decNumber *rhs,
5242                         decContext *set, uInt *status) {
5243  uInt ignore=0;                   /* working status  */
5244  Int h;                           /* adjusted exponent for 0.xxxx  */
5245  Int p;                           /* working precision  */
5246  Int residue;                     /* rounding residue  */
5247  uInt needbytes;                  /* for space calculations  */
5248  const decNumber *x=rhs;          /* (may point to safe copy later)  */
5249  decContext aset, tset, dset;     /* working contexts  */
5250  Int comp;                        /* work  */
5251
5252  /* the argument is often copied to normalize it, so (unusually) it  */
5253  /* is treated like other buffers, using DECBUFFER, +1 in case  */
5254  /* DECBUFFER is 0  */
5255  decNumber bufr[D2N(DECBUFFER*2+1)];
5256  decNumber *allocrhs=NULL;        /* non-NULL if rhs buffer allocated  */
5257
5258  /* the working precision will be no more than set->digits+8+1  */
5259  /* so for on-stack buffers DECBUFFER+9 is used, +1 in case DECBUFFER  */
5260  /* is 0 (and twice that for the accumulator)  */
5261
5262  /* buffer for t, term (working precision plus)  */
5263  decNumber buft[D2N(DECBUFFER*2+9+1)];
5264  decNumber *allocbuft=NULL;       /* -> allocated buft, iff allocated  */
5265  decNumber *t=buft;               /* term  */
5266  /* buffer for a, accumulator (working precision * 2), at least 9  */
5267  decNumber bufa[D2N(DECBUFFER*4+18+1)];
5268  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5269  decNumber *a=bufa;               /* accumulator  */
5270  /* decNumber for the divisor term; this needs at most 9 digits  */
5271  /* and so can be fixed size [16 so can use standard context]  */
5272  decNumber bufd[D2N(16)];
5273  decNumber *d=bufd;               /* divisor  */
5274  decNumber numone;                /* constant 1  */
5275
5276  #if DECCHECK
5277  Int iterations=0;                /* for later sanity check  */
5278  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5279  #endif
5280
5281  do {                                  /* protect allocated storage  */
5282    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5283      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5284        if (decNumberIsNegative(rhs))   /* -Infinity -> +0  */
5285          uprv_decNumberZero(res);
5286         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5287        }
5288       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5289      break;}
5290
5291    if (ISZERO(rhs)) {                  /* zeros -> exact 1  */
5292      uprv_decNumberZero(res);               /* make clean 1  */
5293      *res->lsu=1;                      /* ..  */
5294      break;}                           /* [no status to set]  */
5295
5296    /* e**x when 0 < x < 0.66 is < 1+3x/2, hence can fast-path  */
5297    /* positive and negative tiny cases which will result in inexact  */
5298    /* 1.  This also allows the later add-accumulate to always be  */
5299    /* exact (because its length will never be more than twice the  */
5300    /* working precision).  */
5301    /* The comparator (tiny) needs just one digit, so use the  */
5302    /* decNumber d for it (reused as the divisor, etc., below); its  */
5303    /* exponent is such that if x is positive it will have  */
5304    /* set->digits-1 zeros between the decimal point and the digit,  */
5305    /* which is 4, and if x is negative one more zero there as the  */
5306    /* more precise result will be of the form 0.9999999 rather than  */
5307    /* 1.0000001.  Hence, tiny will be 0.0000004  if digits=7 and x>0  */
5308    /* or 0.00000004 if digits=7 and x<0.  If RHS not larger than  */
5309    /* this then the result will be 1.000000  */
5310    uprv_decNumberZero(d);                   /* clean  */
5311    *d->lsu=4;                          /* set 4 ..  */
5312    d->exponent=-set->digits;           /* * 10**(-d)  */
5313    if (decNumberIsNegative(rhs)) d->exponent--;  /* negative case  */
5314    comp=decCompare(d, rhs, 1);         /* signless compare  */
5315    if (comp==BADINT) {
5316      *status|=DEC_Insufficient_storage;
5317      break;}
5318    if (comp>=0) {                      /* rhs < d  */
5319      Int shift=set->digits-1;
5320      uprv_decNumberZero(res);               /* set 1  */
5321      *res->lsu=1;                      /* ..  */
5322      res->digits=decShiftToMost(res->lsu, 1, shift);
5323      res->exponent=-shift;                  /* make 1.0000...  */
5324      *status|=DEC_Inexact | DEC_Rounded;    /* .. inexactly  */
5325      break;} /* tiny  */
5326
5327    /* set up the context to be used for calculating a, as this is  */
5328    /* used on both paths below  */
5329    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64);
5330    /* accumulator bounds are as requested (could underflow)  */
5331    aset.emax=set->emax;                /* usual bounds  */
5332    aset.emin=set->emin;                /* ..  */
5333    aset.clamp=0;                       /* and no concrete format  */
5334
5335    /* calculate the adjusted (Hull & Abrham) exponent (where the  */
5336    /* decimal point is just to the left of the coefficient msd)  */
5337    h=rhs->exponent+rhs->digits;
5338    /* if h>8 then 10**h cannot be calculated safely; however, when  */
5339    /* h=8 then exp(|rhs|) will be at least exp(1E+7) which is at  */
5340    /* least 6.59E+4342944, so (due to the restriction on Emax/Emin)  */
5341    /* overflow (or underflow to 0) is guaranteed -- so this case can  */
5342    /* be handled by simply forcing the appropriate excess  */
5343    if (h>8) {                          /* overflow/underflow  */
5344      /* set up here so Power call below will over or underflow to  */
5345      /* zero; set accumulator to either 2 or 0.02  */
5346      /* [stack buffer for a is always big enough for this]  */
5347      uprv_decNumberZero(a);
5348      *a->lsu=2;                        /* not 1 but < exp(1)  */
5349      if (decNumberIsNegative(rhs)) a->exponent=-2; /* make 0.02  */
5350      h=8;                              /* clamp so 10**h computable  */
5351      p=9;                              /* set a working precision  */
5352      }
5353     else {                             /* h<=8  */
5354      Int maxlever=(rhs->digits>8?1:0);
5355      /* [could/should increase this for precisions >40 or so, too]  */
5356
5357      /* if h is 8, cannot normalize to a lower upper limit because  */
5358      /* the final result will not be computable (see notes above),  */
5359      /* but leverage can be applied whenever h is less than 8.  */
5360      /* Apply as much as possible, up to a MAXLEVER digits, which  */
5361      /* sets the tradeoff against the cost of the later a**(10**h).  */
5362      /* As h is increased, the working precision below also  */
5363      /* increases to compensate for the "constant digits at the  */
5364      /* front" effect.  */
5365      Int lever=MINI(8-h, maxlever);    /* leverage attainable  */
5366      Int use=-rhs->digits-lever;       /* exponent to use for RHS  */
5367      h+=lever;                         /* apply leverage selected  */
5368      if (h<0) {                        /* clamp  */
5369        use+=h;                         /* [may end up subnormal]  */
5370        h=0;
5371        }
5372      /* Take a copy of RHS if it needs normalization (true whenever x>=1)  */
5373      if (rhs->exponent!=use) {
5374        decNumber *newrhs=bufr;         /* assume will fit on stack  */
5375        needbytes=sizeof(decNumber)+(D2U(rhs->digits)-1)*sizeof(Unit);
5376        if (needbytes>sizeof(bufr)) {   /* need malloc space  */
5377          allocrhs=(decNumber *)malloc(needbytes);
5378          if (allocrhs==NULL) {         /* hopeless -- abandon  */
5379            *status|=DEC_Insufficient_storage;
5380            break;}
5381          newrhs=allocrhs;              /* use the allocated space  */
5382          }
5383        uprv_decNumberCopy(newrhs, rhs);     /* copy to safe space  */
5384        newrhs->exponent=use;           /* normalize; now <1  */
5385        x=newrhs;                       /* ready for use  */
5386        /* decNumberShow(x);  */
5387        }
5388
5389      /* Now use the usual power series to evaluate exp(x).  The  */
5390      /* series starts as 1 + x + x^2/2 ... so prime ready for the  */
5391      /* third term by setting the term variable t=x, the accumulator  */
5392      /* a=1, and the divisor d=2.  */
5393
5394      /* First determine the working precision.  From Hull & Abrham  */
5395      /* this is set->digits+h+2.  However, if x is 'over-precise' we  */
5396      /* need to allow for all its digits to potentially participate  */
5397      /* (consider an x where all the excess digits are 9s) so in  */
5398      /* this case use x->digits+h+2  */
5399      p=MAXI(x->digits, set->digits)+h+2;    /* [h<=8]  */
5400
5401      /* a and t are variable precision, and depend on p, so space  */
5402      /* must be allocated for them if necessary  */
5403
5404      /* the accumulator needs to be able to hold 2p digits so that  */
5405      /* the additions on the second and subsequent iterations are  */
5406      /* sufficiently exact.  */
5407      needbytes=sizeof(decNumber)+(D2U(p*2)-1)*sizeof(Unit);
5408      if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5409        allocbufa=(decNumber *)malloc(needbytes);
5410        if (allocbufa==NULL) {          /* hopeless -- abandon  */
5411          *status|=DEC_Insufficient_storage;
5412          break;}
5413        a=allocbufa;                    /* use the allocated space  */
5414        }
5415      /* the term needs to be able to hold p digits (which is  */
5416      /* guaranteed to be larger than x->digits, so the initial copy  */
5417      /* is safe); it may also be used for the raise-to-power  */
5418      /* calculation below, which needs an extra two digits  */
5419      needbytes=sizeof(decNumber)+(D2U(p+2)-1)*sizeof(Unit);
5420      if (needbytes>sizeof(buft)) {     /* need malloc space  */
5421        allocbuft=(decNumber *)malloc(needbytes);
5422        if (allocbuft==NULL) {          /* hopeless -- abandon  */
5423          *status|=DEC_Insufficient_storage;
5424          break;}
5425        t=allocbuft;                    /* use the allocated space  */
5426        }
5427
5428      uprv_decNumberCopy(t, x);              /* term=x  */
5429      uprv_decNumberZero(a); *a->lsu=1;      /* accumulator=1  */
5430      uprv_decNumberZero(d); *d->lsu=2;      /* divisor=2  */
5431      uprv_decNumberZero(&numone); *numone.lsu=1; /* constant 1 for increment  */
5432
5433      /* set up the contexts for calculating a, t, and d  */
5434      uprv_decContextDefault(&tset, DEC_INIT_DECIMAL64);
5435      dset=tset;
5436      /* accumulator bounds are set above, set precision now  */
5437      aset.digits=p*2;                  /* double  */
5438      /* term bounds avoid any underflow or overflow  */
5439      tset.digits=p;
5440      tset.emin=DEC_MIN_EMIN;           /* [emax is plenty]  */
5441      /* [dset.digits=16, etc., are sufficient]  */
5442
5443      /* finally ready to roll  */
5444      for (;;) {
5445        #if DECCHECK
5446        iterations++;
5447        #endif
5448        /* only the status from the accumulation is interesting  */
5449        /* [but it should remain unchanged after first add]  */
5450        decAddOp(a, a, t, &aset, 0, status);           /* a=a+t  */
5451        decMultiplyOp(t, t, x, &tset, &ignore);        /* t=t*x  */
5452        decDivideOp(t, t, d, &tset, DIVIDE, &ignore);  /* t=t/d  */
5453        /* the iteration ends when the term cannot affect the result,  */
5454        /* if rounded to p digits, which is when its value is smaller  */
5455        /* than the accumulator by p+1 digits.  There must also be  */
5456        /* full precision in a.  */
5457        if (((a->digits+a->exponent)>=(t->digits+t->exponent+p+1))
5458            && (a->digits>=p)) break;
5459        decAddOp(d, d, &numone, &dset, 0, &ignore);    /* d=d+1  */
5460        } /* iterate  */
5461
5462      #if DECCHECK
5463      /* just a sanity check; comment out test to show always  */
5464      if (iterations>p+3)
5465        printf("Exp iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5466               (LI)iterations, (LI)*status, (LI)p, (LI)x->digits);
5467      #endif
5468      } /* h<=8  */
5469
5470    /* apply postconditioning: a=a**(10**h) -- this is calculated  */
5471    /* at a slightly higher precision than Hull & Abrham suggest  */
5472    if (h>0) {
5473      Int seenbit=0;               /* set once a 1-bit is seen  */
5474      Int i;                       /* counter  */
5475      Int n=powers[h];             /* always positive  */
5476      aset.digits=p+2;             /* sufficient precision  */
5477      /* avoid the overhead and many extra digits of decNumberPower  */
5478      /* as all that is needed is the short 'multipliers' loop; here  */
5479      /* accumulate the answer into t  */
5480      uprv_decNumberZero(t); *t->lsu=1; /* acc=1  */
5481      for (i=1;;i++){              /* for each bit [top bit ignored]  */
5482        /* abandon if have had overflow or terminal underflow  */
5483        if (*status & (DEC_Overflow|DEC_Underflow)) { /* interesting?  */
5484          if (*status&DEC_Overflow || ISZERO(t)) break;}
5485        n=n<<1;                    /* move next bit to testable position  */
5486        if (n<0) {                 /* top bit is set  */
5487          seenbit=1;               /* OK, have a significant bit  */
5488          decMultiplyOp(t, t, a, &aset, status); /* acc=acc*x  */
5489          }
5490        if (i==31) break;          /* that was the last bit  */
5491        if (!seenbit) continue;    /* no need to square 1  */
5492        decMultiplyOp(t, t, t, &aset, status); /* acc=acc*acc [square]  */
5493        } /*i*/ /* 32 bits  */
5494      /* decNumberShow(t);  */
5495      a=t;                         /* and carry on using t instead of a  */
5496      }
5497
5498    /* Copy and round the result to res  */
5499    residue=1;                          /* indicate dirt to right ..  */
5500    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5501    aset.digits=set->digits;            /* [use default rounding]  */
5502    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5503    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5504    } while(0);                         /* end protected  */
5505
5506  if (allocrhs !=NULL) free(allocrhs);  /* drop any storage used  */
5507  if (allocbufa!=NULL) free(allocbufa); /* ..  */
5508  if (allocbuft!=NULL) free(allocbuft); /* ..  */
5509  /* [status is handled by caller]  */
5510  return res;
5511  } /* decExpOp  */
5512
5513/* ------------------------------------------------------------------ */
5514/* Initial-estimate natural logarithm table                           */
5515/*                                                                    */
5516/*   LNnn -- 90-entry 16-bit table for values from .10 through .99.   */
5517/*           The result is a 4-digit encode of the coefficient (c=the */
5518/*           top 14 bits encoding 0-9999) and a 2-digit encode of the */
5519/*           exponent (e=the bottom 2 bits encoding 0-3)              */
5520/*                                                                    */
5521/*           The resulting value is given by:                         */
5522/*                                                                    */
5523/*             v = -c * 10**(-e-3)                                    */
5524/*                                                                    */
5525/*           where e and c are extracted from entry k = LNnn[x-10]    */
5526/*           where x is truncated (NB) into the range 10 through 99,  */
5527/*           and then c = k>>2 and e = k&3.                           */
5528/* ------------------------------------------------------------------ */
5529const uShort LNnn[90]={9016,  8652,  8316,  8008,  7724,  7456,  7208,
5530  6972,  6748,  6540,  6340,  6148,  5968,  5792,  5628,  5464,  5312,
5531  5164,  5020,  4884,  4748,  4620,  4496,  4376,  4256,  4144,  4032,
5532 39233, 38181, 37157, 36157, 35181, 34229, 33297, 32389, 31501, 30629,
5533 29777, 28945, 28129, 27329, 26545, 25777, 25021, 24281, 23553, 22837,
5534 22137, 21445, 20769, 20101, 19445, 18801, 18165, 17541, 16925, 16321,
5535 15721, 15133, 14553, 13985, 13421, 12865, 12317, 11777, 11241, 10717,
5536 10197,  9685,  9177,  8677,  8185,  7697,  7213,  6737,  6269,  5801,
5537  5341,  4889,  4437, 39930, 35534, 31186, 26886, 22630, 18418, 14254,
5538 10130,  6046, 20055};
5539
5540/* ------------------------------------------------------------------ */
5541/* decLnOp -- effect natural logarithm                                */
5542/*                                                                    */
5543/*   This computes C = ln(A)                                          */
5544/*                                                                    */
5545/*   res is C, the result.  C may be A                                */
5546/*   rhs is A                                                         */
5547/*   set is the context; note that rounding mode has no effect        */
5548/*                                                                    */
5549/* C must have space for set->digits digits.                          */
5550/*                                                                    */
5551/* Notable cases:                                                     */
5552/*   A<0 -> Invalid                                                   */
5553/*   A=0 -> -Infinity (Exact)                                         */
5554/*   A=+Infinity -> +Infinity (Exact)                                 */
5555/*   A=1 exactly -> 0 (Exact)                                         */
5556/*                                                                    */
5557/* Restrictions (as for Exp):                                         */
5558/*                                                                    */
5559/*   digits, emax, and -emin in the context must be less than         */
5560/*   DEC_MAX_MATH+11 (1000010), and the rhs must be within these      */
5561/*   bounds or a zero.  This is an internal routine, so these         */
5562/*   restrictions are contractual and not enforced.                   */
5563/*                                                                    */
5564/* A finite result is rounded using DEC_ROUND_HALF_EVEN; it will      */
5565/* almost always be correctly rounded, but may be up to 1 ulp in      */
5566/* error in rare cases.                                               */
5567/* ------------------------------------------------------------------ */
5568/* The result is calculated using Newton's method, with each          */
5569/* iteration calculating a' = a + x * exp(-a) - 1.  See, for example, */
5570/* Epperson 1989.                                                     */
5571/*                                                                    */
5572/* The iteration ends when the adjustment x*exp(-a)-1 is tiny enough. */
5573/* This has to be calculated at the sum of the precision of x and the */
5574/* working precision.                                                 */
5575/*                                                                    */
5576/* Implementation notes:                                              */
5577/*                                                                    */
5578/* 1. This is separated out as decLnOp so it can be called from       */
5579/*    other Mathematical functions (e.g., Log 10) with a wider range  */
5580/*    than normal.  In particular, it can handle the slightly wider   */
5581/*    (+9+2) range needed by a power function.                        */
5582/*                                                                    */
5583/* 2. The speed of this function is about 10x slower than exp, as     */
5584/*    it typically needs 4-6 iterations for short numbers, and the    */
5585/*    extra precision needed adds a squaring effect, twice.           */
5586/*                                                                    */
5587/* 3. Fastpaths are included for ln(10) and ln(2), up to length 40,   */
5588/*    as these are common requests.  ln(10) is used by log10(x).      */
5589/*                                                                    */
5590/* 4. An iteration might be saved by widening the LNnn table, and     */
5591/*    would certainly save at least one if it were made ten times     */
5592/*    bigger, too (for truncated fractions 0.100 through 0.999).      */
5593/*    However, for most practical evaluations, at least four or five  */
5594/*    iterations will be neede -- so this would only speed up by      */
5595/*    20-25% and that probably does not justify increasing the table  */
5596/*    size.                                                           */
5597/*                                                                    */
5598/* 5. The static buffers are larger than might be expected to allow   */
5599/*    for calls from decNumberPower.                                  */
5600/* ------------------------------------------------------------------ */
5601#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
5602#pragma GCC diagnostic push
5603#pragma GCC diagnostic ignored "-Warray-bounds"
5604#endif
5605decNumber * decLnOp(decNumber *res, const decNumber *rhs,
5606                    decContext *set, uInt *status) {
5607  uInt ignore=0;                   /* working status accumulator  */
5608  uInt needbytes;                  /* for space calculations  */
5609  Int residue;                     /* rounding residue  */
5610  Int r;                           /* rhs=f*10**r [see below]  */
5611  Int p;                           /* working precision  */
5612  Int pp;                          /* precision for iteration  */
5613  Int t;                           /* work  */
5614
5615  /* buffers for a (accumulator, typically precision+2) and b  */
5616  /* (adjustment calculator, same size)  */
5617  decNumber bufa[D2N(DECBUFFER+12)];
5618  decNumber *allocbufa=NULL;       /* -> allocated bufa, iff allocated  */
5619  decNumber *a=bufa;               /* accumulator/work  */
5620  decNumber bufb[D2N(DECBUFFER*2+2)];
5621  decNumber *allocbufb=NULL;       /* -> allocated bufa, iff allocated  */
5622  decNumber *b=bufb;               /* adjustment/work  */
5623
5624  decNumber  numone;               /* constant 1  */
5625  decNumber  cmp;                  /* work  */
5626  decContext aset, bset;           /* working contexts  */
5627
5628  #if DECCHECK
5629  Int iterations=0;                /* for later sanity check  */
5630  if (decCheckOperands(res, DECUNUSED, rhs, set)) return res;
5631  #endif
5632
5633  do {                                  /* protect allocated storage  */
5634    if (SPECIALARG) {                   /* handle infinities and NaNs  */
5635      if (decNumberIsInfinite(rhs)) {   /* an infinity  */
5636        if (decNumberIsNegative(rhs))   /* -Infinity -> error  */
5637          *status|=DEC_Invalid_operation;
5638         else uprv_decNumberCopy(res, rhs);  /* +Infinity -> self  */
5639        }
5640       else decNaNs(res, rhs, NULL, set, status); /* a NaN  */
5641      break;}
5642
5643    if (ISZERO(rhs)) {                  /* +/- zeros -> -Infinity  */
5644      uprv_decNumberZero(res);               /* make clean  */
5645      res->bits=DECINF|DECNEG;          /* set - infinity  */
5646      break;}                           /* [no status to set]  */
5647
5648    /* Non-zero negatives are bad...  */
5649    if (decNumberIsNegative(rhs)) {     /* -x -> error  */
5650      *status|=DEC_Invalid_operation;
5651      break;}
5652
5653    /* Here, rhs is positive, finite, and in range  */
5654
5655    /* lookaside fastpath code for ln(2) and ln(10) at common lengths  */
5656    if (rhs->exponent==0 && set->digits<=40) {
5657      #if DECDPUN==1
5658      if (rhs->lsu[0]==0 && rhs->lsu[1]==1 && rhs->digits==2) { /* ln(10)  */
5659      #else
5660      if (rhs->lsu[0]==10 && rhs->digits==2) {                  /* ln(10)  */
5661      #endif
5662        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5663        #define LN10 "2.302585092994045684017991454684364207601"
5664        uprv_decNumberFromString(res, LN10, &aset);
5665        *status|=(DEC_Inexact | DEC_Rounded); /* is inexact  */
5666        break;}
5667      if (rhs->lsu[0]==2 && rhs->digits==1) { /* ln(2)  */
5668        aset=*set; aset.round=DEC_ROUND_HALF_EVEN;
5669        #define LN2 "0.6931471805599453094172321214581765680755"
5670        uprv_decNumberFromString(res, LN2, &aset);
5671        *status|=(DEC_Inexact | DEC_Rounded);
5672        break;}
5673      } /* integer and short  */
5674
5675    /* Determine the working precision.  This is normally the  */
5676    /* requested precision + 2, with a minimum of 9.  However, if  */
5677    /* the rhs is 'over-precise' then allow for all its digits to  */
5678    /* potentially participate (consider an rhs where all the excess  */
5679    /* digits are 9s) so in this case use rhs->digits+2.  */
5680    p=MAXI(rhs->digits, MAXI(set->digits, 7))+2;
5681
5682    /* Allocate space for the accumulator and the high-precision  */
5683    /* adjustment calculator, if necessary.  The accumulator must  */
5684    /* be able to hold p digits, and the adjustment up to  */
5685    /* rhs->digits+p digits.  They are also made big enough for 16  */
5686    /* digits so that they can be used for calculating the initial  */
5687    /* estimate.  */
5688    needbytes=sizeof(decNumber)+(D2U(MAXI(p,16))-1)*sizeof(Unit);
5689    if (needbytes>sizeof(bufa)) {     /* need malloc space  */
5690      allocbufa=(decNumber *)malloc(needbytes);
5691      if (allocbufa==NULL) {          /* hopeless -- abandon  */
5692        *status|=DEC_Insufficient_storage;
5693        break;}
5694      a=allocbufa;                    /* use the allocated space  */
5695      }
5696    pp=p+rhs->digits;
5697    needbytes=sizeof(decNumber)+(D2U(MAXI(pp,16))-1)*sizeof(Unit);
5698    if (needbytes>sizeof(bufb)) {     /* need malloc space  */
5699      allocbufb=(decNumber *)malloc(needbytes);
5700      if (allocbufb==NULL) {          /* hopeless -- abandon  */
5701        *status|=DEC_Insufficient_storage;
5702        break;}
5703      b=allocbufb;                    /* use the allocated space  */
5704      }
5705
5706    /* Prepare an initial estimate in acc. Calculate this by  */
5707    /* considering the coefficient of x to be a normalized fraction,  */
5708    /* f, with the decimal point at far left and multiplied by  */
5709    /* 10**r.  Then, rhs=f*10**r and 0.1<=f<1, and  */
5710    /*   ln(x) = ln(f) + ln(10)*r  */
5711    /* Get the initial estimate for ln(f) from a small lookup  */
5712    /* table (see above) indexed by the first two digits of f,  */
5713    /* truncated.  */
5714
5715    uprv_decContextDefault(&aset, DEC_INIT_DECIMAL64); /* 16-digit extended  */
5716    r=rhs->exponent+rhs->digits;        /* 'normalised' exponent  */
5717    uprv_decNumberFromInt32(a, r);           /* a=r  */
5718    uprv_decNumberFromInt32(b, 2302585);     /* b=ln(10) (2.302585)  */
5719    b->exponent=-6;                     /*  ..  */
5720    decMultiplyOp(a, a, b, &aset, &ignore);  /* a=a*b  */
5721    /* now get top two digits of rhs into b by simple truncate and  */
5722    /* force to integer  */
5723    residue=0;                          /* (no residue)  */
5724    aset.digits=2; aset.round=DEC_ROUND_DOWN;
5725    decCopyFit(b, rhs, &aset, &residue, &ignore); /* copy & shorten  */
5726    b->exponent=0;                      /* make integer  */
5727    t=decGetInt(b);                     /* [cannot fail]  */
5728    if (t<10) t=X10(t);                 /* adjust single-digit b  */
5729    t=LNnn[t-10];                       /* look up ln(b)  */
5730    uprv_decNumberFromInt32(b, t>>2);        /* b=ln(b) coefficient  */
5731    b->exponent=-(t&3)-3;               /* set exponent  */
5732    b->bits=DECNEG;                     /* ln(0.10)->ln(0.99) always -ve  */
5733    aset.digits=16; aset.round=DEC_ROUND_HALF_EVEN; /* restore  */
5734    decAddOp(a, a, b, &aset, 0, &ignore); /* acc=a+b  */
5735    /* the initial estimate is now in a, with up to 4 digits correct.  */
5736    /* When rhs is at or near Nmax the estimate will be low, so we  */
5737    /* will approach it from below, avoiding overflow when calling exp.  */
5738
5739    uprv_decNumberZero(&numone); *numone.lsu=1;   /* constant 1 for adjustment  */
5740
5741    /* accumulator bounds are as requested (could underflow, but  */
5742    /* cannot overflow)  */
5743    aset.emax=set->emax;
5744    aset.emin=set->emin;
5745    aset.clamp=0;                       /* no concrete format  */
5746    /* set up a context to be used for the multiply and subtract  */
5747    bset=aset;
5748    bset.emax=DEC_MAX_MATH*2;           /* use double bounds for the  */
5749    bset.emin=-DEC_MAX_MATH*2;          /* adjustment calculation  */
5750                                        /* [see decExpOp call below]  */
5751    /* for each iteration double the number of digits to calculate,  */
5752    /* up to a maximum of p  */
5753    pp=9;                               /* initial precision  */
5754    /* [initially 9 as then the sequence starts 7+2, 16+2, and  */
5755    /* 34+2, which is ideal for standard-sized numbers]  */
5756    aset.digits=pp;                     /* working context  */
5757    bset.digits=pp+rhs->digits;         /* wider context  */
5758    for (;;) {                          /* iterate  */
5759      #if DECCHECK
5760      iterations++;
5761      if (iterations>24) break;         /* consider 9 * 2**24  */
5762      #endif
5763      /* calculate the adjustment (exp(-a)*x-1) into b.  This is a  */
5764      /* catastrophic subtraction but it really is the difference  */
5765      /* from 1 that is of interest.  */
5766      /* Use the internal entry point to Exp as it allows the double  */
5767      /* range for calculating exp(-a) when a is the tiniest subnormal.  */
5768      a->bits^=DECNEG;                  /* make -a  */
5769      decExpOp(b, a, &bset, &ignore);   /* b=exp(-a)  */
5770      a->bits^=DECNEG;                  /* restore sign of a  */
5771      /* now multiply by rhs and subtract 1, at the wider precision  */
5772      decMultiplyOp(b, b, rhs, &bset, &ignore);        /* b=b*rhs  */
5773      decAddOp(b, b, &numone, &bset, DECNEG, &ignore); /* b=b-1  */
5774
5775      /* the iteration ends when the adjustment cannot affect the  */
5776      /* result by >=0.5 ulp (at the requested digits), which  */
5777      /* is when its value is smaller than the accumulator by  */
5778      /* set->digits+1 digits (or it is zero) -- this is a looser  */
5779      /* requirement than for Exp because all that happens to the  */
5780      /* accumulator after this is the final rounding (but note that  */
5781      /* there must also be full precision in a, or a=0).  */
5782
5783      if (decNumberIsZero(b) ||
5784          (a->digits+a->exponent)>=(b->digits+b->exponent+set->digits+1)) {
5785        if (a->digits==p) break;
5786        if (decNumberIsZero(a)) {
5787          decCompareOp(&cmp, rhs, &numone, &aset, COMPARE, &ignore); /* rhs=1 ?  */
5788          if (cmp.lsu[0]==0) a->exponent=0;            /* yes, exact 0  */
5789           else *status|=(DEC_Inexact | DEC_Rounded);  /* no, inexact  */
5790          break;
5791          }
5792        /* force padding if adjustment has gone to 0 before full length  */
5793        if (decNumberIsZero(b)) b->exponent=a->exponent-p;
5794        }
5795
5796      /* not done yet ...  */
5797      decAddOp(a, a, b, &aset, 0, &ignore);  /* a=a+b for next estimate  */
5798      if (pp==p) continue;                   /* precision is at maximum  */
5799      /* lengthen the next calculation  */
5800      pp=pp*2;                               /* double precision  */
5801      if (pp>p) pp=p;                        /* clamp to maximum  */
5802      aset.digits=pp;                        /* working context  */
5803      bset.digits=pp+rhs->digits;            /* wider context  */
5804      } /* Newton's iteration  */
5805
5806    #if DECCHECK
5807    /* just a sanity check; remove the test to show always  */
5808    if (iterations>24)
5809      printf("Ln iterations=%ld, status=%08lx, p=%ld, d=%ld\n",
5810            (LI)iterations, (LI)*status, (LI)p, (LI)rhs->digits);
5811    #endif
5812
5813    /* Copy and round the result to res  */
5814    residue=1;                          /* indicate dirt to right  */
5815    if (ISZERO(a)) residue=0;           /* .. unless underflowed to 0  */
5816    aset.digits=set->digits;            /* [use default rounding]  */
5817    decCopyFit(res, a, &aset, &residue, status); /* copy & shorten  */
5818    decFinish(res, set, &residue, status);       /* cleanup/set flags  */
5819    } while(0);                         /* end protected  */
5820
5821  if (allocbufa!=NULL) free(allocbufa); /* drop any storage used  */
5822  if (allocbufb!=NULL) free(allocbufb); /* ..  */
5823  /* [status is handled by caller]  */
5824  return res;
5825  } /* decLnOp  */
5826#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ * 100 + __GNUC_MINOR__) >= 406))
5827#pragma GCC diagnostic pop
5828#endif
5829
5830/* ------------------------------------------------------------------ */
5831/* decQuantizeOp  -- force exponent to requested value                */
5832/*                                                                    */
5833/*   This computes C = op(A, B), where op adjusts the coefficient     */
5834/*   of C (by rounding or shifting) such that the exponent (-scale)   */
5835/*   of C has the value B or matches the exponent of B.               */
5836/*   The numerical value of C will equal A, except for the effects of */
5837/*   any rounding that occurred.                                      */
5838/*                                                                    */
5839/*   res is C, the result.  C may be A or B                           */
5840/*   lhs is A, the number to adjust                                   */
5841/*   rhs is B, the requested exponent                                 */
5842/*   set is the context                                               */
5843/*   quant is 1 for quantize or 0 for rescale                         */
5844/*   status is the status accumulator (this can be called without     */
5845/*          risk of control loss)                                     */
5846/*                                                                    */
5847/* C must have space for set->digits digits.                          */
5848/*                                                                    */
5849/* Unless there is an error or the result is infinite, the exponent   */
5850/* after the operation is guaranteed to be that requested.            */
5851/* ------------------------------------------------------------------ */
5852static decNumber * decQuantizeOp(decNumber *res, const decNumber *lhs,
5853                                 const decNumber *rhs, decContext *set,
5854                                 Flag quant, uInt *status) {
5855  #if DECSUBSET
5856  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
5857  decNumber *allocrhs=NULL;        /* .., rhs  */
5858  #endif
5859  const decNumber *inrhs=rhs;      /* save original rhs  */
5860  Int   reqdigits=set->digits;     /* requested DIGITS  */
5861  Int   reqexp;                    /* requested exponent [-scale]  */
5862  Int   residue=0;                 /* rounding residue  */
5863  Int   etiny=set->emin-(reqdigits-1);
5864
5865  #if DECCHECK
5866  if (decCheckOperands(res, lhs, rhs, set)) return res;
5867  #endif
5868
5869  do {                             /* protect allocated storage  */
5870    #if DECSUBSET
5871    if (!set->extended) {
5872      /* reduce operands and set lostDigits status, as needed  */
5873      if (lhs->digits>reqdigits) {
5874        alloclhs=decRoundOperand(lhs, set, status);
5875        if (alloclhs==NULL) break;
5876        lhs=alloclhs;
5877        }
5878      if (rhs->digits>reqdigits) { /* [this only checks lostDigits]  */
5879        allocrhs=decRoundOperand(rhs, set, status);
5880        if (allocrhs==NULL) break;
5881        rhs=allocrhs;
5882        }
5883      }
5884    #endif
5885    /* [following code does not require input rounding]  */
5886
5887    /* Handle special values  */
5888    if (SPECIALARGS) {
5889      /* NaNs get usual processing  */
5890      if (SPECIALARGS & (DECSNAN | DECNAN))
5891        decNaNs(res, lhs, rhs, set, status);
5892      /* one infinity but not both is bad  */
5893      else if ((lhs->bits ^ rhs->bits) & DECINF)
5894        *status|=DEC_Invalid_operation;
5895      /* both infinity: return lhs  */
5896      else uprv_decNumberCopy(res, lhs);          /* [nop if in place]  */
5897      break;
5898      }
5899
5900    /* set requested exponent  */
5901    if (quant) reqexp=inrhs->exponent;  /* quantize -- match exponents  */
5902     else {                             /* rescale -- use value of rhs  */
5903      /* Original rhs must be an integer that fits and is in range,  */
5904      /* which could be from -1999999997 to +999999999, thanks to  */
5905      /* subnormals  */
5906      reqexp=decGetInt(inrhs);               /* [cannot fail]  */
5907      }
5908
5909    #if DECSUBSET
5910    if (!set->extended) etiny=set->emin;     /* no subnormals  */
5911    #endif
5912
5913    if (reqexp==BADINT                       /* bad (rescale only) or ..  */
5914     || reqexp==BIGODD || reqexp==BIGEVEN    /* very big (ditto) or ..  */
5915     || (reqexp<etiny)                       /* < lowest  */
5916     || (reqexp>set->emax)) {                /* > emax  */
5917      *status|=DEC_Invalid_operation;
5918      break;}
5919
5920    /* the RHS has been processed, so it can be overwritten now if necessary  */
5921    if (ISZERO(lhs)) {                       /* zero coefficient unchanged  */
5922      uprv_decNumberCopy(res, lhs);               /* [nop if in place]  */
5923      res->exponent=reqexp;                  /* .. just set exponent  */
5924      #if DECSUBSET
5925      if (!set->extended) res->bits=0;       /* subset specification; no -0  */
5926      #endif
5927      }
5928     else {                                  /* non-zero lhs  */
5929      Int adjust=reqexp-lhs->exponent;       /* digit adjustment needed  */
5930      /* if adjusted coefficient will definitely not fit, give up now  */
5931      if ((lhs->digits-adjust)>reqdigits) {
5932        *status|=DEC_Invalid_operation;
5933        break;
5934        }
5935
5936      if (adjust>0) {                        /* increasing exponent  */
5937        /* this will decrease the length of the coefficient by adjust  */
5938        /* digits, and must round as it does so  */
5939        decContext workset;                  /* work  */
5940        workset=*set;                        /* clone rounding, etc.  */
5941        workset.digits=lhs->digits-adjust;   /* set requested length  */
5942        /* [note that the latter can be <1, here]  */
5943        decCopyFit(res, lhs, &workset, &residue, status); /* fit to result  */
5944        decApplyRound(res, &workset, residue, status);    /* .. and round  */
5945        residue=0;                                        /* [used]  */
5946        /* If just rounded a 999s case, exponent will be off by one;  */
5947        /* adjust back (after checking space), if so.  */
5948        if (res->exponent>reqexp) {
5949          /* re-check needed, e.g., for quantize(0.9999, 0.001) under  */
5950          /* set->digits==3  */
5951          if (res->digits==reqdigits) {      /* cannot shift by 1  */
5952            *status&=~(DEC_Inexact | DEC_Rounded); /* [clean these]  */
5953            *status|=DEC_Invalid_operation;
5954            break;
5955            }
5956          res->digits=decShiftToMost(res->lsu, res->digits, 1); /* shift  */
5957          res->exponent--;                   /* (re)adjust the exponent.  */
5958          }
5959        #if DECSUBSET
5960        if (ISZERO(res) && !set->extended) res->bits=0; /* subset; no -0  */
5961        #endif
5962        } /* increase  */
5963       else /* adjust<=0 */ {                /* decreasing or = exponent  */
5964        /* this will increase the length of the coefficient by -adjust  */
5965        /* digits, by adding zero or more trailing zeros; this is  */
5966        /* already checked for fit, above  */
5967        uprv_decNumberCopy(res, lhs);             /* [it will fit]  */
5968        /* if padding needed (adjust<0), add it now...  */
5969        if (adjust<0) {
5970          res->digits=decShiftToMost(res->lsu, res->digits, -adjust);
5971          res->exponent+=adjust;             /* adjust the exponent  */
5972          }
5973        } /* decrease  */
5974      } /* non-zero  */
5975
5976    /* Check for overflow [do not use Finalize in this case, as an  */
5977    /* overflow here is a "don't fit" situation]  */
5978    if (res->exponent>set->emax-res->digits+1) {  /* too big  */
5979      *status|=DEC_Invalid_operation;
5980      break;
5981      }
5982     else {
5983      decFinalize(res, set, &residue, status);    /* set subnormal flags  */
5984      *status&=~DEC_Underflow;          /* suppress Underflow [as per 754]  */
5985      }
5986    } while(0);                         /* end protected  */
5987
5988  #if DECSUBSET
5989  if (allocrhs!=NULL) free(allocrhs);   /* drop any storage used  */
5990  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
5991  #endif
5992  return res;
5993  } /* decQuantizeOp  */
5994
5995/* ------------------------------------------------------------------ */
5996/* decCompareOp -- compare, min, or max two Numbers                   */
5997/*                                                                    */
5998/*   This computes C = A ? B and carries out one of four operations:  */
5999/*     COMPARE    -- returns the signum (as a number) giving the      */
6000/*                   result of a comparison unless one or both        */
6001/*                   operands is a NaN (in which case a NaN results)  */
6002/*     COMPSIG    -- as COMPARE except that a quiet NaN raises        */
6003/*                   Invalid operation.                               */
6004/*     COMPMAX    -- returns the larger of the operands, using the    */
6005/*                   754 maxnum operation                             */
6006/*     COMPMAXMAG -- ditto, comparing absolute values                 */
6007/*     COMPMIN    -- the 754 minnum operation                         */
6008/*     COMPMINMAG -- ditto, comparing absolute values                 */
6009/*     COMTOTAL   -- returns the signum (as a number) giving the      */
6010/*                   result of a comparison using 754 total ordering  */
6011/*                                                                    */
6012/*   res is C, the result.  C may be A and/or B (e.g., X=X?X)         */
6013/*   lhs is A                                                         */
6014/*   rhs is B                                                         */
6015/*   set is the context                                               */
6016/*   op  is the operation flag                                        */
6017/*   status is the usual accumulator                                  */
6018/*                                                                    */
6019/* C must have space for one digit for COMPARE or set->digits for     */
6020/* COMPMAX, COMPMIN, COMPMAXMAG, or COMPMINMAG.                       */
6021/* ------------------------------------------------------------------ */
6022/* The emphasis here is on speed for common cases, and avoiding       */
6023/* coefficient comparison if possible.                                */
6024/* ------------------------------------------------------------------ */
6025static decNumber * decCompareOp(decNumber *res, const decNumber *lhs,
6026                         const decNumber *rhs, decContext *set,
6027                         Flag op, uInt *status) {
6028  #if DECSUBSET
6029  decNumber *alloclhs=NULL;        /* non-NULL if rounded lhs allocated  */
6030  decNumber *allocrhs=NULL;        /* .., rhs  */
6031  #endif
6032  Int   result=0;                  /* default result value  */
6033  uByte merged;                    /* work  */
6034
6035  #if DECCHECK
6036  if (decCheckOperands(res, lhs, rhs, set)) return res;
6037  #endif
6038
6039  do {                             /* protect allocated storage  */
6040    #if DECSUBSET
6041    if (!set->extended) {
6042      /* reduce operands and set lostDigits status, as needed  */
6043      if (lhs->digits>set->digits) {
6044        alloclhs=decRoundOperand(lhs, set, status);
6045        if (alloclhs==NULL) {result=BADINT; break;}
6046        lhs=alloclhs;
6047        }
6048      if (rhs->digits>set->digits) {
6049        allocrhs=decRoundOperand(rhs, set, status);
6050        if (allocrhs==NULL) {result=BADINT; break;}
6051        rhs=allocrhs;
6052        }
6053      }
6054    #endif
6055    /* [following code does not require input rounding]  */
6056
6057    /* If total ordering then handle differing signs 'up front'  */
6058    if (op==COMPTOTAL) {                /* total ordering  */
6059      if (decNumberIsNegative(lhs) & !decNumberIsNegative(rhs)) {
6060        result=-1;
6061        break;
6062        }
6063      if (!decNumberIsNegative(lhs) & decNumberIsNegative(rhs)) {
6064        result=+1;
6065        break;
6066        }
6067      }
6068
6069    /* handle NaNs specially; let infinities drop through  */
6070    /* This assumes sNaN (even just one) leads to NaN.  */
6071    merged=(lhs->bits | rhs->bits) & (DECSNAN | DECNAN);
6072    if (merged) {                       /* a NaN bit set  */
6073      if (op==COMPARE);                 /* result will be NaN  */
6074       else if (op==COMPSIG)            /* treat qNaN as sNaN  */
6075        *status|=DEC_Invalid_operation | DEC_sNaN;
6076       else if (op==COMPTOTAL) {        /* total ordering, always finite  */
6077        /* signs are known to be the same; compute the ordering here  */
6078        /* as if the signs are both positive, then invert for negatives  */
6079        if (!decNumberIsNaN(lhs)) result=-1;
6080         else if (!decNumberIsNaN(rhs)) result=+1;
6081         /* here if both NaNs  */
6082         else if (decNumberIsSNaN(lhs) && decNumberIsQNaN(rhs)) result=-1;
6083         else if (decNumberIsQNaN(lhs) && decNumberIsSNaN(rhs)) result=+1;
6084         else { /* both NaN or both sNaN  */
6085          /* now it just depends on the payload  */
6086          result=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6087                                rhs->lsu, D2U(rhs->digits), 0);
6088          /* [Error not possible, as these are 'aligned']  */
6089          } /* both same NaNs  */
6090        if (decNumberIsNegative(lhs)) result=-result;
6091        break;
6092        } /* total order  */
6093
6094       else if (merged & DECSNAN);           /* sNaN -> qNaN  */
6095       else { /* here if MIN or MAX and one or two quiet NaNs  */
6096        /* min or max -- 754 rules ignore single NaN  */
6097        if (!decNumberIsNaN(lhs) || !decNumberIsNaN(rhs)) {
6098          /* just one NaN; force choice to be the non-NaN operand  */
6099          op=COMPMAX;
6100          if (lhs->bits & DECNAN) result=-1; /* pick rhs  */
6101                             else result=+1; /* pick lhs  */
6102          break;
6103          }
6104        } /* max or min  */
6105      op=COMPNAN;                            /* use special path  */
6106      decNaNs(res, lhs, rhs, set, status);   /* propagate NaN  */
6107      break;
6108      }
6109    /* have numbers  */
6110    if (op==COMPMAXMAG || op==COMPMINMAG) result=decCompare(lhs, rhs, 1);
6111     else result=decCompare(lhs, rhs, 0);    /* sign matters  */
6112    } while(0);                              /* end protected  */
6113
6114  if (result==BADINT) *status|=DEC_Insufficient_storage; /* rare  */
6115   else {
6116    if (op==COMPARE || op==COMPSIG ||op==COMPTOTAL) { /* returning signum  */
6117      if (op==COMPTOTAL && result==0) {
6118        /* operands are numerically equal or same NaN (and same sign,  */
6119        /* tested first); if identical, leave result 0  */
6120        if (lhs->exponent!=rhs->exponent) {
6121          if (lhs->exponent<rhs->exponent) result=-1;
6122           else result=+1;
6123          if (decNumberIsNegative(lhs)) result=-result;
6124          } /* lexp!=rexp  */
6125        } /* total-order by exponent  */
6126      uprv_decNumberZero(res);               /* [always a valid result]  */
6127      if (result!=0) {                  /* must be -1 or +1  */
6128        *res->lsu=1;
6129        if (result<0) res->bits=DECNEG;
6130        }
6131      }
6132     else if (op==COMPNAN);             /* special, drop through  */
6133     else {                             /* MAX or MIN, non-NaN result  */
6134      Int residue=0;                    /* rounding accumulator  */
6135      /* choose the operand for the result  */
6136      const decNumber *choice;
6137      if (result==0) { /* operands are numerically equal  */
6138        /* choose according to sign then exponent (see 754)  */
6139        uByte slhs=(lhs->bits & DECNEG);
6140        uByte srhs=(rhs->bits & DECNEG);
6141        #if DECSUBSET
6142        if (!set->extended) {           /* subset: force left-hand  */
6143          op=COMPMAX;
6144          result=+1;
6145          }
6146        else
6147        #endif
6148        if (slhs!=srhs) {          /* signs differ  */
6149          if (slhs) result=-1;     /* rhs is max  */
6150               else result=+1;     /* lhs is max  */
6151          }
6152         else if (slhs && srhs) {  /* both negative  */
6153          if (lhs->exponent<rhs->exponent) result=+1;
6154                                      else result=-1;
6155          /* [if equal, use lhs, technically identical]  */
6156          }
6157         else {                    /* both positive  */
6158          if (lhs->exponent>rhs->exponent) result=+1;
6159                                      else result=-1;
6160          /* [ditto]  */
6161          }
6162        } /* numerically equal  */
6163      /* here result will be non-0; reverse if looking for MIN  */
6164      if (op==COMPMIN || op==COMPMINMAG) result=-result;
6165      choice=(result>0 ? lhs : rhs);    /* choose  */
6166      /* copy chosen to result, rounding if need be  */
6167      decCopyFit(res, choice, set, &residue, status);
6168      decFinish(res, set, &residue, status);
6169      }
6170    }
6171  #if DECSUBSET
6172  if (allocrhs!=NULL) free(allocrhs);   /* free any storage used  */
6173  if (alloclhs!=NULL) free(alloclhs);   /* ..  */
6174  #endif
6175  return res;
6176  } /* decCompareOp  */
6177
6178/* ------------------------------------------------------------------ */
6179/* decCompare -- compare two decNumbers by numerical value            */
6180/*                                                                    */
6181/*  This routine compares A ? B without altering them.                */
6182/*                                                                    */
6183/*  Arg1 is A, a decNumber which is not a NaN                         */
6184/*  Arg2 is B, a decNumber which is not a NaN                         */
6185/*  Arg3 is 1 for a sign-independent compare, 0 otherwise             */
6186/*                                                                    */
6187/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6188/*  (the only possible failure is an allocation error)                */
6189/* ------------------------------------------------------------------ */
6190static Int decCompare(const decNumber *lhs, const decNumber *rhs,
6191                      Flag abs_c) {
6192  Int   result;                    /* result value  */
6193  Int   sigr;                      /* rhs signum  */
6194  Int   compare;                   /* work  */
6195
6196  result=1;                                  /* assume signum(lhs)  */
6197  if (ISZERO(lhs)) result=0;
6198  if (abs_c) {
6199    if (ISZERO(rhs)) return result;          /* LHS wins or both 0  */
6200    /* RHS is non-zero  */
6201    if (result==0) return -1;                /* LHS is 0; RHS wins  */
6202    /* [here, both non-zero, result=1]  */
6203    }
6204   else {                                    /* signs matter  */
6205    if (result && decNumberIsNegative(lhs)) result=-1;
6206    sigr=1;                                  /* compute signum(rhs)  */
6207    if (ISZERO(rhs)) sigr=0;
6208     else if (decNumberIsNegative(rhs)) sigr=-1;
6209    if (result > sigr) return +1;            /* L > R, return 1  */
6210    if (result < sigr) return -1;            /* L < R, return -1  */
6211    if (result==0) return 0;                   /* both 0  */
6212    }
6213
6214  /* signums are the same; both are non-zero  */
6215  if ((lhs->bits | rhs->bits) & DECINF) {    /* one or more infinities  */
6216    if (decNumberIsInfinite(rhs)) {
6217      if (decNumberIsInfinite(lhs)) result=0;/* both infinite  */
6218       else result=-result;                  /* only rhs infinite  */
6219      }
6220    return result;
6221    }
6222  /* must compare the coefficients, allowing for exponents  */
6223  if (lhs->exponent>rhs->exponent) {         /* LHS exponent larger  */
6224    /* swap sides, and sign  */
6225    const decNumber *temp=lhs;
6226    lhs=rhs;
6227    rhs=temp;
6228    result=-result;
6229    }
6230  compare=decUnitCompare(lhs->lsu, D2U(lhs->digits),
6231                         rhs->lsu, D2U(rhs->digits),
6232                         rhs->exponent-lhs->exponent);
6233  if (compare!=BADINT) compare*=result;      /* comparison succeeded  */
6234  return compare;
6235  } /* decCompare  */
6236
6237/* ------------------------------------------------------------------ */
6238/* decUnitCompare -- compare two >=0 integers in Unit arrays          */
6239/*                                                                    */
6240/*  This routine compares A ? B*10**E where A and B are unit arrays   */
6241/*  A is a plain integer                                              */
6242/*  B has an exponent of E (which must be non-negative)               */
6243/*                                                                    */
6244/*  Arg1 is A first Unit (lsu)                                        */
6245/*  Arg2 is A length in Units                                         */
6246/*  Arg3 is B first Unit (lsu)                                        */
6247/*  Arg4 is B length in Units                                         */
6248/*  Arg5 is E (0 if the units are aligned)                            */
6249/*                                                                    */
6250/*  returns -1, 0, or 1 for A<B, A==B, or A>B, or BADINT if failure   */
6251/*  (the only possible failure is an allocation error, which can      */
6252/*  only occur if E!=0)                                               */
6253/* ------------------------------------------------------------------ */
6254static Int decUnitCompare(const Unit *a, Int alength,
6255                          const Unit *b, Int blength, Int exp) {
6256  Unit  *acc;                      /* accumulator for result  */
6257  Unit  accbuff[SD2U(DECBUFFER*2+1)]; /* local buffer  */
6258  Unit  *allocacc=NULL;            /* -> allocated acc buffer, iff allocated  */
6259  Int   accunits, need;            /* units in use or needed for acc  */
6260  const Unit *l, *r, *u;           /* work  */
6261  Int   expunits, exprem, result;  /* ..  */
6262
6263  if (exp==0) {                    /* aligned; fastpath  */
6264    if (alength>blength) return 1;
6265    if (alength<blength) return -1;
6266    /* same number of units in both -- need unit-by-unit compare  */
6267    l=a+alength-1;
6268    r=b+alength-1;
6269    for (;l>=a; l--, r--) {
6270      if (*l>*r) return 1;
6271      if (*l<*r) return -1;
6272      }
6273    return 0;                      /* all units match  */
6274    } /* aligned  */
6275
6276  /* Unaligned.  If one is >1 unit longer than the other, padded  */
6277  /* approximately, then can return easily  */
6278  if (alength>blength+(Int)D2U(exp)) return 1;
6279  if (alength+1<blength+(Int)D2U(exp)) return -1;
6280
6281  /* Need to do a real subtract.  For this, a result buffer is needed  */
6282  /* even though only the sign is of interest.  Its length needs  */
6283  /* to be the larger of alength and padded blength, +2  */
6284  need=blength+D2U(exp);                /* maximum real length of B  */
6285  if (need<alength) need=alength;
6286  need+=2;
6287  acc=accbuff;                          /* assume use local buffer  */
6288  if (need*sizeof(Unit)>sizeof(accbuff)) {
6289    allocacc=(Unit *)malloc(need*sizeof(Unit));
6290    if (allocacc==NULL) return BADINT;  /* hopeless -- abandon  */
6291    acc=allocacc;
6292    }
6293  /* Calculate units and remainder from exponent.  */
6294  expunits=exp/DECDPUN;
6295  exprem=exp%DECDPUN;
6296  /* subtract [A+B*(-m)]  */
6297  accunits=decUnitAddSub(a, alength, b, blength, expunits, acc,
6298                         -(Int)powers[exprem]);
6299  /* [UnitAddSub result may have leading zeros, even on zero]  */
6300  if (accunits<0) result=-1;            /* negative result  */
6301   else {                               /* non-negative result  */
6302    /* check units of the result before freeing any storage  */
6303    for (u=acc; u<acc+accunits-1 && *u==0;) u++;
6304    result=(*u==0 ? 0 : +1);
6305    }
6306  /* clean up and return the result  */
6307  if (allocacc!=NULL) free(allocacc);   /* drop any storage used  */
6308  return result;
6309  } /* decUnitCompare  */
6310
6311/* ------------------------------------------------------------------ */
6312/* decUnitAddSub -- add or subtract two >=0 integers in Unit arrays   */
6313/*                                                                    */
6314/*  This routine performs the calculation:                            */
6315/*                                                                    */
6316/*  C=A+(B*M)                                                         */
6317/*                                                                    */
6318/*  Where M is in the range -DECDPUNMAX through +DECDPUNMAX.          */
6319/*                                                                    */
6320/*  A may be shorter or longer than B.                                */
6321/*                                                                    */
6322/*  Leading zeros are not removed after a calculation.  The result is */
6323/*  either the same length as the longer of A and B (adding any       */
6324/*  shift), or one Unit longer than that (if a Unit carry occurred).  */
6325/*                                                                    */
6326/*  A and B content are not altered unless C is also A or B.          */
6327/*  C may be the same array as A or B, but only if no zero padding is */
6328/*  requested (that is, C may be B only if bshift==0).                */
6329/*  C is filled from the lsu; only those units necessary to complete  */
6330/*  the calculation are referenced.                                   */
6331/*                                                                    */
6332/*  Arg1 is A first Unit (lsu)                                        */
6333/*  Arg2 is A length in Units                                         */
6334/*  Arg3 is B first Unit (lsu)                                        */
6335/*  Arg4 is B length in Units                                         */
6336/*  Arg5 is B shift in Units  (>=0; pads with 0 units if positive)    */
6337/*  Arg6 is C first Unit (lsu)                                        */
6338/*  Arg7 is M, the multiplier                                         */
6339/*                                                                    */
6340/*  returns the count of Units written to C, which will be non-zero   */
6341/*  and negated if the result is negative.  That is, the sign of the  */
6342/*  returned Int is the sign of the result (positive for zero) and    */
6343/*  the absolute value of the Int is the count of Units.              */
6344/*                                                                    */
6345/*  It is the caller's responsibility to make sure that C size is     */
6346/*  safe, allowing space if necessary for a one-Unit carry.           */
6347/*                                                                    */
6348/*  This routine is severely performance-critical; *any* change here  */
6349/*  must be measured (timed) to assure no performance degradation.    */
6350/*  In particular, trickery here tends to be counter-productive, as   */
6351/*  increased complexity of code hurts register optimizations on      */
6352/*  register-poor architectures.  Avoiding divisions is nearly        */
6353/*  always a Good Idea, however.                                      */
6354/*                                                                    */
6355/* Special thanks to Rick McGuire (IBM Cambridge, MA) and Dave Clark  */
6356/* (IBM Warwick, UK) for some of the ideas used in this routine.      */
6357/* ------------------------------------------------------------------ */
6358static Int decUnitAddSub(const Unit *a, Int alength,
6359                         const Unit *b, Int blength, Int bshift,
6360                         Unit *c, Int m) {
6361  const Unit *alsu=a;              /* A lsu [need to remember it]  */
6362  Unit *clsu=c;                    /* C ditto  */
6363  Unit *minC;                      /* low water mark for C  */
6364  Unit *maxC;                      /* high water mark for C  */
6365  eInt carry=0;                    /* carry integer (could be Long)  */
6366  Int  add;                        /* work  */
6367  #if DECDPUN<=4                   /* myriadal, millenary, etc.  */
6368  Int  est;                        /* estimated quotient  */
6369  #endif
6370
6371  #if DECTRACE
6372  if (alength<1 || blength<1)
6373    printf("decUnitAddSub: alen blen m %ld %ld [%ld]\n", alength, blength, m);
6374  #endif
6375
6376  maxC=c+alength;                  /* A is usually the longer  */
6377  minC=c+blength;                  /* .. and B the shorter  */
6378  if (bshift!=0) {                 /* B is shifted; low As copy across  */
6379    minC+=bshift;
6380    /* if in place [common], skip copy unless there's a gap [rare]  */
6381    if (a==c && bshift<=alength) {
6382      c+=bshift;
6383      a+=bshift;
6384      }
6385     else for (; c<clsu+bshift; a++, c++) {  /* copy needed  */
6386      if (a<alsu+alength) *c=*a;
6387       else *c=0;
6388      }
6389    }
6390  if (minC>maxC) { /* swap  */
6391    Unit *hold=minC;
6392    minC=maxC;
6393    maxC=hold;
6394    }
6395
6396  /* For speed, do the addition as two loops; the first where both A  */
6397  /* and B contribute, and the second (if necessary) where only one or  */
6398  /* other of the numbers contribute.  */
6399  /* Carry handling is the same (i.e., duplicated) in each case.  */
6400  for (; c<minC; c++) {
6401    carry+=*a;
6402    a++;
6403    carry+=((eInt)*b)*m;                /* [special-casing m=1/-1  */
6404    b++;                                /* here is not a win]  */
6405    /* here carry is new Unit of digits; it could be +ve or -ve  */
6406    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6407      *c=(Unit)carry;
6408      carry=0;
6409      continue;
6410      }
6411    #if DECDPUN==4                           /* use divide-by-multiply  */
6412      if (carry>=0) {
6413        est=(((ueInt)carry>>11)*53687)>>18;
6414        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6415        carry=est;                           /* likely quotient [89%]  */
6416        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6417        carry++;
6418        *c-=DECDPUNMAX+1;
6419        continue;
6420        }
6421      /* negative case  */
6422      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6423      est=(((ueInt)carry>>11)*53687)>>18;
6424      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6425      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6426      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6427      carry++;
6428      *c-=DECDPUNMAX+1;
6429    #elif DECDPUN==3
6430      if (carry>=0) {
6431        est=(((ueInt)carry>>3)*16777)>>21;
6432        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6433        carry=est;                           /* likely quotient [99%]  */
6434        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6435        carry++;
6436        *c-=DECDPUNMAX+1;
6437        continue;
6438        }
6439      /* negative case  */
6440      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6441      est=(((ueInt)carry>>3)*16777)>>21;
6442      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6443      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6444      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6445      carry++;
6446      *c-=DECDPUNMAX+1;
6447    #elif DECDPUN<=2
6448      /* Can use QUOT10 as carry <= 4 digits  */
6449      if (carry>=0) {
6450        est=QUOT10(carry, DECDPUN);
6451        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6452        carry=est;                           /* quotient  */
6453        continue;
6454        }
6455      /* negative case  */
6456      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6457      est=QUOT10(carry, DECDPUN);
6458      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6459      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6460    #else
6461      /* remainder operator is undefined if negative, so must test  */
6462      if ((ueInt)carry<(DECDPUNMAX+1)*2) {   /* fastpath carry +1  */
6463        *c=(Unit)(carry-(DECDPUNMAX+1));     /* [helps additions]  */
6464        carry=1;
6465        continue;
6466        }
6467      if (carry>=0) {
6468        *c=(Unit)(carry%(DECDPUNMAX+1));
6469        carry=carry/(DECDPUNMAX+1);
6470        continue;
6471        }
6472      /* negative case  */
6473      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6474      *c=(Unit)(carry%(DECDPUNMAX+1));
6475      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6476    #endif
6477    } /* c  */
6478
6479  /* now may have one or other to complete  */
6480  /* [pretest to avoid loop setup/shutdown]  */
6481  if (c<maxC) for (; c<maxC; c++) {
6482    if (a<alsu+alength) {               /* still in A  */
6483      carry+=*a;
6484      a++;
6485      }
6486     else {                             /* inside B  */
6487      carry+=((eInt)*b)*m;
6488      b++;
6489      }
6490    /* here carry is new Unit of digits; it could be +ve or -ve and  */
6491    /* magnitude up to DECDPUNMAX squared  */
6492    if ((ueInt)carry<=DECDPUNMAX) {     /* fastpath 0-DECDPUNMAX  */
6493      *c=(Unit)carry;
6494      carry=0;
6495      continue;
6496      }
6497    /* result for this unit is negative or >DECDPUNMAX  */
6498    #if DECDPUN==4                           /* use divide-by-multiply  */
6499      if (carry>=0) {
6500        est=(((ueInt)carry>>11)*53687)>>18;
6501        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6502        carry=est;                           /* likely quotient [79.7%]  */
6503        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6504        carry++;
6505        *c-=DECDPUNMAX+1;
6506        continue;
6507        }
6508      /* negative case  */
6509      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6510      est=(((ueInt)carry>>11)*53687)>>18;
6511      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6512      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6513      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6514      carry++;
6515      *c-=DECDPUNMAX+1;
6516    #elif DECDPUN==3
6517      if (carry>=0) {
6518        est=(((ueInt)carry>>3)*16777)>>21;
6519        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6520        carry=est;                           /* likely quotient [99%]  */
6521        if (*c<DECDPUNMAX+1) continue;       /* estimate was correct  */
6522        carry++;
6523        *c-=DECDPUNMAX+1;
6524        continue;
6525        }
6526      /* negative case  */
6527      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6528      est=(((ueInt)carry>>3)*16777)>>21;
6529      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6530      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6531      if (*c<DECDPUNMAX+1) continue;         /* was OK  */
6532      carry++;
6533      *c-=DECDPUNMAX+1;
6534    #elif DECDPUN<=2
6535      if (carry>=0) {
6536        est=QUOT10(carry, DECDPUN);
6537        *c=(Unit)(carry-est*(DECDPUNMAX+1)); /* remainder  */
6538        carry=est;                           /* quotient  */
6539        continue;
6540        }
6541      /* negative case  */
6542      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6543      est=QUOT10(carry, DECDPUN);
6544      *c=(Unit)(carry-est*(DECDPUNMAX+1));
6545      carry=est-(DECDPUNMAX+1);              /* correctly negative  */
6546    #else
6547      if ((ueInt)carry<(DECDPUNMAX+1)*2){    /* fastpath carry 1  */
6548        *c=(Unit)(carry-(DECDPUNMAX+1));
6549        carry=1;
6550        continue;
6551        }
6552      /* remainder operator is undefined if negative, so must test  */
6553      if (carry>=0) {
6554        *c=(Unit)(carry%(DECDPUNMAX+1));
6555        carry=carry/(DECDPUNMAX+1);
6556        continue;
6557        }
6558      /* negative case  */
6559      carry=carry+(eInt)(DECDPUNMAX+1)*(DECDPUNMAX+1); /* make positive  */
6560      *c=(Unit)(carry%(DECDPUNMAX+1));
6561      carry=carry/(DECDPUNMAX+1)-(DECDPUNMAX+1);
6562    #endif
6563    } /* c  */
6564
6565  /* OK, all A and B processed; might still have carry or borrow  */
6566  /* return number of Units in the result, negated if a borrow  */
6567  if (carry==0) return c-clsu;     /* no carry, so no more to do  */
6568  if (carry>0) {                   /* positive carry  */
6569    *c=(Unit)carry;                /* place as new unit  */
6570    c++;                           /* ..  */
6571    return c-clsu;
6572    }
6573  /* -ve carry: it's a borrow; complement needed  */
6574  add=1;                           /* temporary carry...  */
6575  for (c=clsu; c<maxC; c++) {
6576    add=DECDPUNMAX+add-*c;
6577    if (add<=DECDPUNMAX) {
6578      *c=(Unit)add;
6579      add=0;
6580      }
6581     else {
6582      *c=0;
6583      add=1;
6584      }
6585    }
6586  /* add an extra unit iff it would be non-zero  */
6587  #if DECTRACE
6588    printf("UAS borrow: add %ld, carry %ld\n", add, carry);
6589  #endif
6590  if ((add-carry-1)!=0) {
6591    *c=(Unit)(add-carry-1);
6592    c++;                      /* interesting, include it  */
6593    }
6594  return clsu-c;              /* -ve result indicates borrowed  */
6595  } /* decUnitAddSub  */
6596
6597/* ------------------------------------------------------------------ */
6598/* decTrim -- trim trailing zeros or normalize                        */
6599/*                                                                    */
6600/*   dn is the number to trim or normalize                            */
6601/*   set is the context to use to check for clamp                     */
6602/*   all is 1 to remove all trailing zeros, 0 for just fraction ones  */
6603/*   noclamp is 1 to unconditional (unclamped) trim                   */
6604/*   dropped returns the number of discarded trailing zeros           */
6605/*   returns dn                                                       */
6606/*                                                                    */
6607/* If clamp is set in the context then the number of zeros trimmed    */
6608/* may be limited if the exponent is high.                            */
6609/* All fields are updated as required.  This is a utility operation,  */
6610/* so special values are unchanged and no error is possible.          */
6611/* ------------------------------------------------------------------ */
6612static decNumber * decTrim(decNumber *dn, decContext *set, Flag all,
6613                           Flag noclamp, Int *dropped) {
6614  Int   d, exp;                    /* work  */
6615  uInt  cut;                       /* ..  */
6616  Unit  *up;                       /* -> current Unit  */
6617
6618  #if DECCHECK
6619  if (decCheckOperands(dn, DECUNUSED, DECUNUSED, DECUNCONT)) return dn;
6620  #endif
6621
6622  *dropped=0;                           /* assume no zeros dropped  */
6623  if ((dn->bits & DECSPECIAL)           /* fast exit if special ..  */
6624    || (*dn->lsu & 0x01)) return dn;    /* .. or odd  */
6625  if (ISZERO(dn)) {                     /* .. or 0  */
6626    dn->exponent=0;                     /* (sign is preserved)  */
6627    return dn;
6628    }
6629
6630  /* have a finite number which is even  */
6631  exp=dn->exponent;
6632  cut=1;                           /* digit (1-DECDPUN) in Unit  */
6633  up=dn->lsu;                      /* -> current Unit  */
6634  for (d=0; d<dn->digits-1; d++) { /* [don't strip the final digit]  */
6635    /* slice by powers  */
6636    #if DECDPUN<=4
6637      uInt quot=QUOT10(*up, cut);
6638      if ((*up-quot*powers[cut])!=0) break;  /* found non-0 digit  */
6639    #else
6640      if (*up%powers[cut]!=0) break;         /* found non-0 digit  */
6641    #endif
6642    /* have a trailing 0  */
6643    if (!all) {                    /* trimming  */
6644      /* [if exp>0 then all trailing 0s are significant for trim]  */
6645      if (exp<=0) {                /* if digit might be significant  */
6646        if (exp==0) break;         /* then quit  */
6647        exp++;                     /* next digit might be significant  */
6648        }
6649      }
6650    cut++;                         /* next power  */
6651    if (cut>DECDPUN) {             /* need new Unit  */
6652      up++;
6653      cut=1;
6654      }
6655    } /* d  */
6656  if (d==0) return dn;             /* none to drop  */
6657
6658  /* may need to limit drop if clamping  */
6659  if (set->clamp && !noclamp) {
6660    Int maxd=set->emax-set->digits+1-dn->exponent;
6661    if (maxd<=0) return dn;        /* nothing possible  */
6662    if (d>maxd) d=maxd;
6663    }
6664
6665  /* effect the drop  */
6666  decShiftToLeast(dn->lsu, D2U(dn->digits), d);
6667  dn->exponent+=d;                 /* maintain numerical value  */
6668  dn->digits-=d;                   /* new length  */
6669  *dropped=d;                      /* report the count  */
6670  return dn;
6671  } /* decTrim  */
6672
6673/* ------------------------------------------------------------------ */
6674/* decReverse -- reverse a Unit array in place                        */
6675/*                                                                    */
6676/*   ulo    is the start of the array                                 */
6677/*   uhi    is the end of the array (highest Unit to include)         */
6678/*                                                                    */
6679/* The units ulo through uhi are reversed in place (if the number     */
6680/* of units is odd, the middle one is untouched).  Note that the      */
6681/* digit(s) in each unit are unaffected.                              */
6682/* ------------------------------------------------------------------ */
6683static void decReverse(Unit *ulo, Unit *uhi) {
6684  Unit temp;
6685  for (; ulo<uhi; ulo++, uhi--) {
6686    temp=*ulo;
6687    *ulo=*uhi;
6688    *uhi=temp;
6689    }
6690  return;
6691  } /* decReverse  */
6692
6693/* ------------------------------------------------------------------ */
6694/* decShiftToMost -- shift digits in array towards most significant   */
6695/*                                                                    */
6696/*   uar    is the array                                              */
6697/*   digits is the count of digits in use in the array                */
6698/*   shift  is the number of zeros to pad with (least significant);   */
6699/*     it must be zero or positive                                    */
6700/*                                                                    */
6701/*   returns the new length of the integer in the array, in digits    */
6702/*                                                                    */
6703/* No overflow is permitted (that is, the uar array must be known to  */
6704/* be large enough to hold the result, after shifting).               */
6705/* ------------------------------------------------------------------ */
6706static Int decShiftToMost(Unit *uar, Int digits, Int shift) {
6707  Unit  *target, *source, *first;  /* work  */
6708  Int   cut;                       /* odd 0's to add  */
6709  uInt  next;                      /* work  */
6710
6711  if (shift==0) return digits;     /* [fastpath] nothing to do  */
6712  if ((digits+shift)<=DECDPUN) {   /* [fastpath] single-unit case  */
6713    *uar=(Unit)(*uar*powers[shift]);
6714    return digits+shift;
6715    }
6716
6717  next=0;                          /* all paths  */
6718  source=uar+D2U(digits)-1;        /* where msu comes from  */
6719  target=source+D2U(shift);        /* where upper part of first cut goes  */
6720  cut=DECDPUN-MSUDIGITS(shift);    /* where to slice  */
6721  if (cut==0) {                    /* unit-boundary case  */
6722    for (; source>=uar; source--, target--) *target=*source;
6723    }
6724   else {
6725    first=uar+D2U(digits+shift)-1; /* where msu of source will end up  */
6726    for (; source>=uar; source--, target--) {
6727      /* split the source Unit and accumulate remainder for next  */
6728      #if DECDPUN<=4
6729        uInt quot=QUOT10(*source, cut);
6730        uInt rem=*source-quot*powers[cut];
6731        next+=quot;
6732      #else
6733        uInt rem=*source%powers[cut];
6734        next+=*source/powers[cut];
6735      #endif
6736      if (target<=first) *target=(Unit)next;   /* write to target iff valid  */
6737      next=rem*powers[DECDPUN-cut];            /* save remainder for next Unit  */
6738      }
6739    } /* shift-move  */
6740
6741  /* propagate any partial unit to one below and clear the rest  */
6742  for (; target>=uar; target--) {
6743    *target=(Unit)next;
6744    next=0;
6745    }
6746  return digits+shift;
6747  } /* decShiftToMost  */
6748
6749/* ------------------------------------------------------------------ */
6750/* decShiftToLeast -- shift digits in array towards least significant */
6751/*                                                                    */
6752/*   uar   is the array                                               */
6753/*   units is length of the array, in units                           */
6754/*   shift is the number of digits to remove from the lsu end; it     */
6755/*     must be zero or positive and <= than units*DECDPUN.            */
6756/*                                                                    */
6757/*   returns the new length of the integer in the array, in units     */
6758/*                                                                    */
6759/* Removed digits are discarded (lost).  Units not required to hold   */
6760/* the final result are unchanged.                                    */
6761/* ------------------------------------------------------------------ */
6762static Int decShiftToLeast(Unit *uar, Int units, Int shift) {
6763  Unit  *target, *up;              /* work  */
6764  Int   cut, count;                /* work  */
6765  Int   quot, rem;                 /* for division  */
6766
6767  if (shift==0) return units;      /* [fastpath] nothing to do  */
6768  if (shift==units*DECDPUN) {      /* [fastpath] little to do  */
6769    *uar=0;                        /* all digits cleared gives zero  */
6770    return 1;                      /* leaves just the one  */
6771    }
6772
6773  target=uar;                      /* both paths  */
6774  cut=MSUDIGITS(shift);
6775  if (cut==DECDPUN) {              /* unit-boundary case; easy  */
6776    up=uar+D2U(shift);
6777    for (; up<uar+units; target++, up++) *target=*up;
6778    return target-uar;
6779    }
6780
6781  /* messier  */
6782  up=uar+D2U(shift-cut);           /* source; correct to whole Units  */
6783  count=units*DECDPUN-shift;       /* the maximum new length  */
6784  #if DECDPUN<=4
6785    quot=QUOT10(*up, cut);
6786  #else
6787    quot=*up/powers[cut];
6788  #endif
6789  for (; ; target++) {
6790    *target=(Unit)quot;
6791    count-=(DECDPUN-cut);
6792    if (count<=0) break;
6793    up++;
6794    quot=*up;
6795    #if DECDPUN<=4
6796      quot=QUOT10(quot, cut);
6797      rem=*up-quot*powers[cut];
6798    #else
6799      rem=quot%powers[cut];
6800      quot=quot/powers[cut];
6801    #endif
6802    *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
6803    count-=cut;
6804    if (count<=0) break;
6805    }
6806  return target-uar+1;
6807  } /* decShiftToLeast  */
6808
6809#if DECSUBSET
6810/* ------------------------------------------------------------------ */
6811/* decRoundOperand -- round an operand  [used for subset only]        */
6812/*                                                                    */
6813/*   dn is the number to round (dn->digits is > set->digits)          */
6814/*   set is the relevant context                                      */
6815/*   status is the status accumulator                                 */
6816/*                                                                    */
6817/*   returns an allocated decNumber with the rounded result.          */
6818/*                                                                    */
6819/* lostDigits and other status may be set by this.                    */
6820/*                                                                    */
6821/* Since the input is an operand, it must not be modified.            */
6822/* Instead, return an allocated decNumber, rounded as required.       */
6823/* It is the caller's responsibility to free the allocated storage.   */
6824/*                                                                    */
6825/* If no storage is available then the result cannot be used, so NULL */
6826/* is returned.                                                       */
6827/* ------------------------------------------------------------------ */
6828static decNumber *decRoundOperand(const decNumber *dn, decContext *set,
6829                                  uInt *status) {
6830  decNumber *res;                       /* result structure  */
6831  uInt newstatus=0;                     /* status from round  */
6832  Int  residue=0;                       /* rounding accumulator  */
6833
6834  /* Allocate storage for the returned decNumber, big enough for the  */
6835  /* length specified by the context  */
6836  res=(decNumber *)malloc(sizeof(decNumber)
6837                          +(D2U(set->digits)-1)*sizeof(Unit));
6838  if (res==NULL) {
6839    *status|=DEC_Insufficient_storage;
6840    return NULL;
6841    }
6842  decCopyFit(res, dn, set, &residue, &newstatus);
6843  decApplyRound(res, set, residue, &newstatus);
6844
6845  /* If that set Inexact then "lost digits" is raised...  */
6846  if (newstatus & DEC_Inexact) newstatus|=DEC_Lost_digits;
6847  *status|=newstatus;
6848  return res;
6849  } /* decRoundOperand  */
6850#endif
6851
6852/* ------------------------------------------------------------------ */
6853/* decCopyFit -- copy a number, truncating the coefficient if needed  */
6854/*                                                                    */
6855/*   dest is the target decNumber                                     */
6856/*   src  is the source decNumber                                     */
6857/*   set is the context [used for length (digits) and rounding mode]  */
6858/*   residue is the residue accumulator                               */
6859/*   status contains the current status to be updated                 */
6860/*                                                                    */
6861/* (dest==src is allowed and will be a no-op if fits)                 */
6862/* All fields are updated as required.                                */
6863/* ------------------------------------------------------------------ */
6864static void decCopyFit(decNumber *dest, const decNumber *src,
6865                       decContext *set, Int *residue, uInt *status) {
6866  dest->bits=src->bits;
6867  dest->exponent=src->exponent;
6868  decSetCoeff(dest, set, src->lsu, src->digits, residue, status);
6869  } /* decCopyFit  */
6870
6871/* ------------------------------------------------------------------ */
6872/* decSetCoeff -- set the coefficient of a number                     */
6873/*                                                                    */
6874/*   dn    is the number whose coefficient array is to be set.        */
6875/*         It must have space for set->digits digits                  */
6876/*   set   is the context [for size]                                  */
6877/*   lsu   -> lsu of the source coefficient [may be dn->lsu]          */
6878/*   len   is digits in the source coefficient [may be dn->digits]    */
6879/*   residue is the residue accumulator.  This has values as in       */
6880/*         decApplyRound, and will be unchanged unless the            */
6881/*         target size is less than len.  In this case, the           */
6882/*         coefficient is truncated and the residue is updated to     */
6883/*         reflect the previous residue and the dropped digits.       */
6884/*   status is the status accumulator, as usual                       */
6885/*                                                                    */
6886/* The coefficient may already be in the number, or it can be an      */
6887/* external intermediate array.  If it is in the number, lsu must ==  */
6888/* dn->lsu and len must == dn->digits.                                */
6889/*                                                                    */
6890/* Note that the coefficient length (len) may be < set->digits, and   */
6891/* in this case this merely copies the coefficient (or is a no-op     */
6892/* if dn->lsu==lsu).                                                  */
6893/*                                                                    */
6894/* Note also that (only internally, from decQuantizeOp and            */
6895/* decSetSubnormal) the value of set->digits may be less than one,    */
6896/* indicating a round to left.  This routine handles that case        */
6897/* correctly; caller ensures space.                                   */
6898/*                                                                    */
6899/* dn->digits, dn->lsu (and as required), and dn->exponent are        */
6900/* updated as necessary.   dn->bits (sign) is unchanged.              */
6901/*                                                                    */
6902/* DEC_Rounded status is set if any digits are discarded.             */
6903/* DEC_Inexact status is set if any non-zero digits are discarded, or */
6904/*                       incoming residue was non-0 (implies rounded) */
6905/* ------------------------------------------------------------------ */
6906/* mapping array: maps 0-9 to canonical residues, so that a residue  */
6907/* can be adjusted in the range [-1, +1] and achieve correct rounding  */
6908/*                             0  1  2  3  4  5  6  7  8  9  */
6909static const uByte resmap[10]={0, 3, 3, 3, 3, 5, 7, 7, 7, 7};
6910static void decSetCoeff(decNumber *dn, decContext *set, const Unit *lsu,
6911                        Int len, Int *residue, uInt *status) {
6912  Int   discard;              /* number of digits to discard  */
6913  uInt  cut;                  /* cut point in Unit  */
6914  const Unit *up;             /* work  */
6915  Unit  *target;              /* ..  */
6916  Int   count;                /* ..  */
6917  #if DECDPUN<=4
6918  uInt  temp;                 /* ..  */
6919  #endif
6920
6921  discard=len-set->digits;    /* digits to discard  */
6922  if (discard<=0) {           /* no digits are being discarded  */
6923    if (dn->lsu!=lsu) {       /* copy needed  */
6924      /* copy the coefficient array to the result number; no shift needed  */
6925      count=len;              /* avoids D2U  */
6926      up=lsu;
6927      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6928        *target=*up;
6929      dn->digits=len;         /* set the new length  */
6930      }
6931    /* dn->exponent and residue are unchanged, record any inexactitude  */
6932    if (*residue!=0) *status|=(DEC_Inexact | DEC_Rounded);
6933    return;
6934    }
6935
6936  /* some digits must be discarded ...  */
6937  dn->exponent+=discard;      /* maintain numerical value  */
6938  *status|=DEC_Rounded;       /* accumulate Rounded status  */
6939  if (*residue>1) *residue=1; /* previous residue now to right, so reduce  */
6940
6941  if (discard>len) {          /* everything, +1, is being discarded  */
6942    /* guard digit is 0  */
6943    /* residue is all the number [NB could be all 0s]  */
6944    if (*residue<=0) {        /* not already positive  */
6945      count=len;              /* avoids D2U  */
6946      for (up=lsu; count>0; up++, count-=DECDPUN) if (*up!=0) { /* found non-0  */
6947        *residue=1;
6948        break;                /* no need to check any others  */
6949        }
6950      }
6951    if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
6952    *dn->lsu=0;               /* coefficient will now be 0  */
6953    dn->digits=1;             /* ..  */
6954    return;
6955    } /* total discard  */
6956
6957  /* partial discard [most common case]  */
6958  /* here, at least the first (most significant) discarded digit exists  */
6959
6960  /* spin up the number, noting residue during the spin, until get to  */
6961  /* the Unit with the first discarded digit.  When reach it, extract  */
6962  /* it and remember its position  */
6963  count=0;
6964  for (up=lsu;; up++) {
6965    count+=DECDPUN;
6966    if (count>=discard) break; /* full ones all checked  */
6967    if (*up!=0) *residue=1;
6968    } /* up  */
6969
6970  /* here up -> Unit with first discarded digit  */
6971  cut=discard-(count-DECDPUN)-1;
6972  if (cut==DECDPUN-1) {       /* unit-boundary case (fast)  */
6973    Unit half=(Unit)powers[DECDPUN]>>1;
6974    /* set residue directly  */
6975    if (*up>=half) {
6976      if (*up>half) *residue=7;
6977      else *residue+=5;       /* add sticky bit  */
6978      }
6979     else { /* <half  */
6980      if (*up!=0) *residue=3; /* [else is 0, leave as sticky bit]  */
6981      }
6982    if (set->digits<=0) {     /* special for Quantize/Subnormal :-(  */
6983      *dn->lsu=0;             /* .. result is 0  */
6984      dn->digits=1;           /* ..  */
6985      }
6986     else {                   /* shift to least  */
6987      count=set->digits;      /* now digits to end up with  */
6988      dn->digits=count;       /* set the new length  */
6989      up++;                   /* move to next  */
6990      /* on unit boundary, so shift-down copy loop is simple  */
6991      for (target=dn->lsu; count>0; target++, up++, count-=DECDPUN)
6992        *target=*up;
6993      }
6994    } /* unit-boundary case  */
6995
6996   else { /* discard digit is in low digit(s), and not top digit  */
6997    uInt  discard1;                /* first discarded digit  */
6998    uInt  quot, rem;               /* for divisions  */
6999    if (cut==0) quot=*up;          /* is at bottom of unit  */
7000     else /* cut>0 */ {            /* it's not at bottom of unit  */
7001      #if DECDPUN<=4
7002        quot=QUOT10(*up, cut);
7003        rem=*up-quot*powers[cut];
7004      #else
7005        rem=*up%powers[cut];
7006        quot=*up/powers[cut];
7007      #endif
7008      if (rem!=0) *residue=1;
7009      }
7010    /* discard digit is now at bottom of quot  */
7011    #if DECDPUN<=4
7012      temp=(quot*6554)>>16;        /* fast /10  */
7013      /* Vowels algorithm here not a win (9 instructions)  */
7014      discard1=quot-X10(temp);
7015      quot=temp;
7016    #else
7017      discard1=quot%10;
7018      quot=quot/10;
7019    #endif
7020    /* here, discard1 is the guard digit, and residue is everything  */
7021    /* else [use mapping array to accumulate residue safely]  */
7022    *residue+=resmap[discard1];
7023    cut++;                         /* update cut  */
7024    /* here: up -> Unit of the array with bottom digit  */
7025    /*       cut is the division point for each Unit  */
7026    /*       quot holds the uncut high-order digits for the current unit  */
7027    if (set->digits<=0) {          /* special for Quantize/Subnormal :-(  */
7028      *dn->lsu=0;                  /* .. result is 0  */
7029      dn->digits=1;                /* ..  */
7030      }
7031     else {                        /* shift to least needed  */
7032      count=set->digits;           /* now digits to end up with  */
7033      dn->digits=count;            /* set the new length  */
7034      /* shift-copy the coefficient array to the result number  */
7035      for (target=dn->lsu; ; target++) {
7036        *target=(Unit)quot;
7037        count-=(DECDPUN-cut);
7038        if (count<=0) break;
7039        up++;
7040        quot=*up;
7041        #if DECDPUN<=4
7042          quot=QUOT10(quot, cut);
7043          rem=*up-quot*powers[cut];
7044        #else
7045          rem=quot%powers[cut];
7046          quot=quot/powers[cut];
7047        #endif
7048        *target=(Unit)(*target+rem*powers[DECDPUN-cut]);
7049        count-=cut;
7050        if (count<=0) break;
7051        } /* shift-copy loop  */
7052      } /* shift to least  */
7053    } /* not unit boundary  */
7054
7055  if (*residue!=0) *status|=DEC_Inexact; /* record inexactitude  */
7056  return;
7057  } /* decSetCoeff  */
7058
7059/* ------------------------------------------------------------------ */
7060/* decApplyRound -- apply pending rounding to a number                */
7061/*                                                                    */
7062/*   dn    is the number, with space for set->digits digits           */
7063/*   set   is the context [for size and rounding mode]                */
7064/*   residue indicates pending rounding, being any accumulated        */
7065/*         guard and sticky information.  It may be:                  */
7066/*         6-9: rounding digit is >5                                  */
7067/*         5:   rounding digit is exactly half-way                    */
7068/*         1-4: rounding digit is <5 and >0                           */
7069/*         0:   the coefficient is exact                              */
7070/*        -1:   as 1, but the hidden digits are subtractive, that     */
7071/*              is, of the opposite sign to dn.  In this case the     */
7072/*              coefficient must be non-0.  This case occurs when     */
7073/*              subtracting a small number (which can be reduced to   */
7074/*              a sticky bit); see decAddOp.                          */
7075/*   status is the status accumulator, as usual                       */
7076/*                                                                    */
7077/* This routine applies rounding while keeping the length of the      */
7078/* coefficient constant.  The exponent and status are unchanged       */
7079/* except if:                                                         */
7080/*                                                                    */
7081/*   -- the coefficient was increased and is all nines (in which      */
7082/*      case Overflow could occur, and is handled directly here so    */
7083/*      the caller does not need to re-test for overflow)             */
7084/*                                                                    */
7085/*   -- the coefficient was decreased and becomes all nines (in which */
7086/*      case Underflow could occur, and is also handled directly).    */
7087/*                                                                    */
7088/* All fields in dn are updated as required.                          */
7089/*                                                                    */
7090/* ------------------------------------------------------------------ */
7091static void decApplyRound(decNumber *dn, decContext *set, Int residue,
7092                          uInt *status) {
7093  Int  bump;                  /* 1 if coefficient needs to be incremented  */
7094                              /* -1 if coefficient needs to be decremented  */
7095
7096  if (residue==0) return;     /* nothing to apply  */
7097
7098  bump=0;                     /* assume a smooth ride  */
7099
7100  /* now decide whether, and how, to round, depending on mode  */
7101  switch (set->round) {
7102    case DEC_ROUND_05UP: {    /* round zero or five up (for reround)  */
7103      /* This is the same as DEC_ROUND_DOWN unless there is a  */
7104      /* positive residue and the lsd of dn is 0 or 5, in which case  */
7105      /* it is bumped; when residue is <0, the number is therefore  */
7106      /* bumped down unless the final digit was 1 or 6 (in which  */
7107      /* case it is bumped down and then up -- a no-op)  */
7108      Int lsd5=*dn->lsu%5;     /* get lsd and quintate  */
7109      if (residue<0 && lsd5!=1) bump=-1;
7110       else if (residue>0 && lsd5==0) bump=1;
7111      /* [bump==1 could be applied directly; use common path for clarity]  */
7112      break;} /* r-05  */
7113
7114    case DEC_ROUND_DOWN: {
7115      /* no change, except if negative residue  */
7116      if (residue<0) bump=-1;
7117      break;} /* r-d  */
7118
7119    case DEC_ROUND_HALF_DOWN: {
7120      if (residue>5) bump=1;
7121      break;} /* r-h-d  */
7122
7123    case DEC_ROUND_HALF_EVEN: {
7124      if (residue>5) bump=1;            /* >0.5 goes up  */
7125       else if (residue==5) {           /* exactly 0.5000...  */
7126        /* 0.5 goes up iff [new] lsd is odd  */
7127        if (*dn->lsu & 0x01) bump=1;
7128        }
7129      break;} /* r-h-e  */
7130
7131    case DEC_ROUND_HALF_UP: {
7132      if (residue>=5) bump=1;
7133      break;} /* r-h-u  */
7134
7135    case DEC_ROUND_UP: {
7136      if (residue>0) bump=1;
7137      break;} /* r-u  */
7138
7139    case DEC_ROUND_CEILING: {
7140      /* same as _UP for positive numbers, and as _DOWN for negatives  */
7141      /* [negative residue cannot occur on 0]  */
7142      if (decNumberIsNegative(dn)) {
7143        if (residue<0) bump=-1;
7144        }
7145       else {
7146        if (residue>0) bump=1;
7147        }
7148      break;} /* r-c  */
7149
7150    case DEC_ROUND_FLOOR: {
7151      /* same as _UP for negative numbers, and as _DOWN for positive  */
7152      /* [negative residue cannot occur on 0]  */
7153      if (!decNumberIsNegative(dn)) {
7154        if (residue<0) bump=-1;
7155        }
7156       else {
7157        if (residue>0) bump=1;
7158        }
7159      break;} /* r-f  */
7160
7161    default: {      /* e.g., DEC_ROUND_MAX  */
7162      *status|=DEC_Invalid_context;
7163      #if DECTRACE || (DECCHECK && DECVERB)
7164      printf("Unknown rounding mode: %d\n", set->round);
7165      #endif
7166      break;}
7167    } /* switch  */
7168
7169  /* now bump the number, up or down, if need be  */
7170  if (bump==0) return;                       /* no action required  */
7171
7172  /* Simply use decUnitAddSub unless bumping up and the number is  */
7173  /* all nines.  In this special case set to 100... explicitly  */
7174  /* and adjust the exponent by one (as otherwise could overflow  */
7175  /* the array)  */
7176  /* Similarly handle all-nines result if bumping down.  */
7177  if (bump>0) {
7178    Unit *up;                                /* work  */
7179    uInt count=dn->digits;                   /* digits to be checked  */
7180    for (up=dn->lsu; ; up++) {
7181      if (count<=DECDPUN) {
7182        /* this is the last Unit (the msu)  */
7183        if (*up!=powers[count]-1) break;     /* not still 9s  */
7184        /* here if it, too, is all nines  */
7185        *up=(Unit)powers[count-1];           /* here 999 -> 100 etc.  */
7186        for (up=up-1; up>=dn->lsu; up--) *up=0; /* others all to 0  */
7187        dn->exponent++;                      /* and bump exponent  */
7188        /* [which, very rarely, could cause Overflow...]  */
7189        if ((dn->exponent+dn->digits)>set->emax+1) {
7190          decSetOverflow(dn, set, status);
7191          }
7192        return;                              /* done  */
7193        }
7194      /* a full unit to check, with more to come  */
7195      if (*up!=DECDPUNMAX) break;            /* not still 9s  */
7196      count-=DECDPUN;
7197      } /* up  */
7198    } /* bump>0  */
7199   else {                                    /* -1  */
7200    /* here checking for a pre-bump of 1000... (leading 1, all  */
7201    /* other digits zero)  */
7202    Unit *up, *sup;                          /* work  */
7203    uInt count=dn->digits;                   /* digits to be checked  */
7204    for (up=dn->lsu; ; up++) {
7205      if (count<=DECDPUN) {
7206        /* this is the last Unit (the msu)  */
7207        if (*up!=powers[count-1]) break;     /* not 100..  */
7208        /* here if have the 1000... case  */
7209        sup=up;                              /* save msu pointer  */
7210        *up=(Unit)powers[count]-1;           /* here 100 in msu -> 999  */
7211        /* others all to all-nines, too  */
7212        for (up=up-1; up>=dn->lsu; up--) *up=(Unit)powers[DECDPUN]-1;
7213        dn->exponent--;                      /* and bump exponent  */
7214
7215        /* iff the number was at the subnormal boundary (exponent=etiny)  */
7216        /* then the exponent is now out of range, so it will in fact get  */
7217        /* clamped to etiny and the final 9 dropped.  */
7218        /* printf(">> emin=%d exp=%d sdig=%d\n", set->emin,  */
7219        /*        dn->exponent, set->digits);  */
7220        if (dn->exponent+1==set->emin-set->digits+1) {
7221          if (count==1 && dn->digits==1) *sup=0;  /* here 9 -> 0[.9]  */
7222           else {
7223            *sup=(Unit)powers[count-1]-1;    /* here 999.. in msu -> 99..  */
7224            dn->digits--;
7225            }
7226          dn->exponent++;
7227          *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7228          }
7229        return;                              /* done  */
7230        }
7231
7232      /* a full unit to check, with more to come  */
7233      if (*up!=0) break;                     /* not still 0s  */
7234      count-=DECDPUN;
7235      } /* up  */
7236
7237    } /* bump<0  */
7238
7239  /* Actual bump needed.  Do it.  */
7240  decUnitAddSub(dn->lsu, D2U(dn->digits), uarrone, 1, 0, dn->lsu, bump);
7241  } /* decApplyRound  */
7242
7243#if DECSUBSET
7244/* ------------------------------------------------------------------ */
7245/* decFinish -- finish processing a number                            */
7246/*                                                                    */
7247/*   dn is the number                                                 */
7248/*   set is the context                                               */
7249/*   residue is the rounding accumulator (as in decApplyRound)        */
7250/*   status is the accumulator                                        */
7251/*                                                                    */
7252/* This finishes off the current number by:                           */
7253/*    1. If not extended:                                             */
7254/*       a. Converting a zero result to clean '0'                     */
7255/*       b. Reducing positive exponents to 0, if would fit in digits  */
7256/*    2. Checking for overflow and subnormals (always)                */
7257/* Note this is just Finalize when no subset arithmetic.              */
7258/* All fields are updated as required.                                */
7259/* ------------------------------------------------------------------ */
7260static void decFinish(decNumber *dn, decContext *set, Int *residue,
7261                      uInt *status) {
7262  if (!set->extended) {
7263    if ISZERO(dn) {                /* value is zero  */
7264      dn->exponent=0;              /* clean exponent ..  */
7265      dn->bits=0;                  /* .. and sign  */
7266      return;                      /* no error possible  */
7267      }
7268    if (dn->exponent>=0) {         /* non-negative exponent  */
7269      /* >0; reduce to integer if possible  */
7270      if (set->digits >= (dn->exponent+dn->digits)) {
7271        dn->digits=decShiftToMost(dn->lsu, dn->digits, dn->exponent);
7272        dn->exponent=0;
7273        }
7274      }
7275    } /* !extended  */
7276
7277  decFinalize(dn, set, residue, status);
7278  } /* decFinish  */
7279#endif
7280
7281/* ------------------------------------------------------------------ */
7282/* decFinalize -- final check, clamp, and round of a number           */
7283/*                                                                    */
7284/*   dn is the number                                                 */
7285/*   set is the context                                               */
7286/*   residue is the rounding accumulator (as in decApplyRound)        */
7287/*   status is the status accumulator                                 */
7288/*                                                                    */
7289/* This finishes off the current number by checking for subnormal     */
7290/* results, applying any pending rounding, checking for overflow,     */
7291/* and applying any clamping.                                         */
7292/* Underflow and overflow conditions are raised as appropriate.       */
7293/* All fields are updated as required.                                */
7294/* ------------------------------------------------------------------ */
7295static void decFinalize(decNumber *dn, decContext *set, Int *residue,
7296                        uInt *status) {
7297  Int shift;                            /* shift needed if clamping  */
7298  Int tinyexp=set->emin-dn->digits+1;   /* precalculate subnormal boundary  */
7299
7300  /* Must be careful, here, when checking the exponent as the  */
7301  /* adjusted exponent could overflow 31 bits [because it may already  */
7302  /* be up to twice the expected].  */
7303
7304  /* First test for subnormal.  This must be done before any final  */
7305  /* round as the result could be rounded to Nmin or 0.  */
7306  if (dn->exponent<=tinyexp) {          /* prefilter  */
7307    Int comp;
7308    decNumber nmin;
7309    /* A very nasty case here is dn == Nmin and residue<0  */
7310    if (dn->exponent<tinyexp) {
7311      /* Go handle subnormals; this will apply round if needed.  */
7312      decSetSubnormal(dn, set, residue, status);
7313      return;
7314      }
7315    /* Equals case: only subnormal if dn=Nmin and negative residue  */
7316    uprv_decNumberZero(&nmin);
7317    nmin.lsu[0]=1;
7318    nmin.exponent=set->emin;
7319    comp=decCompare(dn, &nmin, 1);                /* (signless compare)  */
7320    if (comp==BADINT) {                           /* oops  */
7321      *status|=DEC_Insufficient_storage;          /* abandon...  */
7322      return;
7323      }
7324    if (*residue<0 && comp==0) {                  /* neg residue and dn==Nmin  */
7325      decApplyRound(dn, set, *residue, status);   /* might force down  */
7326      decSetSubnormal(dn, set, residue, status);
7327      return;
7328      }
7329    }
7330
7331  /* now apply any pending round (this could raise overflow).  */
7332  if (*residue!=0) decApplyRound(dn, set, *residue, status);
7333
7334  /* Check for overflow [redundant in the 'rare' case] or clamp  */
7335  if (dn->exponent<=set->emax-set->digits+1) return;   /* neither needed  */
7336
7337
7338  /* here when might have an overflow or clamp to do  */
7339  if (dn->exponent>set->emax-dn->digits+1) {           /* too big  */
7340    decSetOverflow(dn, set, status);
7341    return;
7342    }
7343  /* here when the result is normal but in clamp range  */
7344  if (!set->clamp) return;
7345
7346  /* here when need to apply the IEEE exponent clamp (fold-down)  */
7347  shift=dn->exponent-(set->emax-set->digits+1);
7348
7349  /* shift coefficient (if non-zero)  */
7350  if (!ISZERO(dn)) {
7351    dn->digits=decShiftToMost(dn->lsu, dn->digits, shift);
7352    }
7353  dn->exponent-=shift;   /* adjust the exponent to match  */
7354  *status|=DEC_Clamped;  /* and record the dirty deed  */
7355  return;
7356  } /* decFinalize  */
7357
7358/* ------------------------------------------------------------------ */
7359/* decSetOverflow -- set number to proper overflow value              */
7360/*                                                                    */
7361/*   dn is the number (used for sign [only] and result)               */
7362/*   set is the context [used for the rounding mode, etc.]            */
7363/*   status contains the current status to be updated                 */
7364/*                                                                    */
7365/* This sets the sign of a number and sets its value to either        */
7366/* Infinity or the maximum finite value, depending on the sign of     */
7367/* dn and the rounding mode, following IEEE 754 rules.                */
7368/* ------------------------------------------------------------------ */
7369static void decSetOverflow(decNumber *dn, decContext *set, uInt *status) {
7370  Flag needmax=0;                  /* result is maximum finite value  */
7371  uByte sign=dn->bits&DECNEG;      /* clean and save sign bit  */
7372
7373  if (ISZERO(dn)) {                /* zero does not overflow magnitude  */
7374    Int emax=set->emax;                      /* limit value  */
7375    if (set->clamp) emax-=set->digits-1;     /* lower if clamping  */
7376    if (dn->exponent>emax) {                 /* clamp required  */
7377      dn->exponent=emax;
7378      *status|=DEC_Clamped;
7379      }
7380    return;
7381    }
7382
7383  uprv_decNumberZero(dn);
7384  switch (set->round) {
7385    case DEC_ROUND_DOWN: {
7386      needmax=1;                   /* never Infinity  */
7387      break;} /* r-d  */
7388    case DEC_ROUND_05UP: {
7389      needmax=1;                   /* never Infinity  */
7390      break;} /* r-05  */
7391    case DEC_ROUND_CEILING: {
7392      if (sign) needmax=1;         /* Infinity if non-negative  */
7393      break;} /* r-c  */
7394    case DEC_ROUND_FLOOR: {
7395      if (!sign) needmax=1;        /* Infinity if negative  */
7396      break;} /* r-f  */
7397    default: break;                /* Infinity in all other cases  */
7398    }
7399  if (needmax) {
7400    decSetMaxValue(dn, set);
7401    dn->bits=sign;                 /* set sign  */
7402    }
7403   else dn->bits=sign|DECINF;      /* Value is +/-Infinity  */
7404  *status|=DEC_Overflow | DEC_Inexact | DEC_Rounded;
7405  } /* decSetOverflow  */
7406
7407/* ------------------------------------------------------------------ */
7408/* decSetMaxValue -- set number to +Nmax (maximum normal value)       */
7409/*                                                                    */
7410/*   dn is the number to set                                          */
7411/*   set is the context [used for digits and emax]                    */
7412/*                                                                    */
7413/* This sets the number to the maximum positive value.                */
7414/* ------------------------------------------------------------------ */
7415static void decSetMaxValue(decNumber *dn, decContext *set) {
7416  Unit *up;                        /* work  */
7417  Int count=set->digits;           /* nines to add  */
7418  dn->digits=count;
7419  /* fill in all nines to set maximum value  */
7420  for (up=dn->lsu; ; up++) {
7421    if (count>DECDPUN) *up=DECDPUNMAX;  /* unit full o'nines  */
7422     else {                             /* this is the msu  */
7423      *up=(Unit)(powers[count]-1);
7424      break;
7425      }
7426    count-=DECDPUN;                /* filled those digits  */
7427    } /* up  */
7428  dn->bits=0;                      /* + sign  */
7429  dn->exponent=set->emax-set->digits+1;
7430  } /* decSetMaxValue  */
7431
7432/* ------------------------------------------------------------------ */
7433/* decSetSubnormal -- process value whose exponent is <Emin           */
7434/*                                                                    */
7435/*   dn is the number (used as input as well as output; it may have   */
7436/*         an allowed subnormal value, which may need to be rounded)  */
7437/*   set is the context [used for the rounding mode]                  */
7438/*   residue is any pending residue                                   */
7439/*   status contains the current status to be updated                 */
7440/*                                                                    */
7441/* If subset mode, set result to zero and set Underflow flags.        */
7442/*                                                                    */
7443/* Value may be zero with a low exponent; this does not set Subnormal */
7444/* but the exponent will be clamped to Etiny.                         */
7445/*                                                                    */
7446/* Otherwise ensure exponent is not out of range, and round as        */
7447/* necessary.  Underflow is set if the result is Inexact.             */
7448/* ------------------------------------------------------------------ */
7449static void decSetSubnormal(decNumber *dn, decContext *set, Int *residue,
7450                            uInt *status) {
7451  decContext workset;         /* work  */
7452  Int        etiny, adjust;   /* ..  */
7453
7454  #if DECSUBSET
7455  /* simple set to zero and 'hard underflow' for subset  */
7456  if (!set->extended) {
7457    uprv_decNumberZero(dn);
7458    /* always full overflow  */
7459    *status|=DEC_Underflow | DEC_Subnormal | DEC_Inexact | DEC_Rounded;
7460    return;
7461    }
7462  #endif
7463
7464  /* Full arithmetic -- allow subnormals, rounded to minimum exponent  */
7465  /* (Etiny) if needed  */
7466  etiny=set->emin-(set->digits-1);      /* smallest allowed exponent  */
7467
7468  if ISZERO(dn) {                       /* value is zero  */
7469    /* residue can never be non-zero here  */
7470    #if DECCHECK
7471      if (*residue!=0) {
7472        printf("++ Subnormal 0 residue %ld\n", (LI)*residue);
7473        *status|=DEC_Invalid_operation;
7474        }
7475    #endif
7476    if (dn->exponent<etiny) {           /* clamp required  */
7477      dn->exponent=etiny;
7478      *status|=DEC_Clamped;
7479      }
7480    return;
7481    }
7482
7483  *status|=DEC_Subnormal;               /* have a non-zero subnormal  */
7484  adjust=etiny-dn->exponent;            /* calculate digits to remove  */
7485  if (adjust<=0) {                      /* not out of range; unrounded  */
7486    /* residue can never be non-zero here, except in the Nmin-residue  */
7487    /* case (which is a subnormal result), so can take fast-path here  */
7488    /* it may already be inexact (from setting the coefficient)  */
7489    if (*status&DEC_Inexact) *status|=DEC_Underflow;
7490    return;
7491    }
7492
7493  /* adjust>0, so need to rescale the result so exponent becomes Etiny  */
7494  /* [this code is similar to that in rescale]  */
7495  workset=*set;                         /* clone rounding, etc.  */
7496  workset.digits=dn->digits-adjust;     /* set requested length  */
7497  workset.emin-=adjust;                 /* and adjust emin to match  */
7498  /* [note that the latter can be <1, here, similar to Rescale case]  */
7499  decSetCoeff(dn, &workset, dn->lsu, dn->digits, residue, status);
7500  decApplyRound(dn, &workset, *residue, status);
7501
7502  /* Use 754 default rule: Underflow is set iff Inexact  */
7503  /* [independent of whether trapped]  */
7504  if (*status&DEC_Inexact) *status|=DEC_Underflow;
7505
7506  /* if rounded up a 999s case, exponent will be off by one; adjust  */
7507  /* back if so [it will fit, because it was shortened earlier]  */
7508  if (dn->exponent>etiny) {
7509    dn->digits=decShiftToMost(dn->lsu, dn->digits, 1);
7510    dn->exponent--;                     /* (re)adjust the exponent.  */
7511    }
7512
7513  /* if rounded to zero, it is by definition clamped...  */
7514  if (ISZERO(dn)) *status|=DEC_Clamped;
7515  } /* decSetSubnormal  */
7516
7517/* ------------------------------------------------------------------ */
7518/* decCheckMath - check entry conditions for a math function          */
7519/*                                                                    */
7520/*   This checks the context and the operand                          */
7521/*                                                                    */
7522/*   rhs is the operand to check                                      */
7523/*   set is the context to check                                      */
7524/*   status is unchanged if both are good                             */
7525/*                                                                    */
7526/* returns non-zero if status is changed, 0 otherwise                 */
7527/*                                                                    */
7528/* Restrictions enforced:                                             */
7529/*                                                                    */
7530/*   digits, emax, and -emin in the context must be less than         */
7531/*   DEC_MAX_MATH (999999), and A must be within these bounds if      */
7532/*   non-zero.  Invalid_operation is set in the status if a           */
7533/*   restriction is violated.                                         */
7534/* ------------------------------------------------------------------ */
7535static uInt decCheckMath(const decNumber *rhs, decContext *set,
7536                         uInt *status) {
7537  uInt save=*status;                         /* record  */
7538  if (set->digits>DEC_MAX_MATH
7539   || set->emax>DEC_MAX_MATH
7540   || -set->emin>DEC_MAX_MATH) *status|=DEC_Invalid_context;
7541   else if ((rhs->digits>DEC_MAX_MATH
7542     || rhs->exponent+rhs->digits>DEC_MAX_MATH+1
7543     || rhs->exponent+rhs->digits<2*(1-DEC_MAX_MATH))
7544     && !ISZERO(rhs)) *status|=DEC_Invalid_operation;
7545  return (*status!=save);
7546  } /* decCheckMath  */
7547
7548/* ------------------------------------------------------------------ */
7549/* decGetInt -- get integer from a number                             */
7550/*                                                                    */
7551/*   dn is the number [which will not be altered]                     */
7552/*                                                                    */
7553/*   returns one of:                                                  */
7554/*     BADINT if there is a non-zero fraction                         */
7555/*     the converted integer                                          */
7556/*     BIGEVEN if the integer is even and magnitude > 2*10**9         */
7557/*     BIGODD  if the integer is odd  and magnitude > 2*10**9         */
7558/*                                                                    */
7559/* This checks and gets a whole number from the input decNumber.      */
7560/* The sign can be determined from dn by the caller when BIGEVEN or   */
7561/* BIGODD is returned.                                                */
7562/* ------------------------------------------------------------------ */
7563static Int decGetInt(const decNumber *dn) {
7564  Int  theInt;                          /* result accumulator  */
7565  const Unit *up;                       /* work  */
7566  Int  got;                             /* digits (real or not) processed  */
7567  Int  ilength=dn->digits+dn->exponent; /* integral length  */
7568  Flag neg=decNumberIsNegative(dn);     /* 1 if -ve  */
7569
7570  /* The number must be an integer that fits in 10 digits  */
7571  /* Assert, here, that 10 is enough for any rescale Etiny  */
7572  #if DEC_MAX_EMAX > 999999999
7573    #error GetInt may need updating [for Emax]
7574  #endif
7575  #if DEC_MIN_EMIN < -999999999
7576    #error GetInt may need updating [for Emin]
7577  #endif
7578  if (ISZERO(dn)) return 0;             /* zeros are OK, with any exponent  */
7579
7580  up=dn->lsu;                           /* ready for lsu  */
7581  theInt=0;                             /* ready to accumulate  */
7582  if (dn->exponent>=0) {                /* relatively easy  */
7583    /* no fractional part [usual]; allow for positive exponent  */
7584    got=dn->exponent;
7585    }
7586   else { /* -ve exponent; some fractional part to check and discard  */
7587    Int count=-dn->exponent;            /* digits to discard  */
7588    /* spin up whole units until reach the Unit with the unit digit  */
7589    for (; count>=DECDPUN; up++) {
7590      if (*up!=0) return BADINT;        /* non-zero Unit to discard  */
7591      count-=DECDPUN;
7592      }
7593    if (count==0) got=0;                /* [a multiple of DECDPUN]  */
7594     else {                             /* [not multiple of DECDPUN]  */
7595      Int rem;                          /* work  */
7596      /* slice off fraction digits and check for non-zero  */
7597      #if DECDPUN<=4
7598        theInt=QUOT10(*up, count);
7599        rem=*up-theInt*powers[count];
7600      #else
7601        rem=*up%powers[count];          /* slice off discards  */
7602        theInt=*up/powers[count];
7603      #endif
7604      if (rem!=0) return BADINT;        /* non-zero fraction  */
7605      /* it looks good  */
7606      got=DECDPUN-count;                /* number of digits so far  */
7607      up++;                             /* ready for next  */
7608      }
7609    }
7610  /* now it's known there's no fractional part  */
7611
7612  /* tricky code now, to accumulate up to 9.3 digits  */
7613  if (got==0) {theInt=*up; got+=DECDPUN; up++;} /* ensure lsu is there  */
7614
7615  if (ilength<11) {
7616    Int save=theInt;
7617    /* collect any remaining unit(s)  */
7618    for (; got<ilength; up++) {
7619      theInt+=*up*powers[got];
7620      got+=DECDPUN;
7621      }
7622    if (ilength==10) {                  /* need to check for wrap  */
7623      if (theInt/(Int)powers[got-DECDPUN]!=(Int)*(up-1)) ilength=11;
7624         /* [that test also disallows the BADINT result case]  */
7625       else if (neg && theInt>1999999997) ilength=11;
7626       else if (!neg && theInt>999999999) ilength=11;
7627      if (ilength==11) theInt=save;     /* restore correct low bit  */
7628      }
7629    }
7630
7631  if (ilength>10) {                     /* too big  */
7632    if (theInt&1) return BIGODD;        /* bottom bit 1  */
7633    return BIGEVEN;                     /* bottom bit 0  */
7634    }
7635
7636  if (neg) theInt=-theInt;              /* apply sign  */
7637  return theInt;
7638  } /* decGetInt  */
7639
7640/* ------------------------------------------------------------------ */
7641/* decDecap -- decapitate the coefficient of a number                 */
7642/*                                                                    */
7643/*   dn   is the number to be decapitated                             */
7644/*   drop is the number of digits to be removed from the left of dn;  */
7645/*     this must be <= dn->digits (if equal, the coefficient is       */
7646/*     set to 0)                                                      */
7647/*                                                                    */
7648/* Returns dn; dn->digits will be <= the initial digits less drop     */
7649/* (after removing drop digits there may be leading zero digits       */
7650/* which will also be removed).  Only dn->lsu and dn->digits change.  */
7651/* ------------------------------------------------------------------ */
7652static decNumber *decDecap(decNumber *dn, Int drop) {
7653  Unit *msu;                            /* -> target cut point  */
7654  Int cut;                              /* work  */
7655  if (drop>=dn->digits) {               /* losing the whole thing  */
7656    #if DECCHECK
7657    if (drop>dn->digits)
7658      printf("decDecap called with drop>digits [%ld>%ld]\n",
7659             (LI)drop, (LI)dn->digits);
7660    #endif
7661    dn->lsu[0]=0;
7662    dn->digits=1;
7663    return dn;
7664    }
7665  msu=dn->lsu+D2U(dn->digits-drop)-1;   /* -> likely msu  */
7666  cut=MSUDIGITS(dn->digits-drop);       /* digits to be in use in msu  */
7667  if (cut!=DECDPUN) *msu%=powers[cut];  /* clear left digits  */
7668  /* that may have left leading zero digits, so do a proper count...  */
7669  dn->digits=decGetDigits(dn->lsu, msu-dn->lsu+1);
7670  return dn;
7671  } /* decDecap  */
7672
7673/* ------------------------------------------------------------------ */
7674/* decBiStr -- compare string with pairwise options                   */
7675/*                                                                    */
7676/*   targ is the string to compare                                    */
7677/*   str1 is one of the strings to compare against (length may be 0)  */
7678/*   str2 is the other; it must be the same length as str1            */
7679/*                                                                    */
7680/*   returns 1 if strings compare equal, (that is, it is the same     */
7681/*   length as str1 and str2, and each character of targ is in either */
7682/*   str1 or str2 in the corresponding position), or 0 otherwise      */
7683/*                                                                    */
7684/* This is used for generic caseless compare, including the awkward   */
7685/* case of the Turkish dotted and dotless Is.  Use as (for example):  */
7686/*   if (decBiStr(test, "mike", "MIKE")) ...                          */
7687/* ------------------------------------------------------------------ */
7688static Flag decBiStr(const char *targ, const char *str1, const char *str2) {
7689  for (;;targ++, str1++, str2++) {
7690    if (*targ!=*str1 && *targ!=*str2) return 0;
7691    /* *targ has a match in one (or both, if terminator)  */
7692    if (*targ=='\0') break;
7693    } /* forever  */
7694  return 1;
7695  } /* decBiStr  */
7696
7697/* ------------------------------------------------------------------ */
7698/* decNaNs -- handle NaN operand or operands                          */
7699/*                                                                    */
7700/*   res     is the result number                                     */
7701/*   lhs     is the first operand                                     */
7702/*   rhs     is the second operand, or NULL if none                   */
7703/*   context is used to limit payload length                          */
7704/*   status  contains the current status                              */
7705/*   returns res in case convenient                                   */
7706/*                                                                    */
7707/* Called when one or both operands is a NaN, and propagates the      */
7708/* appropriate result to res.  When an sNaN is found, it is changed   */
7709/* to a qNaN and Invalid operation is set.                            */
7710/* ------------------------------------------------------------------ */
7711static decNumber * decNaNs(decNumber *res, const decNumber *lhs,
7712                           const decNumber *rhs, decContext *set,
7713                           uInt *status) {
7714  /* This decision tree ends up with LHS being the source pointer,  */
7715  /* and status updated if need be  */
7716  if (lhs->bits & DECSNAN)
7717    *status|=DEC_Invalid_operation | DEC_sNaN;
7718   else if (rhs==NULL);
7719   else if (rhs->bits & DECSNAN) {
7720    lhs=rhs;
7721    *status|=DEC_Invalid_operation | DEC_sNaN;
7722    }
7723   else if (lhs->bits & DECNAN);
7724   else lhs=rhs;
7725
7726  /* propagate the payload  */
7727  if (lhs->digits<=set->digits) uprv_decNumberCopy(res, lhs); /* easy  */
7728   else { /* too long  */
7729    const Unit *ul;
7730    Unit *ur, *uresp1;
7731    /* copy safe number of units, then decapitate  */
7732    res->bits=lhs->bits;                /* need sign etc.  */
7733    uresp1=res->lsu+D2U(set->digits);
7734    for (ur=res->lsu, ul=lhs->lsu; ur<uresp1; ur++, ul++) *ur=*ul;
7735    res->digits=D2U(set->digits)*DECDPUN;
7736    /* maybe still too long  */
7737    if (res->digits>set->digits) decDecap(res, res->digits-set->digits);
7738    }
7739
7740  res->bits&=~DECSNAN;        /* convert any sNaN to NaN, while  */
7741  res->bits|=DECNAN;          /* .. preserving sign  */
7742  res->exponent=0;            /* clean exponent  */
7743                              /* [coefficient was copied/decapitated]  */
7744  return res;
7745  } /* decNaNs  */
7746
7747/* ------------------------------------------------------------------ */
7748/* decStatus -- apply non-zero status                                 */
7749/*                                                                    */
7750/*   dn     is the number to set if error                             */
7751/*   status contains the current status (not yet in context)          */
7752/*   set    is the context                                            */
7753/*                                                                    */
7754/* If the status is an error status, the number is set to a NaN,      */
7755/* unless the error was an overflow, divide-by-zero, or underflow,    */
7756/* in which case the number will have already been set.               */
7757/*                                                                    */
7758/* The context status is then updated with the new status.  Note that */
7759/* this may raise a signal, so control may never return from this     */
7760/* routine (hence resources must be recovered before it is called).   */
7761/* ------------------------------------------------------------------ */
7762static void decStatus(decNumber *dn, uInt status, decContext *set) {
7763  if (status & DEC_NaNs) {              /* error status -> NaN  */
7764    /* if cause was an sNaN, clear and propagate [NaN is already set up]  */
7765    if (status & DEC_sNaN) status&=~DEC_sNaN;
7766     else {
7767      uprv_decNumberZero(dn);                /* other error: clean throughout  */
7768      dn->bits=DECNAN;                  /* and make a quiet NaN  */
7769      }
7770    }
7771  uprv_decContextSetStatus(set, status);     /* [may not return]  */
7772  return;
7773  } /* decStatus  */
7774
7775/* ------------------------------------------------------------------ */
7776/* decGetDigits -- count digits in a Units array                      */
7777/*                                                                    */
7778/*   uar is the Unit array holding the number (this is often an       */
7779/*          accumulator of some sort)                                 */
7780/*   len is the length of the array in units [>=1]                    */
7781/*                                                                    */
7782/*   returns the number of (significant) digits in the array          */
7783/*                                                                    */
7784/* All leading zeros are excluded, except the last if the array has   */
7785/* only zero Units.                                                   */
7786/* ------------------------------------------------------------------ */
7787/* This may be called twice during some operations.  */
7788static Int decGetDigits(Unit *uar, Int len) {
7789  Unit *up=uar+(len-1);            /* -> msu  */
7790  Int  digits=(len-1)*DECDPUN+1;   /* possible digits excluding msu  */
7791  #if DECDPUN>4
7792  uInt const *pow;                 /* work  */
7793  #endif
7794                                   /* (at least 1 in final msu)  */
7795  #if DECCHECK
7796  if (len<1) printf("decGetDigits called with len<1 [%ld]\n", (LI)len);
7797  #endif
7798
7799  for (; up>=uar; up--) {
7800    if (*up==0) {                  /* unit is all 0s  */
7801      if (digits==1) break;        /* a zero has one digit  */
7802      digits-=DECDPUN;             /* adjust for 0 unit  */
7803      continue;}
7804    /* found the first (most significant) non-zero Unit  */
7805    #if DECDPUN>1                  /* not done yet  */
7806    if (*up<10) break;             /* is 1-9  */
7807    digits++;
7808    #if DECDPUN>2                  /* not done yet  */
7809    if (*up<100) break;            /* is 10-99  */
7810    digits++;
7811    #if DECDPUN>3                  /* not done yet  */
7812    if (*up<1000) break;           /* is 100-999  */
7813    digits++;
7814    #if DECDPUN>4                  /* count the rest ...  */
7815    for (pow=&powers[4]; *up>=*pow; pow++) digits++;
7816    #endif
7817    #endif
7818    #endif
7819    #endif
7820    break;
7821    } /* up  */
7822  return digits;
7823  } /* decGetDigits  */
7824
7825#if DECTRACE | DECCHECK
7826/* ------------------------------------------------------------------ */
7827/* decNumberShow -- display a number [debug aid]                      */
7828/*   dn is the number to show                                         */
7829/*                                                                    */
7830/* Shows: sign, exponent, coefficient (msu first), digits             */
7831/*    or: sign, special-value                                         */
7832/* ------------------------------------------------------------------ */
7833/* this is public so other modules can use it  */
7834void uprv_decNumberShow(const decNumber *dn) {
7835  const Unit *up;                  /* work  */
7836  uInt u, d;                       /* ..  */
7837  Int cut;                         /* ..  */
7838  char isign='+';                  /* main sign  */
7839  if (dn==NULL) {
7840    printf("NULL\n");
7841    return;}
7842  if (decNumberIsNegative(dn)) isign='-';
7843  printf(" >> %c ", isign);
7844  if (dn->bits&DECSPECIAL) {       /* Is a special value  */
7845    if (decNumberIsInfinite(dn)) printf("Infinity");
7846     else {                                  /* a NaN  */
7847      if (dn->bits&DECSNAN) printf("sNaN");  /* signalling NaN  */
7848       else printf("NaN");
7849      }
7850    /* if coefficient and exponent are 0, no more to do  */
7851    if (dn->exponent==0 && dn->digits==1 && *dn->lsu==0) {
7852      printf("\n");
7853      return;}
7854    /* drop through to report other information  */
7855    printf(" ");
7856    }
7857
7858  /* now carefully display the coefficient  */
7859  up=dn->lsu+D2U(dn->digits)-1;         /* msu  */
7860  printf("%ld", (LI)*up);
7861  for (up=up-1; up>=dn->lsu; up--) {
7862    u=*up;
7863    printf(":");
7864    for (cut=DECDPUN-1; cut>=0; cut--) {
7865      d=u/powers[cut];
7866      u-=d*powers[cut];
7867      printf("%ld", (LI)d);
7868      } /* cut  */
7869    } /* up  */
7870  if (dn->exponent!=0) {
7871    char esign='+';
7872    if (dn->exponent<0) esign='-';
7873    printf(" E%c%ld", esign, (LI)abs(dn->exponent));
7874    }
7875  printf(" [%ld]\n", (LI)dn->digits);
7876  } /* decNumberShow  */
7877#endif
7878
7879#if DECTRACE || DECCHECK
7880/* ------------------------------------------------------------------ */
7881/* decDumpAr -- display a unit array [debug/check aid]                */
7882/*   name is a single-character tag name                              */
7883/*   ar   is the array to display                                     */
7884/*   len  is the length of the array in Units                         */
7885/* ------------------------------------------------------------------ */
7886static void decDumpAr(char name, const Unit *ar, Int len) {
7887  Int i;
7888  const char *spec;
7889  #if DECDPUN==9
7890    spec="%09d ";
7891  #elif DECDPUN==8
7892    spec="%08d ";
7893  #elif DECDPUN==7
7894    spec="%07d ";
7895  #elif DECDPUN==6
7896    spec="%06d ";
7897  #elif DECDPUN==5
7898    spec="%05d ";
7899  #elif DECDPUN==4
7900    spec="%04d ";
7901  #elif DECDPUN==3
7902    spec="%03d ";
7903  #elif DECDPUN==2
7904    spec="%02d ";
7905  #else
7906    spec="%d ";
7907  #endif
7908  printf("  :%c: ", name);
7909  for (i=len-1; i>=0; i--) {
7910    if (i==len-1) printf("%ld ", (LI)ar[i]);
7911     else printf(spec, ar[i]);
7912    }
7913  printf("\n");
7914  return;}
7915#endif
7916
7917#if DECCHECK
7918/* ------------------------------------------------------------------ */
7919/* decCheckOperands -- check operand(s) to a routine                  */
7920/*   res is the result structure (not checked; it will be set to      */
7921/*          quiet NaN if error found (and it is not NULL))            */
7922/*   lhs is the first operand (may be DECUNRESU)                      */
7923/*   rhs is the second (may be DECUNUSED)                             */
7924/*   set is the context (may be DECUNCONT)                            */
7925/*   returns 0 if both operands, and the context are clean, or 1      */
7926/*     otherwise (in which case the context will show an error,       */
7927/*     unless NULL).  Note that res is not cleaned; caller should     */
7928/*     handle this so res=NULL case is safe.                          */
7929/* The caller is expected to abandon immediately if 1 is returned.    */
7930/* ------------------------------------------------------------------ */
7931static Flag decCheckOperands(decNumber *res, const decNumber *lhs,
7932                             const decNumber *rhs, decContext *set) {
7933  Flag bad=0;
7934  if (set==NULL) {                 /* oops; hopeless  */
7935    #if DECTRACE || DECVERB
7936    printf("Reference to context is NULL.\n");
7937    #endif
7938    bad=1;
7939    return 1;}
7940   else if (set!=DECUNCONT
7941     && (set->digits<1 || set->round>=DEC_ROUND_MAX)) {
7942    bad=1;
7943    #if DECTRACE || DECVERB
7944    printf("Bad context [digits=%ld round=%ld].\n",
7945           (LI)set->digits, (LI)set->round);
7946    #endif
7947    }
7948   else {
7949    if (res==NULL) {
7950      bad=1;
7951      #if DECTRACE
7952      /* this one not DECVERB as standard tests include NULL  */
7953      printf("Reference to result is NULL.\n");
7954      #endif
7955      }
7956    if (!bad && lhs!=DECUNUSED) bad=(decCheckNumber(lhs));
7957    if (!bad && rhs!=DECUNUSED) bad=(decCheckNumber(rhs));
7958    }
7959  if (bad) {
7960    if (set!=DECUNCONT) uprv_decContextSetStatus(set, DEC_Invalid_operation);
7961    if (res!=DECUNRESU && res!=NULL) {
7962      uprv_decNumberZero(res);
7963      res->bits=DECNAN;       /* qNaN  */
7964      }
7965    }
7966  return bad;
7967  } /* decCheckOperands  */
7968
7969/* ------------------------------------------------------------------ */
7970/* decCheckNumber -- check a number                                   */
7971/*   dn is the number to check                                        */
7972/*   returns 0 if the number is clean, or 1 otherwise                 */
7973/*                                                                    */
7974/* The number is considered valid if it could be a result from some   */
7975/* operation in some valid context.                                   */
7976/* ------------------------------------------------------------------ */
7977static Flag decCheckNumber(const decNumber *dn) {
7978  const Unit *up;             /* work  */
7979  uInt maxuint;               /* ..  */
7980  Int ae, d, digits;          /* ..  */
7981  Int emin, emax;             /* ..  */
7982
7983  if (dn==NULL) {             /* hopeless  */
7984    #if DECTRACE
7985    /* this one not DECVERB as standard tests include NULL  */
7986    printf("Reference to decNumber is NULL.\n");
7987    #endif
7988    return 1;}
7989
7990  /* check special values  */
7991  if (dn->bits & DECSPECIAL) {
7992    if (dn->exponent!=0) {
7993      #if DECTRACE || DECVERB
7994      printf("Exponent %ld (not 0) for a special value [%02x].\n",
7995             (LI)dn->exponent, dn->bits);
7996      #endif
7997      return 1;}
7998
7999    /* 2003.09.08: NaNs may now have coefficients, so next tests Inf only  */
8000    if (decNumberIsInfinite(dn)) {
8001      if (dn->digits!=1) {
8002        #if DECTRACE || DECVERB
8003        printf("Digits %ld (not 1) for an infinity.\n", (LI)dn->digits);
8004        #endif
8005        return 1;}
8006      if (*dn->lsu!=0) {
8007        #if DECTRACE || DECVERB
8008        printf("LSU %ld (not 0) for an infinity.\n", (LI)*dn->lsu);
8009        #endif
8010        decDumpAr('I', dn->lsu, D2U(dn->digits));
8011        return 1;}
8012      } /* Inf  */
8013    /* 2002.12.26: negative NaNs can now appear through proposed IEEE  */
8014    /*             concrete formats (decimal64, etc.).  */
8015    return 0;
8016    }
8017
8018  /* check the coefficient  */
8019  if (dn->digits<1 || dn->digits>DECNUMMAXP) {
8020    #if DECTRACE || DECVERB
8021    printf("Digits %ld in number.\n", (LI)dn->digits);
8022    #endif
8023    return 1;}
8024
8025  d=dn->digits;
8026
8027  for (up=dn->lsu; d>0; up++) {
8028    if (d>DECDPUN) maxuint=DECDPUNMAX;
8029     else {                   /* reached the msu  */
8030      maxuint=powers[d]-1;
8031      if (dn->digits>1 && *up<powers[d-1]) {
8032        #if DECTRACE || DECVERB
8033        printf("Leading 0 in number.\n");
8034        uprv_decNumberShow(dn);
8035        #endif
8036        return 1;}
8037      }
8038    if (*up>maxuint) {
8039      #if DECTRACE || DECVERB
8040      printf("Bad Unit [%08lx] in %ld-digit number at offset %ld [maxuint %ld].\n",
8041              (LI)*up, (LI)dn->digits, (LI)(up-dn->lsu), (LI)maxuint);
8042      #endif
8043      return 1;}
8044    d-=DECDPUN;
8045    }
8046
8047  /* check the exponent.  Note that input operands can have exponents  */
8048  /* which are out of the set->emin/set->emax and set->digits range  */
8049  /* (just as they can have more digits than set->digits).  */
8050  ae=dn->exponent+dn->digits-1;    /* adjusted exponent  */
8051  emax=DECNUMMAXE;
8052  emin=DECNUMMINE;
8053  digits=DECNUMMAXP;
8054  if (ae<emin-(digits-1)) {
8055    #if DECTRACE || DECVERB
8056    printf("Adjusted exponent underflow [%ld].\n", (LI)ae);
8057    uprv_decNumberShow(dn);
8058    #endif
8059    return 1;}
8060  if (ae>+emax) {
8061    #if DECTRACE || DECVERB
8062    printf("Adjusted exponent overflow [%ld].\n", (LI)ae);
8063    uprv_decNumberShow(dn);
8064    #endif
8065    return 1;}
8066
8067  return 0;              /* it's OK  */
8068  } /* decCheckNumber  */
8069
8070/* ------------------------------------------------------------------ */
8071/* decCheckInexact -- check a normal finite inexact result has digits */
8072/*   dn is the number to check                                        */
8073/*   set is the context (for status and precision)                    */
8074/*   sets Invalid operation, etc., if some digits are missing         */
8075/* [this check is not made for DECSUBSET compilation or when          */
8076/* subnormal is not set]                                              */
8077/* ------------------------------------------------------------------ */
8078static void decCheckInexact(const decNumber *dn, decContext *set) {
8079  #if !DECSUBSET && DECEXTFLAG
8080    if ((set->status & (DEC_Inexact|DEC_Subnormal))==DEC_Inexact
8081     && (set->digits!=dn->digits) && !(dn->bits & DECSPECIAL)) {
8082      #if DECTRACE || DECVERB
8083      printf("Insufficient digits [%ld] on normal Inexact result.\n",
8084             (LI)dn->digits);
8085      uprv_decNumberShow(dn);
8086      #endif
8087      uprv_decContextSetStatus(set, DEC_Invalid_operation);
8088      }
8089  #else
8090    /* next is a noop for quiet compiler  */
8091    if (dn!=NULL && dn->digits==0) set->status|=DEC_Invalid_operation;
8092  #endif
8093  return;
8094  } /* decCheckInexact  */
8095#endif
8096
8097#if DECALLOC
8098#undef malloc
8099#undef free
8100/* ------------------------------------------------------------------ */
8101/* decMalloc -- accountable allocation routine                        */
8102/*   n is the number of bytes to allocate                             */
8103/*                                                                    */
8104/* Semantics is the same as the stdlib malloc routine, but bytes      */
8105/* allocated are accounted for globally, and corruption fences are    */
8106/* added before and after the 'actual' storage.                       */
8107/* ------------------------------------------------------------------ */
8108/* This routine allocates storage with an extra twelve bytes; 8 are   */
8109/* at the start and hold:                                             */
8110/*   0-3 the original length requested                                */
8111/*   4-7 buffer corruption detection fence (DECFENCE, x4)             */
8112/* The 4 bytes at the end also hold a corruption fence (DECFENCE, x4) */
8113/* ------------------------------------------------------------------ */
8114static void *decMalloc(size_t n) {
8115  uInt  size=n+12;                 /* true size  */
8116  void  *alloc;                    /* -> allocated storage  */
8117  uByte *b, *b0;                   /* work  */
8118  uInt  uiwork;                    /* for macros  */
8119
8120  alloc=malloc(size);              /* -> allocated storage  */
8121  if (alloc==NULL) return NULL;    /* out of strorage  */
8122  b0=(uByte *)alloc;               /* as bytes  */
8123  decAllocBytes+=n;                /* account for storage  */
8124  UBFROMUI(alloc, n);              /* save n  */
8125  /* printf(" alloc ++ dAB: %ld (%ld)\n", (LI)decAllocBytes, (LI)n);  */
8126  for (b=b0+4; b<b0+8; b++) *b=DECFENCE;
8127  for (b=b0+n+8; b<b0+n+12; b++) *b=DECFENCE;
8128  return b0+8;                     /* -> play area  */
8129  } /* decMalloc  */
8130
8131/* ------------------------------------------------------------------ */
8132/* decFree -- accountable free routine                                */
8133/*   alloc is the storage to free                                     */
8134/*                                                                    */
8135/* Semantics is the same as the stdlib malloc routine, except that    */
8136/* the global storage accounting is updated and the fences are        */
8137/* checked to ensure that no routine has written 'out of bounds'.     */
8138/* ------------------------------------------------------------------ */
8139/* This routine first checks that the fences have not been corrupted. */
8140/* It then frees the storage using the 'truw' storage address (that   */
8141/* is, offset by 8).                                                  */
8142/* ------------------------------------------------------------------ */
8143static void decFree(void *alloc) {
8144  uInt  n;                         /* original length  */
8145  uByte *b, *b0;                   /* work  */
8146  uInt  uiwork;                    /* for macros  */
8147
8148  if (alloc==NULL) return;         /* allowed; it's a nop  */
8149  b0=(uByte *)alloc;               /* as bytes  */
8150  b0-=8;                           /* -> true start of storage  */
8151  n=UBTOUI(b0);                    /* lift length  */
8152  for (b=b0+4; b<b0+8; b++) if (*b!=DECFENCE)
8153    printf("=== Corrupt byte [%02x] at offset %d from %ld ===\n", *b,
8154           b-b0-8, (LI)b0);
8155  for (b=b0+n+8; b<b0+n+12; b++) if (*b!=DECFENCE)
8156    printf("=== Corrupt byte [%02x] at offset +%d from %ld, n=%ld ===\n", *b,
8157           b-b0-8, (LI)b0, (LI)n);
8158  free(b0);                        /* drop the storage  */
8159  decAllocBytes-=n;                /* account for storage  */
8160  /* printf(" free -- dAB: %d (%d)\n", decAllocBytes, -n);  */
8161  } /* decFree  */
8162#define malloc(a) decMalloc(a)
8163#define free(a) decFree(a)
8164#endif
8165